package com.brilliance.isc.automatic.cpt.service;

import com.brilliance.isc.automatic.engine.constant.enums.AutoSrcTypeEnum;
import com.brilliance.isc.automatic.engine.constant.enums.AutoStaEnum;
import com.brilliance.isc.automatic.engine.constant.enums.AutoTypeEnum;
import com.brilliance.isc.automatic.engine.flow.AutoFlowHelper;
import com.brilliance.isc.bo.*;
import com.brilliance.isc.bo.auto.AutoFlow;
import com.brilliance.isc.bo.auto.AutoSignCountPty;
import com.brilliance.isc.bo.auto.AutoSignInfo;
import com.brilliance.isc.bo.auto.AutoSignRule;
import com.brilliance.isc.bo.model.Cpdgrp;
import com.brilliance.isc.bo.remit.CptadvAutoStoreBo;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.common.sysmod.SysmodService;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.mda.dao.*;
import com.brilliance.isc.vo.PtsptaInfoVo;
import com.brilliance.isc.vo.PtsptaQueryVo;
import com.brilliance.isc.vo.collection.AutsigQueryVo;
import com.brilliance.isc.vo.collection.AutsigRulQueryVo;
import com.brilliance.mda.runtime.mda.util.Codetables;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Strings;
import com.brilliance.mda.runtime.mda.util.Systems;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.brilliance.mda.runtime.mda.Constants.NULLSTR;

@Service
public class AutoCptAccessService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AutoCptAccessService.class);
    @Resource
    private AutoFlowHelper autoFlowHelper;
    @Autowired
    private SptMapper sptMapper;
    @Autowired
    private QueMapper queMapper;
    @Autowired
    private CndMapper cndMapper;
    @Autowired
    private PtsptaMapper ptsptaMapper;
    @Autowired
    private AtdMapper atdMapper;
    @Autowired
    private AutoSignInfoMapper autoSignInfoMapper;
    @Autowired
    private AutoSignRuleMapper autoSignRuleMapper;
    @Autowired
    private AutoSignCountPtyMapper autoSignCountPtyMapper;
    @Autowired
    private PtyMapper ptyMapper;
    @Resource
    private SysmodService sysmodService;
    @Autowired
    private ActMapper actMapper;
    @Autowired
    private BnlMapper bnlMapper;
    @Autowired
    private CnnMapper cnnMapper;
    @Autowired
    private SmhMapper smhMapper;
    @Autowired
    private CodetableService codetableService;
    @Autowired
    private DgaMapper dgaMapper;
    @Resource
    private EcmMapper ecmMapper;
    @Resource
    private EcmbopMapper ecmbopMapper;
    @Resource
    private PtaMapper ptaMapper;


    /**
     * 注册自动化任务
     * @param sptinr 待办任务inr
     */
    public boolean insertAutoFlow(String sptinr) {
//        String label = codetableService.getTblLabel("ISOPEN", "AUTSIG", "EN");
//        if ("0".equalsIgnoreCase(label)) {
//            return false;
//        }
        Spt spt = sptMapper.getSptByInr(sptinr);
        if (spt == null) {
            return false;
        }
        AutoFlow access = autoFlowHelper.access(AutoTypeEnum.CPT, AutoSrcTypeEnum.SPT.getCode(), sptinr, spt, this::autoAccessForCpt);
        if (access != null && access.getSta().equals(AutoStaEnum.WAITING.getCode())) {
            return true;
        }
        return false;
    }

    /**
     * 汇入、汇出汇款准入校验
     */
    private String autoAccessForCpt(Spt spt) {
        if (!"CPTADV".equalsIgnoreCase(spt.getFrm()) && !"CPTOPN".equalsIgnoreCase(spt.getFrm())) {
            LOGGER.error("业务交易数据不符合准入条件FRM:{}", spt.getFrm());
            return null;
        }
        String sceneCode = "";//CPTECI\CPTECO\CPTHYF\CPTHYI
        if (StringUtils.isNotEmpty(spt.getSta())) {
            boolean flag = false;
            String errorMsg = "";
            String cptrou = "";
            String paytyp = "";
            switch (spt.getSta()) {
                //swift
                case "INC":
                    flag = true;
                    if (StringUtils.isNotEmpty(spt.getMsgtyp()) && "103".equals(spt.getMsgtyp())) {
                        CptadvAutoStoreBo cptadvSwiftBo = getSwiftTrnInfo(spt);
                        sceneCode = checkAutoSignInfo(cptadvSwiftBo);
                        cptrou = "SWIFT";
                        paytyp = "I";
                    }
                    break;
                //境内外币
                case "FMT":
                    flag = true;
                    CptadvAutoStoreBo cptadvAtdBo = readAtd(spt);
                    //CptadvAutoStoreBo cptadvAtdBo = getAtdTrnInfo(spt);
                    sceneCode = checkAutoSignInfo(cptadvAtdBo);
                    cptrou = "JNWB";
                    paytyp = "I";
                    break;
                //大额支付系统 todo 大小额不准入自动化
//                case "HVP":
//                case "HVQ":
//                case "HVR":
//                    //小额支付系统
//                case "BEP":
//                case "BEQ":
//                case "BES":
//                    flag = true;
//                    CptadvAutoStoreBo cptadvOtherBo = readCnd(spt);
//                    sceneCode = checkAutoSignInfo(cptadvOtherBo);
//                    cptrou = "OTHER";
//                    paytyp = "I";
//                    break;
                //CIPS 只cips111
                case "CIU":
                    flag = true;
                    CptadvAutoStoreBo cptadvCIPSBo = readCnd(spt);
                    sceneCode = checkAutoSignInfo(cptadvCIPSBo);
                    cptrou = "CIPS";
                    paytyp = "I";
                    break;
                case "EJS":
                    flag = true;
                    cptrou = "JNWB";
                    paytyp = "O";
                    sceneCode = checkCptopnAutoSignInfo(spt);
                    break;
                case "ECM":
                    flag = true;
                    paytyp = "O";
                    sceneCode = "CPTECO";
                    if ("FXPS111".equalsIgnoreCase(spt.getMsgtyp())) {
                        cptrou = "JNWB";
                    }
                    if ("6701".equalsIgnoreCase(spt.getMsgtyp())) {
                        cptrou = "SWIFT";
                    }
                    if ("CIPS111".equalsIgnoreCase(spt.getMsgtyp())) {
                        cptrou = "CIPS";
                    }
                    break;
                default:
                    flag = false;
                    break;
            }
            if (!flag) {
                LOGGER.error("业务交易数据不符合准入条件STA:{}", spt.getSta());
                return null;
            }
            if (StringUtils.isEmpty(sceneCode)) {
                LOGGER.error("业务交易数据未查询到自动化签约:{}", errorMsg);
                return null;
            }
            spt.setEhtyp(sceneCode);
            sptMapper.updateByPrimaryKeySelective(spt);
            Que que = queMapper.selectByObjtypAndObjinr("SPT", spt.getInr());
            if(que == null){
                LOGGER.error("自动化准入处理中，通过sptinr未查询到QUE数据，sptinr={}", spt.getInr());
                return null;
            }
            que.setEhtyp(sceneCode);
            String label = codetableService.getTblLabel("ISOPEN", "AUTSIG", "EN");
            //0自动化开关关闭，命中场景置为空。外层不生成autoflow数据
            if ("0".equalsIgnoreCase(label)) {
                sceneCode = "";
            }else {
                que.setAuto("Y");
            }
            queMapper.updateByPrimaryKeySelective(que);
            LOGGER.info("待办sptinr:" + spt.getInr() + "命中自动化场景：" + sceneCode);
        }
        return sceneCode;
    }

    private CptadvAutoStoreBo getSwiftTrnInfo(Spt spt) {
        CptadvAutoStoreBo cptadvAutoStoreBo = sysmodService.sptLoadData(CptadvAutoStoreBo.class, spt.getInr());
        cptadvAutoStoreBo.setSpt(spt);
        return cptadvAutoStoreBo;
    }

    public CptadvAutoStoreBo readCnd(Spt spt) {
        //接收报文为CMT，查CND表字段，填入相应面板
        List<Cnd> cnds = cndMapper.selectBySptinr(spt.getInr());
        if (cnds == null || cnds.size() == 0) return null;
        Cnd cnd = cnds.get(0);
        CptadvAutoStoreBo cptadvStoreBo = new CptadvAutoStoreBo();
        cptadvStoreBo.reset();
        cptadvStoreBo.setSpt(spt);
        cptadvStoreBo.getCptp().setResbch(cnd.getRecbchkey());
        cptadvStoreBo.getCptp().setResbchnam("");
        cptadvStoreBo.getCptp().setResbchnam(getBankName(Strings.trim(cptadvStoreBo.getCptp().getResbch())));
        cptadvStoreBo.getCipmod().setStasehbch(cnd.getStasehbch());
        cptadvStoreBo.getCipmod().setRecsehbch(cnd.getRecsehbch());
        cptadvStoreBo.getCipmod().setDlgdat(cnd.getDlgdat());
        cptadvStoreBo.getCipmod().setSatbch(cnd.getSatbch());//hvps-发起行行号
        cptadvStoreBo.getCipmod().setSatbchnam(GetBNLName(cnd.getSatbch()));
        //付款人开户行行号 cnn表里也有这个字段
        cptadvStoreBo.getCipmod().setFkrkhh(cnd.getOrcbchkey());
        cptadvStoreBo.getCptp().setOrcnam(cnd.getOrcnam());
        cptadvStoreBo.getCptp().setOrcadr(cnd.getOrcadr());
        cptadvStoreBo.getCptp().setPyenam(cnd.getPyenam());
        cptadvStoreBo.getCptp().setPyeadr(cnd.getPyeadr());
        cptadvStoreBo.getAttp().setCommet(cnd.getCommet());
        cptadvStoreBo.getHvpmod().setRemark(cnd.getRemark());
        cptadvStoreBo.getCptp().setPyebchkey(cnd.getPyebchkey());
        cptadvStoreBo.getCptp().setPyebchnam(getBankName(Strings.trim(cptadvStoreBo.getCptp().getPyebchkey())));
        String a = NULLSTR;
        if (Strings.pos("-CMT-CMX-CMY-", cptadvStoreBo.getCpdgrp().getRec().getSwftyp()) > 0) {
            //CMT100的情况下
            //Systems.setVisible(cptadvStoreBo.getCptp(), "bustyp");
            cptadvStoreBo.getCptp().setBustyp(cnd.getBustyp());
            if (MdaUtils.isEmpty(cnd.getHxywbh())) {
                cptadvStoreBo.getCptp().setSecmod("0");
            } else {
                cptadvStoreBo.getCptp().setSecmod("1");
            }
            //收进来报文可能为60或62外的其他种类，统一设为OT--其他
            /**
             if CPTP\\bustyp <> "60" and CPTP\\bustyp <> "62" and CPTP\\bustyp <> "70" and CPTP\\bustyp <> "71" then
             CPTP\\bustyp = "OT"
             endif
             **/
        } else {
            a = cnd.getBustyp();
            if (Strings.len(a) == 5) {
                cptadvStoreBo.getCptp().setSecmod("2");
                cptadvStoreBo.getCptp().setBustyp(a);
            } else {
                cptadvStoreBo.getCptp().setSecmod("1");
                cptadvStoreBo.getCptp().setBustyp(a);
            }
        }
        cptadvStoreBo.getCptp().setOribustyp(cptadvStoreBo.getCptp().getBustyp());
        cptadvStoreBo.getCpdgrp().getRec().setOrcact(cnd.getOrcact());
        cptadvStoreBo.getCpdgrp().getRec().setPyeact(cnd.getPyeact());
        cptadvStoreBo.getCpdgrp().getCbs().getNom1().setAmt(cnd.getAmt());
        cptadvStoreBo.getCpdgrp().getCbs().getNom1().setCur(cnd.getCur());
        switch (cptadvStoreBo.getCptp().getBustyp()) {
            case "GOD":
                cptadvStoreBo.getCptp().setBustyp("GODX");
                break;
            case "STR":
                cptadvStoreBo.getCptp().setBustyp("STRX");
                break;
            case "CTF":
                cptadvStoreBo.getCptp().setBustyp("CTFX");
                break;
            case "RMT":
                cptadvStoreBo.getCptp().setBustyp("RMTX");
                break;
            case "OTF":
                cptadvStoreBo.getCptp().setBustyp("OTFX");
                break;
            case "FTF":
                cptadvStoreBo.getCptp().setBustyp("FTFX");
                break;
        }
        cptadvStoreBo.getHvpmod().setAgencydl(cnd.getAgency());
        cptadvStoreBo.getHvpmod().setAgnamedl(cnd.getAgname());
        cptadvStoreBo.getHvpmod().setOribusnum(cnd.getOribusnum());
        cptadvStoreBo.getCipmod().setDddbsh(cnd.getOribusnum());
        cptadvStoreBo.getCipmod().setStaonebch(cnd.getStaonebch());
        cptadvStoreBo.getCipmod().setStasehbch(cnd.getStasehbch());
        cptadvStoreBo.getCipmod().setReconebch(cnd.getReconebch());
        cptadvStoreBo.getCipmod().setRecsehbch(cnd.getRecsehbch());
        //读取cnn表
        List<Cnn> cnns = cnnMapper.selectByCndinr(cnd.getInr());
        if (cnns != null && cnns.size() > 0) {
            Cnn cnn = cnns.get(0);
            cptadvStoreBo.getAttp().setCom102(cnn.getFuyns1());
            cptadvStoreBo.getHvpmod().setFeecod(cnn.getFeecod());
            cptadvStoreBo.getHvpmod().setFecomm(cnn.getCommet());
            cptadvStoreBo.getHvpmod().setFkrmc2(cnn.getFkrmc2());
            cptadvStoreBo.getHvpmod().setFkrdz2(cnn.getFkrdz2());
            cptadvStoreBo.getHvpmod().setFkrdz3(cnn.getFkrdz3());
            cptadvStoreBo.getHvpmod().setFkrdz4(cnn.getFkrdz4());
            cptadvStoreBo.getHvpmod().setFkrdz5(cnn.getFkrdz5());

            cptadvStoreBo.getCipmod().setFuynh2(cnn.getComme2());
            cptadvStoreBo.getCipmod().setFuynh3(cnn.getComme3());
            cptadvStoreBo.getCipmod().setFuynh4(cnn.getComme4());
            cptadvStoreBo.getCipmod().setFkrdz2(cnn.getFkrdz2());
            cptadvStoreBo.getCipmod().setFkrdz3(cnn.getFkrdz3());
            cptadvStoreBo.getCipmod().setFkrdz4(cnn.getFkrdz4());
            cptadvStoreBo.getCipmod().setFkrdz5(cnn.getFkrdz5());
            cptadvStoreBo.getCipmod().setFkrdz6(cnn.getFkrdz6());
            cptadvStoreBo.getCipmod().setFkrdz7(cnn.getFkrdz7());
            cptadvStoreBo.getCipmod().setSkrdz2(cnn.getSkrdz2());
            cptadvStoreBo.getCipmod().setSkrdz3(cnn.getSkrdz3());
            cptadvStoreBo.getCipmod().setSkrdz4(cnn.getSkrdz4());
            cptadvStoreBo.getCipmod().setSkrdz5(cnn.getSkrdz5());
            cptadvStoreBo.getCipmod().setSkrdz6(cnn.getSkrdz6());
            cptadvStoreBo.getCipmod().setSkrdz7(cnn.getSkrdz7());
            //TRNMOD\\CIPMOD\\CYSBZH=TRNMOD\\CNN\\CYSBZH
            //TRNMOD\\CIPMOD\\CYSHJE=TRNMOD\\CNN\\CYSHJE
            cptadvStoreBo.getCipmod().setCfkkhh(cnn.getCfkkhh());
            cptadvStoreBo.getCipmod().setCfkkhm(cnn.getCfkkhm());
            cptadvStoreBo.getCipmod().setCfkrzh(cnn.getCfkrzh());
            cptadvStoreBo.getCipmod().setCfkrmc(cnn.getCfkrmc());
            cptadvStoreBo.getCipmod().setCfkdz1(cnn.getCfkdz1());
            cptadvStoreBo.getCipmod().setCfkdz2(cnn.getCfkdz2());
            cptadvStoreBo.getCipmod().setCfkdz3(cnn.getCfkdz3());
            cptadvStoreBo.getCipmod().setCfkdz4(cnn.getCfkdz4());
            cptadvStoreBo.getCipmod().setCfkdz5(cnn.getCfkdz5());
            cptadvStoreBo.getCipmod().setCfkdz6(cnn.getCfkdz6());
            cptadvStoreBo.getCipmod().setCfkdz7(cnn.getCfkdz7());
            cptadvStoreBo.getCipmod().setCskkhh(cnn.getCskkhh());
            cptadvStoreBo.getCipmod().setCskkhm(cnn.getCskkhm());
            cptadvStoreBo.getCipmod().setCskrzh(cnn.getCskrzh());
            cptadvStoreBo.getCipmod().setCskrmc(cnn.getCskrmc());
            cptadvStoreBo.getCipmod().setCskdz1(cnn.getCskdz1());
            cptadvStoreBo.getCipmod().setCskdz2(cnn.getCskdz2());
            cptadvStoreBo.getCipmod().setCskdz3(cnn.getCskdz3());
            cptadvStoreBo.getCipmod().setCskdz4(cnn.getCskdz4());
            cptadvStoreBo.getCipmod().setCskdz5(cnn.getCskdz5());
            cptadvStoreBo.getCipmod().setCskdz6(cnn.getCskdz6());
            cptadvStoreBo.getCipmod().setCskdz7(cnn.getCskdz7());
            cptadvStoreBo.getCipmod().setCzjjg1(cnn.getCzjjg1());
            cptadvStoreBo.getCipmod().setCzj1mc(cnn.getCzj1mc());
            cptadvStoreBo.getCipmod().setCovfuy(cnn.getCovfuy());
            cptadvStoreBo.getCipmod().setCovfy2(cnn.getCovfy2());
            cptadvStoreBo.getCipmod().setCovfy3(cnn.getCovfy3());
            cptadvStoreBo.getCipmod().setCovfy4(cnn.getCovfy4());
            cptadvStoreBo.getCipmod().setFuyns1(cnn.getFuyns1());
            cptadvStoreBo.getCipmod().setFuyns2(cnn.getFuyns2());
            cptadvStoreBo.getCipmod().setFuyns3(cnn.getFuyns3());
            cptadvStoreBo.getCipmod().setFuyns4(cnn.getFuyns4());
            cptadvStoreBo.getCipmod().setMxywbs(String.valueOf(cnn.getMxywbs()));
            cptadvStoreBo.getCipmod().setMxywje(String.valueOf(cnn.getMxywje()));
            cptadvStoreBo.getCipmod().setFqzyhh(cnn.getFqzyhh());
            cptadvStoreBo.getCipmod().setJszyhh(cnn.getJszyhh());
            cptadvStoreBo.getCipmod().setMxywsh(cnn.getMxywsh());
            //付款人开户行行号
            cptadvStoreBo.getCipmod().setFkrkhh(cnn.getFkrkhh());
            //中介机构2行号
            cptadvStoreBo.getCipmod().setZjg2hh(cnn.getAgname2());
        }


        int ignore = 0;
        if (!MdaUtils.isEmpty(cptadvStoreBo.getSpt().getSmhinr())) {
            Smh smh = smhMapper.getSmhInfoBySptSmhinr(cptadvStoreBo.getSpt().getSmhinr());
        }

        /**
         if CPDGRP\\REC\\SWFTYP == "HVP" or CPDGRP\\REC\\SWFTYP == "HVQ" then
         **/
        /**
         if CPDGRP\\REC\\SWFTYP == "HVP" or CPDGRP\\REC\\SWFTYP == "HVQ" or CPDGRP\\REC\\SWFTYP == "CIU" or CPDGRP\\REC\\SWFTYP == "CIV" or CPDGRP\\REC\\SWFTYP == "CIW" then
         **/
//        String swftyp = cptadvStoreBo.getCpdgrp().getRec().getSwftyp();
//        if (MdaUtils.compareTo(swftyp, "CIU") == 0 || MdaUtils.compareTo(swftyp, "CIV") == 0 || MdaUtils.compareTo(swftyp, "CIW") == 0) {
//            deal8758Interface(cptadvStoreBo, cnd);
//        } else if (MdaUtils.compareTo(swftyp, "HVP") == 0 || MdaUtils.compareTo(swftyp, "HVQ") == 0 || MdaUtils.compareTo(swftyp, "HVR") == 0) {
//            deal8680Interface(cnd);
//        }
        return cptadvStoreBo;
    }

    public CptadvAutoStoreBo readAtd(Spt spt) {
        CptadvAutoStoreBo transactionVo = new CptadvAutoStoreBo();
        transactionVo.reset();
        Cpdgrp cpdgrp = transactionVo.getCpdgrp();
        cpdgrp.getRec().setSwftyp(spt.getMsgtyp());
        Atd atd = atdMapper.getAtdBySptinr(spt.getInr());
        transactionVo.getAttp().setSysno(atd.getBaowbh());
        transactionVo.getCpdgrp().getRec().setSysno(atd.getBaowbh());
        transactionVo.getAttp().setXnggbh(atd.getXnggbh());
        transactionVo.getAttp().setAcctyp(atd.getAcctyp());
        transactionVo.getAttp().setBustyp(atd.getBustyp());
        transactionVo.getAttp().setSwftyp(atd.getFmttyp());
        cpdgrp.getRec().setValdat(atd.getValdat());
        String feetyp = atd.getFeetyp();
        switch (feetyp) {
            case "1":
                transactionVo.getAttp().setFeetyp("BEN");
                break;
            case "2":
                transactionVo.getAttp().setFeetyp("OUR");
                break;
            case "3":
                transactionVo.getAttp().setFeetyp("SHA");
                break;
            default:
        }
        //发报行信息
        String swfcod = atd.getSbknum();
        if (!MdaUtils.isEmpty(swfcod)) {
            if (StringUtils.isEmpty(cpdgrp.getSnd().getPtyinr())) {
                Pty sndPty = ptyMapper.selectByExtkey(swfcod);
                if (sndPty != null) cpdgrp.getSnd().setPtyinr(sndPty.getInr());
            }
            List<Dga> dgas = dgaMapper.selectByBiccod(Strings.toUpper(swfcod));
            if (dgas.size() > 0) {
                transactionVo.getAttp().setSndbch(dgas.get(0).getBiccod());
                transactionVo.getAttp().setSndbchnam(dgas.get(0).getJigomc());
            }
        }
        //接收行信息
        if (StringUtils.isNotEmpty(atd.getRbknum()) && StringUtils.isEmpty(cpdgrp.getRes().getPtyinr())) {
            Pty resPty = ptyMapper.selectByExtkey(atd.getRbknum());
            if (resPty != null) cpdgrp.getRes().setPtyinr(resPty.getInr());
        }
        //transactionVo.getAttp().setResbchnam(SettleContext.getUserSession().getBch().getBchname());
        //transactionVo.getAttp().setResbch(SettleContext.getUserSession().getBch().getSwfcod());
        //汇款人开户行信息
        String oriextkey = atd.getZuichk();
        if (StringUtils.isNotEmpty(oriextkey) && StringUtils.isEmpty(cpdgrp.getOri().getPtyinr())) {
            Pty oriPty = ptyMapper.selectByExtkey(oriextkey);
            if (oriPty != null) cpdgrp.getOri().setPtyinr(oriPty.getInr());
        }
        //收款人开户行信息
        String pybextkey = atd.getZhaghh();
        if (StringUtils.isNotEmpty(pybextkey) && StringUtils.isEmpty(cpdgrp.getPyb().getPtyinr())) {
            Pty pybPty = ptyMapper.selectByExtkey(pybextkey);
            if (pybPty != null) cpdgrp.getPyb().setPtyinr(pybPty.getInr());
        }
        cpdgrp.getOri().getPts().setAdrblk(oriextkey);
        cpdgrp.getPyb().getPts().setAdrblk(pybextkey);
        cpdgrp.getOri().setDbfadrblk(oriextkey);
        cpdgrp.getPyb().setDbfadrblk(pybextkey);
        cpdgrp.getOri().setDbfadrblkcn(oriextkey);
        cpdgrp.getPyb().setDbfadrblkcn(pybextkey);
        cpdgrp.getOri().getPts().setExtkey(atd.getSbkopn());
        if (StringUtils.isNotEmpty(atd.getSbkopn())) {
            //补充汇款人开户行ptyinr
            Pty oriPty = ptyMapper.selectByExtkey(atd.getSbkopn());
            if (oriPty != null) cpdgrp.getOri().setPtyinr(oriPty.getInr());
        }

//        String pybExtkey = SettleContext.getUserSession().getBch().getSwfcod();
//        if(StringUtils.isEmpty(pybExtkey)){
//            pybExtkey = "";
//        }
        String pybExtkey = "";
        cpdgrp.getPyb().getPts().setExtkey(pybExtkey);
        if (StringUtils.isNotEmpty(pybExtkey)) {
            Pty pybPty = ptyMapper.selectByExtkey(pybExtkey);
            if (pybPty != null) cpdgrp.getPyb().setPtyinr(pybPty.getInr());
        }
        transactionVo.getAttp().setOrcnamfxps(atd.getOrcnam());
        transactionVo.getAttp().setOrcadrfxps(atd.getOrcadr());
        //汇入汇款由账号带入
        transactionVo.getAttp().setPyenamfxps(atd.getPyenam());
        transactionVo.getAttp().setPyeadrfxps(atd.getPyeadr());
        transactionVo.getAttp().setYwlxdm(atd.getYwlxdm());
        //24年TD新增逻辑，如果附言有值，就添加到界面附言72栏位，可修改
        if (MdaUtils.compareTo(atd.getFmttyp(), "111") == 0 || MdaUtils.compareTo(atd.getFmttyp(), "112") == 0) {
            if (StringUtils.isNotEmpty(atd.getFuyann())) {
                transactionVo.getAttp().setCom102(atd.getFuyann());
            }
        }
        if (MdaUtils.compareTo(atd.getFmttyp(), "111") == 0) {
            switch (atd.getYwlxdm()) {
                case "A311":
                    transactionVo.getAttp().setCommet(atd.getCommet());
                    transactionVo.getAttp().setCom102(atd.getFuyann());
                    break;
                case "A100":
                    transactionVo.getAttp().setCommet(atd.getCommet());
                    break;
                default:
                    transactionVo.getAttp().setCommet(atd.getFuyann());
            }
        } else {
            switch (atd.getFmttyp()) {
                case "102":
                    transactionVo.getAttp().setCommet(atd.getCommet());
                    transactionVo.getAttp().setCom102(atd.getFuyann());
                    break;
                case "100":
                    transactionVo.getAttp().setCommet(atd.getCommet());
                    break;
                default:
                    transactionVo.getAttp().setCommet(atd.getFuyann());
            }
        }
        //带入202报文的受益行
        transactionVo.getAttp().setShouyh(atd.getShouyh());
        cpdgrp.getCbs().getNom1().setAmt(atd.getAmt());
        cpdgrp.getCbs().getNom1().setCur(Codetables.getCodeTableKeyOfTd(atd.getCurcod(), "CURKEY", Systems.getLang()));
        //收款人 账号\\汇款人账号
        cpdgrp.getRec().setPyeact(atd.getPyeact());
        cpdgrp.getRec().setOrcact(atd.getOrcact());
        return transactionVo;
    }

    public String getBankName(String argNum) {
        String bankName = "";
        Bnl bnl = bnlMapper.selectByFqcyjg(argNum);

        if (bnl != null) {
            bankName = bnl.getFukrhm();
        }
        return bankName;

    }

    private CptadvAutoStoreBo getAtdTrnInfo(Spt spt) {
        Atd atd = atdMapper.getAtdBySptinr(spt.getInr());
        //业务数据
        String pyeact = atd.getPyeact();//收款人账号
        String orcact = atd.getOrcact();//汇款人账号
        String cur = Codetables.getCodeTableKeyOfTd(atd.getCurcod(), "CURKEY", Systems.getLang());//汇款币种
        BigDecimal amt = atd.getAmt();//汇款金额
        CptadvAutoStoreBo cptadvAutoStoreBo = new CptadvAutoStoreBo();
        cptadvAutoStoreBo.reset();
        cptadvAutoStoreBo.setSpt(spt);
        cptadvAutoStoreBo.getCpdgrp().getRec().setSwftyp(spt.getMsgtyp());
        cptadvAutoStoreBo.getCpdgrp().getRec().setPyeact(pyeact);//收款人账号
        cptadvAutoStoreBo.getCpdgrp().getRec().setOrcact(orcact);//汇款人账号
        cptadvAutoStoreBo.getCpdgrp().getCbs().getNom1().setCur(cur);//汇款币种
        cptadvAutoStoreBo.getCpdgrp().getCbs().getNom1().setAmt(amt);//汇款金额
        cptadvAutoStoreBo.getAttp().setYwlxdm(atd.getYwlxdm());
        return cptadvAutoStoreBo;
    }

    private String checkAutoSignInfo(CptadvAutoStoreBo cptadvAutoStoreBo) {
        String errorMsg = "";
        String sceneCode = "";
        //业务数据
        String pyeact = cptadvAutoStoreBo.getCpdgrp().getRec().getPyeact();//收款人账号
        if (StringUtils.isEmpty(pyeact)) {
            LOGGER.info("来报收款人账号为空，汇入汇款自动化场景准入失败！sptinr={}", cptadvAutoStoreBo.getSpt().getInr());
            return "";
        }
        List<Act> actListByPyeact = actMapper.getActListByExtkey(pyeact);
        if (actListByPyeact.size() == 0) {
            LOGGER.info("来报收款人账号不存在，汇入汇款自动化场景准入失败！sptinr={}", cptadvAutoStoreBo.getSpt().getInr());
            return "";
        }
        if (actListByPyeact.size() > 1) {
            LOGGER.info("来报收款人账号extkey对应多个账户，汇入汇款自动化场景准入失败！sptinr={}", cptadvAutoStoreBo.getSpt().getInr());
            return "";
        }
        //来报的账号实体
        Act pyeactBo = actListByPyeact.get(0);
        String orcact = cptadvAutoStoreBo.getCpdgrp().getRec().getOrcact();//汇款人账号
        String cur = cptadvAutoStoreBo.getCpdgrp().getCbs().getNom1().getCur();//汇款币种
        BigDecimal amt = cptadvAutoStoreBo.getCpdgrp().getCbs().getNom1().getAmt();//汇款金额
        String msgTrnCommonCheck = checkTrnCommonInfo(pyeact, cur, amt);
        if (StringUtils.isNotEmpty(msgTrnCommonCheck)) {
            LOGGER.info(msgTrnCommonCheck);
            return "";
        }

        //自动化签约校验
        //判断来报中账号是否存在对应客户pty
//        PtsptaQueryVo ptsptaVo = new PtsptaQueryVo();
//        ptsptaVo.setOrcact(pyeact);
//        PtsptaInfoVo ptsptaInfoVo = ptsptaMapper.selectExtkeyByOrcact(ptsptaVo);
        Pty pyepty = ptyMapper.selectByPtyinr(pyeactBo.getHolptyinr());
        if (pyepty == null) {
            LOGGER.info("收款人账号当前所属客户不存在");
            return "";
        }
        //act -- pty -- ptas
        List<Pta> ptas = ptaMapper.selectByPtyExtkey(pyepty.getExtkey());
        if (ptas == null || ptas.size() == 0) {
            LOGGER.info("该笔报文中收款人账号当前所属客户【" + pyepty.getExtkey() + "】不存在地址信息！");
            return "";
        }
        AutsigQueryVo autsigQueryVo = new AutsigQueryVo();
        autsigQueryVo.setAct(pyeact);
        autsigQueryVo.setPaytyp("I");
        List<AutoSignInfo> autoSignInfos = autoSignInfoMapper.selectList(autsigQueryVo);
        if (autoSignInfos.size() == 0) {
            LOGGER.info("未找到收款人账号对应的汇入场景自动化签约信息！");
            return "";
        }
        //命中一个场景即返回
        int ptacpunt = 0;
        for (int i = 0; i < autoSignInfos.size(); i++) {
            //查询签约中地址是不是当前账户所属客户
            String signPtainr = autoSignInfos.get(i).getPtainr();
            if (StringUtils.isEmpty(signPtainr)) {
                LOGGER.info("签约信息中缺少ptainr，autoSignInfoInr=" + autoSignInfos.get(i).getInr());
                continue;
            }
            Pta selectByInr = ptaMapper.selectByInr(signPtainr);
            if (selectByInr == null) {
                LOGGER.info("签约信息中的ptainr没有对应地址，autoSignInfoInr=" + autoSignInfos.get(i).getInr());
                continue;
            }
            //电商需提前判断签约账号是否有电商标记
            if (StringUtils.isNotEmpty(autoSignInfos.get(i).getScenecode()) && "CPTECI".equalsIgnoreCase(autoSignInfos.get(i).getScenecode())) {
                LOGGER.info("判断是否为汇入电商场景：");
                if (!pyepty.getInr().equals(autoSignInfos.get(i).getPtyinr())) {
                    errorMsg += "汇入电商场景判断：收款人账号当前所属客户与签约客户不匹配。账号客户ptyinr=" + pyepty.getInr() + "签约ptyinr= " + autoSignInfos.get(i).getPtyinr();
                    LOGGER.info(errorMsg);
                } else {
                    if (StringUtils.isNotEmpty(pyeactBo.getTrmtyp()) && "LO-T20".equals(pyeactBo.getTrmtyp())) {
//                        sceneCode = autoSignInfos.get(i).getScenecode();
//                        break;
                    } else {
                        errorMsg += "汇入电商场景判断：收款人账号不是电商账号，trmtyp = " + pyeactBo.getTrmtyp();
                        LOGGER.info(errorMsg);
                    }
                }
            }
            LOGGER.info("场景规则判断：" + autoSignInfos.get(i).getScenecode());
            errorMsg += checkRules(autoSignInfos.get(i), cptadvAutoStoreBo);
            if (StringUtils.isEmpty(errorMsg)) {
                sceneCode = autoSignInfos.get(i).getScenecode();
                break;
            } else {
                LOGGER.info("未命中：" + autoSignInfos.get(i).getScenecode() + "，判断结果：" + errorMsg);
            }

        }

        //交易对手校验
//        if (autoSignInfo.getHascountpty() != null && "Y".equals(autoSignInfo.getHascountpty())) {
//            String msgCheckPty = checkCountPtyInfo(autoSignInfo.getInr(), orcact);
//            if (StringUtils.isNotEmpty(msgCheckPty)) {
//                errorMsg += msgCheckPty;
//            }
//        }
        return sceneCode;
    }

    /**
     * 规则校验，待补充
     *
     * @param autoSignInfo
     * @param cptadvAutoStoreBo
     * @return
     */
    private String checkRules(AutoSignInfo autoSignInfo, CptadvAutoStoreBo cptadvAutoStoreBo) {
        String errorMsg = "";
        AutsigRulQueryVo comRuleParam = new AutsigRulQueryVo();
        comRuleParam.setIsdefault("1");
        comRuleParam.setScenecode(autoSignInfo.getScenecode());
        List<AutoSignRule> comRules = autoSignRuleMapper.selectList(comRuleParam);
        //自定义规则
        AutsigRulQueryVo userRuleParam = new AutsigRulQueryVo();
        userRuleParam.setSigninfoinr(autoSignInfo.getInr());
        userRuleParam.setIsdefault("0");
        userRuleParam.setScenecode(autoSignInfo.getScenecode());
        List<AutoSignRule> userRules = autoSignRuleMapper.selectList(userRuleParam);
        List<AutoSignRule> allrules = new ArrayList<>();
        allrules.addAll(comRules);
        allrules.addAll(userRules);
//        if (allrules.size() == 0) {
//            errorMsg = "未找到签约规则";
//        }

        for (int i = 0; i < allrules.size(); i++) {
            AutoSignRule autoSignRule = allrules.get(i);
            String rulekey = autoSignRule.getRulekey();
            String keytyp = autoSignRule.getKeytyp();
            String content = autoSignRule.getContent();//比较内容
            String symbols = autoSignRule.getSymbols();//判断符号
            String keytxt = autoSignRule.getKeytxt();
            String scenecode = autoSignRule.getScenecode();
            if (rulekey.contains(".")) {
                rulekey = rulekey.replace(".", "//");
            }
            Object fieldValue = Utils.getFieldValue(cptadvAutoStoreBo, rulekey);
            if (fieldValue == null || content == null) {
                continue;
            }
            boolean checkrule = true;

            if ("str".equals(keytyp)) {
                String value = (String) fieldValue;
                switch (symbols) {
                    case "equal":
                        checkrule = value.equals(content);
                        break;
                    case "noequ":
                        checkrule = !value.equals(content);
                        break;
                    case "contains":
                        checkrule = value.contains(content);
                        break;
                    case "nocon":
                        checkrule = !value.contains(content);
                        break;

                }
            } else if ("amt".equals(keytyp)) {
                //todo 金额逻辑
            } else if ("num".equals(keytyp)) {
                //todo 数字逻辑
            }
            if (!checkrule) {
                errorMsg = "签约规则未通过：" + keytxt + ";";
            }
        }

        return errorMsg;
    }

    private String checkTrnCommonInfo(String pyeact, String cur, BigDecimal amt) {
        String errorComMsg = "";
        //业务数据缺失校验
        if (StringUtils.isEmpty(pyeact)) {
            errorComMsg += "收款人账号为空;";
        }
        if (StringUtils.isEmpty(cur)) {
            errorComMsg += "汇款币种为空;";
        }
        if (amt == null || amt.compareTo(BigDecimal.ZERO) == 0) {
            errorComMsg += "汇款金额为空;";
        }
        if (StringUtils.isNotEmpty(errorComMsg)) {
            return errorComMsg;//校验未通过直接返回
        }
        //收款人账号有效性校验
        PtsptaQueryVo ptsptaVo = new PtsptaQueryVo();
        ptsptaVo.setOrcact(pyeact);
        PtsptaInfoVo ptsptaInfoVo = ptsptaMapper.selectExtkeyByOrcact(ptsptaVo);
        if (MdaUtils.isEmpty(ptsptaInfoVo)) {
            errorComMsg += "收款人账号国结未维护,请先维护!(内部户除外);";
        } else if (!MdaUtils.isEmpty(ptsptaInfoVo)) {
            if (!"LO".equals(ptsptaInfoVo.getTyp())) {
                errorComMsg += "收款人账号类型有误;";
            }
        }
        return errorComMsg;
    }

    private String checkCountPtyInfo(String signInfoInr, String orcact) {
        String errorPtyMsg = "";
        if (StringUtils.isEmpty(orcact)) {
            errorPtyMsg += "汇款人账号为空;";
        }
        //交易对手必填时，通过来报中的汇款人账号查询
        AutoSignCountPty param = new AutoSignCountPty();
        param.setSigninfoinr(signInfoInr);
        param.setAct(orcact);
        List<AutoSignCountPty> autoSignCountPtyList = autoSignCountPtyMapper.selectList(param);
        if (autoSignCountPtyList.size() == 0) {
            errorPtyMsg += "汇款人账号不在签约交易对手列表中;";
        }
        return errorPtyMsg;
    }

    /**
     * 二代支付根据行号查询BNL表中的行名
     *
     * @param fqcyjg
     * @return
     */
    public String GetBNLName(String fqcyjg) {
        Bnl bnl = bnlMapper.selectByFqcyjg(fqcyjg);
        if (bnl == null) {
            return "";
        }
        return bnl.getFukrhm();
    }

    private String checkCptopnAutoSignInfo(Spt spt) {
        String label = codetableService.getTblLabel("OPNFLG", "AUTSIG", "EN");
        if ("0".equalsIgnoreCase(label)) {
            return "CPTHYF";
        }
        Ecm ecmReq = new Ecm();
        ecmReq.setSptinr(spt.getInr());
        Ecm ecm = ecmMapper.selectBySptinr(ecmReq);
        if (ecm == null) {
            throw new CommonServiceException("该笔报文SPTINR:" + spt.getInr() + "没有ECM表记录,数据不全！");
        }
        Ecmbop ecmbopReq = new Ecmbop();
        ecmbopReq.setEcminr(ecm.getInr());
        Ecmbop ecmbop = ecmbopMapper.selectByEcminr(ecmbopReq);
        if (ecmbop == null) {
            throw new CommonServiceException("该笔报文SPTINR:" + spt.getInr() + "没有ECMBOP表记录,数据不全！");
        }
        String fcyacc = ecmbop.getFcyacc();
        if (StringUtils.isEmpty(fcyacc)) {
            throw new CommonServiceException("该笔报文涉及到的ECMBOP:" + ecmbop.getInr() + "中的汇款人账号为空！");
        }
        List<Act> actListByExtkey = actMapper.getActListByExtkey(fcyacc);
        if (actListByExtkey == null || actListByExtkey.size() < 1) {
            throw new CommonServiceException("汇款人账号:" + fcyacc + "在国结不存在！");
        }
        Act act = actListByExtkey.get(0);
        Pty pty = ptyMapper.selectByPtyinr(act.getHolptyinr());
        if (pty == null) {
            throw new CommonServiceException("汇款人PTYINR:" + act.getHolptyinr() + "在国结不存在！");
        }
        AutsigQueryVo autsigQueryVo = new AutsigQueryVo();
        autsigQueryVo.setPaytyp("O");
        autsigQueryVo.setExtkey(pty.getExtkey());
        List<AutoSignInfo> autoSignInfos = autoSignInfoMapper.selectList(autsigQueryVo);
        if (autoSignInfos == null || autoSignInfos.size() < 1) {
            return "";
        } else {
            return autoSignInfos.get(0).getScenecode();
        }
    }

}
