package com.brilliance.isc.common.component;

import com.brilliance.isc.bo.Pty;
import com.brilliance.isc.bo.Sin;
import com.brilliance.isc.common.cache.pty.PtyCacheService;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.mda.dao.PtyMapper;
import com.brilliance.isc.mda.dao.SinMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 客户渠道签约组件
 */
@Component
public class PtySignComponent {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SinMapper sinMapper;

    @Autowired
    private PtyCacheService ptyCacheService;

    @Autowired
    private CodetableService codetableService;

    @Autowired
    private PtyMapper ptyMapper;

    /**
     * 1 - 高新投
     * E - E结算
     * Y - 云平台保函
     * G - 国贸公服
     * @param ptyinr
     * @param channel
     * @return
     */
    public boolean isSignChannel(String ptyinr, String channel) {
        logger.info("获取客户渠道签约信息");
        if (StringUtils.isEmpty(ptyinr)) {
            logger.info("客户信息为空，直接返回");
            return false;
        }
        Pty pty = ptyCacheService.getPtyById(ptyinr);
        if (pty == null) {
            logger.info("查询不到客户信息{}，直接返回", ptyinr);
            return false;
        }
        String channelTxt = codetableService.getTblLabel(channel, "FRMFLG");
        if (StringUtils.isEmpty(channelTxt)) {
            channelTxt = channel;
        }
        logger.info("渠道类型为{}",channelTxt);
        Sin sin = sinMapper.queryByPtyextkeyAndFromflg(pty.getExtkey(), channel);
        if (sin != null && "0".equals(sin.getSinsta())) {
            return true;
        }
        logger.info("查询不到签约信息或者签约信息状态不是已签约");
        return false;
    }


    /**
     * 新国结渠道客户签约信息（接口专用）
     * @param cuscode
     * @param channel
     * @return
     */
    public Sin newSstfSign(String cuscode, String channel) {
        //1、判断客户号是否为空
        logger.info("获取客户渠道签约信息");
        if (StringUtils.isEmpty(cuscode)) {
            logger.info("客户信息为空，直接返回");
            return null;
        }
        //2、查询pty表，判断客户信息是否存在
        Pty pty = ptyMapper.selectByExtkey(cuscode);
        if (pty == null) {
            logger.info("查询不到客户信息{}，直接返回", cuscode);
            return null;
        }
        //3、查询具体的渠道信息
        String channelTxt = codetableService.getTblLabel(channel, "FRMFLG");
        if (StringUtils.isEmpty(channelTxt)) {
            channelTxt = channel;
        }
        logger.info("渠道类型为{}",channelTxt);
        //4、查询客户的签约信息
        Sin sin = sinMapper.queryByPtyextkeyAndFromflg(cuscode, channel);
        if (sin == null) {
            sin = new Sin();
            sin.setPtyextkey(cuscode);
            sin.setFromflg(channel);
        }
        return sin;
    }
}
