package com.brilliance.isc.common.txfmod.service.impl;

import com.brilliance.isc.bo.*;
import com.brilliance.isc.common.api.bch.service.BchService;
import com.brilliance.isc.common.cbsmod.service.XrtmodService;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.component.PtsptaToolComponent;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.context.SettleSession;
import com.brilliance.isc.common.counter.service.CounterService;
import com.brilliance.isc.common.esb.whj.IWhjFeign;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.common.txfmod.service.TxfmodService;
import com.brilliance.isc.common.txfmod.vo.TxfResult;
import com.brilliance.isc.common.txfmod.vo.TxfmodBizInfo;
import com.brilliance.isc.common.txfmod.vo.TxfmodVo;
import com.brilliance.isc.common.util.SettleExceptionUtils;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.common.vo.PtsptaVo;
import com.brilliance.isc.esb.model.inner.*;
import com.brilliance.isc.mda.dao.*;
import com.brilliance.mda.runtime.mda.IStream;
import com.brilliance.mda.runtime.mda.impl.Argument;
import com.brilliance.mda.runtime.mda.impl.StreamImpl;
import com.brilliance.mda.runtime.mda.util.*;
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;

@Service
public class TxfmodServiceImpl implements TxfmodService {
    Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    @Resource
    private CounterService counterService;
    @Resource
    private XrtmodService xrtmodService;
    @Resource
    private PtsptaToolComponent ptsptaToolComponent;
    @Resource
    private CodetableService codetableService;
    @Autowired(required = false)
    private IWhjFeign whjFeign;
    @Resource
    private TxpaymMapper txpaymMapper;
    @Resource
    private TxformMapper txformMapper;
    @Resource
    private TxflogMapper txflogMapper;
    @Resource
    private PtyMapper ptyMapper;
    @Resource
    private BopctyMapper bopctyMapper;
    @Resource
    private LidMapper lidMapper;
    @Resource
    private TxpregMapper txpregMapper;
    @Resource
    private DblMapper dblMapper;
    @Resource
    private TrnMapper trnMapper;
    @Resource
    private BopcodMapper bopcodMapper;
    @Resource
    private BchService bchService;


    @Override
    public void assertTxfmod(TxfmodVo txfmodVo,String transName,String payeecountcode,String trntyp,String pntinr,String stacty,
                             String countrycod,String hndtyp,String szflg,List<PtsptaVo> ptsList) {
        txfmodVo.getRec().setTransName(transName);
        txfmodVo.getRec().setPayeecountcode(payeecountcode);
        txfmodVo.getRec().setTrntyp(trntyp);
        txfmodVo.getRec().setPntinr(pntinr);
        txfmodVo.getRec().setStacty(stacty);
        txfmodVo.getRec().setCountrycod(countrycod);
        txfmodVo.getRec().setHndtyp(hndtyp);
        txfmodVo.getRec().setSzflg(szflg);
        txfmodVo.getRec().setPtsList(ptsList);
    }

    @Override
    public TxfmodVo subtxf(TxfmodVo txfmodVo) {
        txfmodVo.setWarningList(new ArrayList<>());
        Txform txform = txfmodVo.getTxform();
        // 先查询TXPAYM表，如果能找到最新的记录，且最新记录为业务受理状态（ACCEPT），则直接将记录查出并将信息带入到交易中，且界面验证已业务受理显示；
        // 如果没有找到记录或最新记录的状态不为业务受理状态（ACCEPT），则还是调用核验接口。
        Txpaym reqPaym = new Txpaym();
        reqPaym.setRcrdno(txfmodVo.getRcrdno());
        reqPaym.setDataverfcd(txfmodVo.getDataverfcd());
        Txpaym txpaym = txpaymMapper.selectMaxInrRecord(reqPaym);
        String bsnSts = "";
        if (txpaym != null) {
            bsnSts = txpaym.getBsnsts();
        }
        if ("ACCEPT".equalsIgnoreCase(bsnSts)) {
            String relflg = txformMapper.selectRecflg(txpaym.getBsnsrlno());
            Txform reqTxform = new Txform();
            reqTxform.setInr(txpaym.getTxfinr());
            txform = txformMapper.selectByPrimaryKey(reqTxform);
            if ("W".equalsIgnoreCase(relflg)) {
                txform.setSta("已占用");
            } else {
                txform.setSta("受理中");
                txfmodVo.setAcpflg("Y");
                txfmodVo.setHyflg("Y");
            }
            txfmodVo.setTxfrst("Y");
            Txpaym reqTxpaym = new Txpaym();
            reqTxpaym.setTxfinr(txform.getInr());
            txpaym = txpaymMapper.selectByTxfinr(reqTxpaym);
            txfmodVo.setTxpaym(txpaym);
            txfmodVo.setTxform(txform);
            txfmodVo.setWarningList(new ArrayList<>());
        } else {
            // 点击提交核验后，向国家外汇管理局跨境金融区块链服务平台发起请求预核验请求.不通过,显示不通过界面UNSUC；
            // 通过，则显示CHKP税务备案表核验界面，并带入税务备案表信息
            txfmodVo.setTxfrst("");
            SettleSession userSession = SettleContext.getUserSession();
            String decnum = userSession.getBch().getDecnum();
            String srvnum = Formats.format(Dates.now(), "YYYYMMDDhhmmssSSS");
            String flg = callTaxcheck(txfmodVo.getRcrdno(), txfmodVo.getDataverfcd(), decnum, srvnum);
            if (MdaUtils.compareTo(flg, "0") == 0) {
                //按照商议结果，接口负责解析报文信息，并将税务备案表信息存入到表中，接口将备案表TXFORM的inr传给国结，国结通过INR读取对应的记录。
                Txform reqTxform = new Txform();
                reqTxform.setSrvnum(srvnum);
                txform = txformMapper.selectBySrvnum(reqTxform);
                //找到对应的备案表信息后再加载报文中的付汇信息
                if (!MdaUtils.isEmpty(txform.getInr())) {
                    if ("PASS".equalsIgnoreCase(txform.getCheckresult())) {
                        Txpaym reqTxpaym = new Txpaym();
                        reqTxpaym.setTxfinr(txform.getInr());
                        txpaym = txpaymMapper.selectByTxfinr(reqTxpaym);
                        txform.setSta("核验通过");
                        txfmodVo.setTxfrst("Y");
                        txfmodVo.setHyflg("Y");
                        txfmodVo.setAcpflg("");
                        txfmodVo.setTxform(txform);
                        txfmodVo.setTxpaym(txpaym);
                        // 业务交易内，核验业务信息是否与备案表信息一致
                        if (Strings.pos("-GITSET-CPTOPN-BRTSET-BCTSET-", SettleContext.getDirectTransName()) > 0) {
                            ArrayList<TxfResult> txfResults = new ArrayList<>();
                            // 核验境外收款人国别
                            Argument<String> txfPayeeCtryCodBox = new Argument<String>();
                            if (getCtryCodeByName(txform.getPayeectrynm(), txfPayeeCtryCodBox)) {
                                String countcode = getVerifiedCtryCode(txfmodVo);
                                if (!MdaUtils.isEmpty(countcode) && MdaUtils.compareTo(countcode, txfPayeeCtryCodBox.value) != 0) {
                                    TxfResult txfResult = new TxfResult();
                                    txfResult.setCode("01");
                                    txfResult.setMessage("该笔备案表收款人国别与交易中收款人国别不一致!");
                                    txfResults.add(txfResult);
                                    txfmodVo.setErrorMsg("该笔备案表收款人国别与交易中收款人国别不一致!");
                                }
                            }
                            // 核验纳税人识别号
                            if (!MdaUtils.isEmpty(txpaym.getTaxpyidnfno())) {
                                String idcode = "";
                                String ecifjuscod = "";
                                String ptyinr = getVerifiedPtyinr(txfmodVo);
                                Pty pty = ptyMapper.selectByPtyinr(ptyinr);
                                if (pty == null) {
                                    TxfResult txfResult = new TxfResult();
                                    txfResult.setCode("02");
                                    txfResult.setMessage("交易中客户不存在!");
                                    txfResults.add(txfResult);
                                    txfmodVo.setErrorMsg("交易中客户不存在!");
                                }
                                idcode = pty.getIdcode();
                                ecifjuscod = pty.getEcifjuscod();
                                if (!MdaUtils.isEmpty(idcode)) {
                                    if (MdaUtils.compareTo(txpaym.getTaxpyidnfno(), idcode) != 0) {
                                        TxfResult txfResult = new TxfResult();
                                        txfResult.setCode("03");
                                        txfResult.setMessage("该笔备案表客户与交易中客户不一致!");
                                        txfResults.add(txfResult);
                                        txfmodVo.setErrorMsg("该笔备案表客户与交易中客户不一致!");
                                    }
                                } else {
                                    if (MdaUtils.compareTo(Strings.mid(txpaym.getTaxpyidnfno(), 9, 9), ecifjuscod) != 0) {
                                        TxfResult txfResult = new TxfResult();
                                        txfResult.setCode("03");
                                        txfResult.setMessage("该笔备案表客户与交易中客户不一致!");
                                        txfResults.add(txfResult);
                                        txfmodVo.setErrorMsg("该笔备案表客户与交易中客户不一致!");
                                    }
                                }
                            }
                            txfmodVo.setWarningList(txfResults);
                        }
                        savtxflog(txfmodVo, "核验");
                    } else {
                        txfmodVo.setTxfrst("N");
                        txfmodVo.setExplan(txform.getCheckresult());
                        txfmodVo.setHyflg("N");
                        txfmodVo.setAcpflg("");
                    }
                } else {
                    txfmodVo.setTxfrst("N");
                    txfmodVo.setExplan("未查询到该张备案表编号");
                    txfmodVo.setHyflg("N");
                    txfmodVo.setAcpflg("");
                }
            } else {
                String outtxt = "";
                switch (flg) {
                    case "1":
                        outtxt = "TAX_FORM_CODE_ERROR";
                        break;
                    case "2":
                        outtxt = "FORM_CODE_AUTH_CODE_MISMATCH";
                        break;
                    case "3":
                        outtxt = "TAX_FORM_INVALID";
                        break;
                    case "4":
                        outtxt = "USED_BY_SELF";
                        break;
                    case "5":
                        outtxt = "USED_BY_OTHER";
                        break;
                    case "6":
                        outtxt = "USED_BY_SELF_OTHER";
                        break;
                }
                txfmodVo.setTxfrst("N");
                txfmodVo.setHyflg("N");
                txfmodVo.setAcpflg("");
                String tblLabel = codetableService.getTblLabel(outtxt, "EXPLAN", "EN");
                txfmodVo.setExplan(tblLabel);
            }
        }
        return txfmodVo;
    }

    @Override
    public TxfmodVo busacp(TxfmodVo txfmodVo) {
        // 业务人员审核备案表无误后，点击“业务受理”按钮，向区块链平台发起业务受理请求.备案表业务受理，备案表状态为“已占用”，并返回结果。
        // 跳转至备案表业务受理详情页面
        SettleSession userSession = SettleContext.getUserSession();
        String decnum = userSession.getBch().getDecnum();
        String flg = callTaxaccept(txfmodVo.getRcrdno(), txfmodVo.getDataverfcd(), decnum);
        if (MdaUtils.compareTo(flg, "0") == 0) {
            // 更新成功后重新加载备案表信息
            Txpaym req = new Txpaym();
            req.setRcrdno(txfmodVo.getRcrdno());
            req.setDataverfcd(txfmodVo.getDataverfcd());
            Txpaym resultTxpaym = txpaymMapper.selectByRcrdnoAndDataVerfcd(req);
            Txform txform = new Txform();
            txform.setInr(resultTxpaym.getTxfinr());
            Txform resultTxform = txformMapper.selectByPrimaryKey(txform);
            txfmodVo.setTxpaym(resultTxpaym);
            txfmodVo.setTxform(resultTxform);
            txfmodVo.getTxform().setSta("已占用");
            txfmodVo.getTxform().setSta("受理中");
            txfmodVo.setAcpflg("Y");
            // 业务受理成功
            // 业务受理成功后，不允许再修改业务编号
            savtxflog(txfmodVo, "业务受理");
        } else {
            String outtxt = "";
            switch (flg) {
                case "1":
                    outtxt = "TAX_FORM_CODE_ERROR";
                    break;
                case "2":
                    outtxt = "FORM_CODE_AUTH_CODE_MISMATCH";
                    break;
                case "3":
                    outtxt = "TAX_FORM_INVALID";
                    break;
                case "4":
                    outtxt = "USED_BY_SELF";
                    break;
                case "5":
                    outtxt = "USED_BY_OTHER";
                    break;
                case "6":
                    outtxt = "USED_BY_SELF_OTHER";
                    break;
            }
            txfmodVo.setAcpflg("");
            String tblLabel = codetableService.getTblLabel(outtxt, "EXPLAN", "EN");
            txfmodVo.setExplan(tblLabel);
        }
        return txfmodVo;
    }


    @Override
    public void calpay(TxfmodVo txfmodVo) {
        // 付汇取消
        String relflg = txformMapper.selectRecflg(txfmodVo.getTxpaym().getBsnsrlno());
        if (MdaUtils.compareTo(relflg, "W") != 0) {
            String code = callTaxcancel(txfmodVo.getTxpaym().getBsnsrlno(), SettleContext.getUserSession().getBch().getDecnum());
            if ("0".equalsIgnoreCase(code)) {
                Txpaym txpaym = new Txpaym();
                txpaym.setBsnsrlno(txfmodVo.getTxpaym().getBsnsrlno());
                Txpaym txpaymResult = txpaymMapper.selectByBsnsrlno(txpaym);
                txfmodVo.setTxpaym(txpaymResult);
                Txform txform = new Txform();
                txform.setInr(txpaymResult.getTxfinr());
                Txform txformResult = txformMapper.selectByPrimaryKey(txform);
                txfmodVo.setTxform(txformResult);
                Txpreg txpreg = new Txpreg();
                txpreg.setTxfinr(txpaymResult.getTxfinr());
                List<Txpreg> txpregList = txpregMapper.selectByTxfinr(txpreg);
                txfmodVo.setReglst(txpregList);
                savtxflog(txfmodVo, "付汇取消");
            }
        } else {
            throw new CommonServiceException("该笔备案表编号有待复核记录！");
        }
    }

    private String callTaxcheck(String rcrdno, String dataverfcd, String decnum, String srvnum) {
        InnerReqTaxcheck innerReqTaxcheck = new InnerReqTaxcheck(rcrdno, dataverfcd, decnum, srvnum);
        InnerReq<InnerReqTaxcheck> innerReqTaxcheckInnerReq = new InnerReq<>(innerReqTaxcheck);
        InnerRes<InnerResTax> innerRes = whjFeign.callTaxcheck(innerReqTaxcheckInnerReq);
        if (innerRes != null && "0".equals(innerRes.header.code) && innerRes.DATA != null) {
            return innerRes.DATA.code;
        } else {
            if (innerRes != null) {
                throw new CommonServiceException(innerRes.header.description);
            }
        }
        return null;
    }

    private String callTaxaccept(String rcrdno, String dataverfcd, String decnum) {
        InnerReqTaxaccept innerReqTaxaccept = new InnerReqTaxaccept();
        innerReqTaxaccept.setTaxformcode(rcrdno);
        innerReqTaxaccept.setAuthcode(dataverfcd);
        innerReqTaxaccept.setBanksafecode(decnum);
        InnerReq<InnerReqTaxaccept> innerReqTaxacceptInnerReq = new InnerReq<>(innerReqTaxaccept);
        InnerRes<InnerResTax> innerRes = whjFeign.callTaxaccept(innerReqTaxacceptInnerReq);
        if (innerRes != null && "0".equals(innerRes.header.code) && innerRes.DATA != null) {
            return innerRes.DATA.code;
        } else {
            if (innerRes != null) {
                throw new CommonServiceException(innerRes.header.description);
            }
        }
        return null;
    }

    private String callTaxcancel(String taxpaymentcode, String banksafecode) {
        InnerReqTaxcancel innerReqTaxcancel = new InnerReqTaxcancel();
        innerReqTaxcancel.setTaxpaymentcode(taxpaymentcode);
        innerReqTaxcancel.setBanksafecode(banksafecode);
        InnerReq<InnerReqTaxcancel> innerReq = new InnerReq<>(innerReqTaxcancel);
        InnerRes<InnerResTax> innerRes = whjFeign.callTaxcancel(innerReq);
        if (innerRes != null && "0".equals(innerRes.header.code) && innerRes.DATA != null) {
            return innerRes.DATA.code;
        } else {
            if (innerRes != null) {
                throw new CommonServiceException(innerRes.header.description);
            }
        }
        return null;
    }

    private void savtxflog(TxfmodVo txfmod, String updtyp) {
        Txflog txflog = new Txflog();
        //!此表只插入，不更新
        String inr = counterService.dbCounterFormat("TXFLOG");
        txflog.setInr(inr);
        txflog.setTxforminr(txfmod.getTxform().getInr());
        txflog.setTxpayminr(txfmod.getTxpaym().getInr());
        txflog.setRcrdno(txfmod.getTxpaym().getRcrdno());
        txflog.setBsnsrlno(txfmod.getTxpaym().getBsnsrlno());
        txflog.setUpdtyp(updtyp);
        SettleSession userSession = SettleContext.getUserSession();
        txflog.setUpdusr(userSession.getUsr().getExtkey());
        txflog.setBranch(userSession.getBch().getBranch());
        txflog.setUpdtim(Dates.now());
        txflog.setInifrm(SettleContext.getTransName());
        txflogMapper.insert(txflog);
    }

    @Override
    public boolean isAmtAvailable(TxfmodVo txfmodVo) {
        boolean bool = false;
        //计算剩余可用金额（USD）
        calAvlAmt(txfmodVo);
        //获取业务金额（USD）
        BigDecimal relAmt = getVerifiedAmt(txfmodVo);
        if (MdaUtils.compareTo(relAmt, txfmodVo.getAvlamt()) <= 0) {
            bool = true;
        }
        return bool;

    }

    private void calAvlAmt(TxfmodVo txfmod) {
        //!获取剩余可用金额并，转换为等值美元
        txfmod.setAvlamt(new BigDecimal(0));
        Txform txform = txfmod.getTxform();
        BigDecimal tolamt = Strings.parseDecimal(txform.getCtramt());
        String cur = txform.getCcy();
        //若不能取到合同总金额
        if (MdaUtils.compareTo(tolamt, 0) == 0 || MdaUtils.isEmpty(cur)) {
            txfmod.setAvlamt(new BigDecimal(0));
        } else {
            if (MdaUtils.compareTo(cur, "USD") != 0) {
                xrtmodService.amtConvTypes(cur, tolamt, "S", "USD", "B", Dates.today());
            }
            txfmod.setAvlamt(Decimals.sub(tolamt, txfmod.getTxpaym().getBeenchkverfamt()));
        }
    }

    private BigDecimal getVerifiedAmt(TxfmodVo txfmodVo) {
        BigDecimal amt = txfmodVo.getRec().getAmt();
        String cur = txfmodVo.getRec().getCur();
        // 转换成美元
        if (!MdaUtils.isEmpty(cur) && !MdaUtils.isEmpty(amt)) {
            if (MdaUtils.compareTo(cur, "USD") != 0) {
                calcuteAMT_TXF(txfmodVo, cur, amt);
                amt = txfmodVo.getRelamt();
            }
        }
        return amt;
    }

    private void calcuteAMT_TXF(TxfmodVo txfmod, String argCur, BigDecimal argAmt) {
        // 转换为等值美元
        if (MdaUtils.compareTo(argAmt, 0) != 0 && MdaUtils.compareTo(argCur, "USD") != 0) {
            BigDecimal relamt = xrtmodService.amtConvTypes(argCur, argAmt, "S", "USD", "B", Dates.today());
            txfmod.setRelamt(relamt);
        } else {
            txfmod.setRelamt(argAmt);
        }
    }

    @Override
    public boolean getCtryCodeByName(String ctryNm, Argument<String> ctryCod) {
        // 通过国别全称获取三位国别码
        // 使用BOPCTY表
        ctryCod.value = "";
        if (MdaUtils.isEmpty(ctryNm)) {
            return false;
        }
        IStream codStm = new StreamImpl();
        Streams.streamClear(codStm);
        List<Bopcty> list = bopctyMapper.selectByTxtOrFultxt(ctryNm);
        if (list.size() == 1) {
            ctryCod.value = list.get(0).getCod();
            return true;
        } else {
            return false;
        }
    }

    @Override
    public TxfmodVo checkYesOrNo(TxfmodVo txfmodVo) {
        txfmodVo.setCheckflg("1");// 默认否
        String transName = txfmodVo.getRec().getTransName();
        // 老国结的 "1" ==> 新国结的"02"  均为服务贸易
        if ("CPTOPN".equalsIgnoreCase(transName) && "02".equalsIgnoreCase(txfmodVo.getRec().getTrntyp())) {
            return innerCheck(txfmodVo);
        } else if("BRTSET".equalsIgnoreCase(transName) || "BRTSET1".equalsIgnoreCase(transName) || "BCTSET".equalsIgnoreCase(transName) || "BCTSET1".equalsIgnoreCase(transName)){
            return innerCheck(txfmodVo);
        }
        return txfmodVo;
    }

    private TxfmodVo innerCheck(TxfmodVo txfmodVo){
        if(MdaUtils.isEmpty(txfmodVo.getTxfflg()) && MdaUtils.isEmpty(txfmodVo.getRec().getManbab())){
            if(!MdaUtils.isEmpty(txfmodVo.getRec().getAmt())){
                if(MdaUtils.compareTo(txfmodVo.getRec().getCur(),"USD") == 0){
                    if(MdaUtils.compareTo(txfmodVo.getRec().getAmt(),50000)>0){
                        txfmodVo.setCheckflg("0");
                        return txfmodVo;
                    }
                } else {
                    Argument<BigDecimal> rateBox = new Argument<BigDecimal>();
                    Argument<BigDecimal> sqrRatBox = new Argument<BigDecimal>();
                    xrtmodService.getratForENT(txfmodVo.getRec().getCur(), "S", "USD", "B", Dates.today(), rateBox, sqrRatBox);
                    BigDecimal rate = rateBox.value;
                    BigDecimal sqrRat = sqrRatBox.value;
                    BigDecimal cpdamt = Decimals.mul(txfmodVo.getRec().getAmt(), rate);
                    if(MdaUtils.compareTo(cpdamt,50000) > 0){
                        txfmodVo.setCheckflg("0");
                        return txfmodVo;
                    }
                }
            }
        }
        return txfmodVo;
    }

    @Override
    public void savtxf(TxfmodVo txfmodVo,String trninr,String rptno) {
        //更新备案表所属金融机构标识码
        if(!MdaUtils.isEmpty(txfmodVo.getTxform().getInr())) {
            String decnum = SettleContext.getUserSession().getBch().getDecnum();
            txfmodVo.getTxform().setDecnum(decnum);
            txfmodVo.getTxform().setTrninr(trninr);
            txformMapper.updateByPrimaryKeySelective(txfmodVo.getTxform());
            //应该只用存储TXPREG（付汇收支申报信息表），此表是复合交易后调用“备案表付汇确认”用的
            for (int i = 0; i < txfmodVo.getReglst().size(); i++) {
                Txpreg txpreg = txfmodVo.getReglst().get(i);
                txpreg.setTrninr(trninr);
                txpreg.setTxfinr(txfmodVo.getTxform().getInr());
                txpreg.setRcrdno(txfmodVo.getTxform().getRcrdno());
                txpreg.setBsnsrlno(txfmodVo.getTxpaym().getBsnsrlno());
                txpreg.setItnlincmpaydclrtnno(rptno);
                if(!MdaUtils.isEmpty(txpreg.getInr())) {
                    txpregMapper.updateByPrimaryKeySelective(txpreg);
                } else {
                    String inr = counterService.dbCounterFormat("TXPREG");
                    txpreg.setInr(inr);
                    txpregMapper.insertSelective(txpreg);
                }
            }
        }
    }

    @Override
    public String getVerifiedCtryCode(TxfmodVo txfmodVo) {
        TxfmodBizInfo rec = txfmodVo.getRec();
        String transName = rec.getTransName().toUpperCase();
        String countcode = "";
        switch (transName) {
            case "CPTOPN":
                countcode = rec.getPayeecountcode();
                break;
            case "BRTSET":
            case "BRTSET1":
                String pntinr = rec.getPntinr();
                Lid reqLid = new Lid();
                reqLid.setInr(pntinr);
                Lid lid = lidMapper.selectByPrimaryKey(reqLid);
                countcode = lid.getCountrycod();
                break;
            case "BCTSET":
            case "BCTSET1":
                String tmpCod = rec.getStacty();
                if (!MdaUtils.isEmpty(tmpCod)) {
                    countcode = codetableService.getTblLabel(tmpCod, "CTYCOD", "EN");
                }
                break;
            case "GITSET":
                countcode = rec.getCountrycod();
                break;
        }
        return countcode;
    }

    @Override
    public String getVerifiedPtyinr(TxfmodVo txfmodVo) {
        TxfmodBizInfo rec = txfmodVo.getRec();
        String transName = rec.getTransName().toUpperCase();
        String ptyinr = "";
        switch (transName) {
            case "CPTOPN":
                PtsptaVo orc = ptsptaToolComponent.getPtsFromListByRol(rec.getPtsList(), "ORC");
                ptyinr = orc.getPtyinr();
                break;
            case "GITSET":
                String hndtyp = rec.getHndtyp();
                if (MdaUtils.compareTo(hndtyp, "OT") == 0) {
                    PtsptaVo ben = ptsptaToolComponent.getPtsFromListByRol(rec.getPtsList(), "BEN");
                    ptyinr = ben.getPtyinr();
                } else {
                    PtsptaVo apl = ptsptaToolComponent.getPtsFromListByRol(rec.getPtsList(), "APL");
                    ptyinr = apl.getPtyinr();
                }
                break;
            case "BRTSET":
            case "BRTSET1":
                PtsptaVo apl = ptsptaToolComponent.getPtsFromListByRol(rec.getPtsList(), "APL");
                ptyinr = apl.getPtyinr();
                break;
            case "BCTSET":
            case "BCTSET1":
                PtsptaVo dre = ptsptaToolComponent.getPtsFromListByRol(rec.getPtsList(), "DRE");
                ptyinr = dre.getPtyinr();
                break;
        }
        return ptyinr;
    }

    @Override
    public void updatetxf(Trn trn, String rptno){
        String trninr = trn.getInr();
        Bch bch = bchService.getDirectAccBchByBchInr(trn.getBranchinr());
        //!更新TXPREG（付汇收支申报信息表）的申报号码并发送备案表付汇确认
        Txpreg txpreg = new Txpreg();
        txpreg.setTrninr(trninr);
        List<Txpreg> txpregList = txpregMapper.selectByTrninr(txpreg);
        if (txpregList == null || txpregList.size() == 0) {
            logger.error("备案表TXF后台服务,获取到的付汇收支申报记录为空,当前trninr:{}",trninr);
            return;
        }
        logger.warn("备案表TXF后台服务,获取到的付汇收支申报记录数为:{}",txpregList.size());
        if(MdaUtils.isEmpty(rptno)) {
            Dbl dbl = dblMapper.selectByTrninr(trninr);
            if (dbl != null) {
                rptno = dbl.getRptno();
                logger.info("备案表TXF后台服务,获取到的收支申报编号为:{}",rptno);
            } else {
                logger.warn("备案表TXF后台服务,获取到的收支申报编号为空!");
            }
        }
        if(!MdaUtils.isEmpty(rptno)) {
            for (int i = 0; i < txpregList.size(); i++) {
                Txpreg item = txpregList.get(i);
                item.setItnlincmpaydclrtnno(rptno);
                txpregMapper.updateByPrimaryKeySelective(item);
            }
            if (txpregList.size() > 0) {
                Txpreg txpreg1 = txpregList.get(0);
                callTaxconfirm(txpregList.get(0).getBsnsrlno(), txpregList, bch.getDecnum());
                TxfmodVo txfmodVo = new TxfmodVo();
                Txform txform = new Txform();
                txform.setInr(txpreg1.getTxfinr());
                Txpaym reqTxpaym = new Txpaym();
                reqTxpaym.setTxfinr(txpreg1.getTxfinr());
                Txpaym resultTxpaym = txpaymMapper.selectByTxfinr(reqTxpaym);
                if (resultTxpaym != null) {
                    Txpaym txpaym = new Txpaym();
                    txpaym.setInr(resultTxpaym.getInr());
                    txpaym.setRcrdno(resultTxpaym.getRcrdno());
                    txpaym.setBsnsrlno(resultTxpaym.getBsnsrlno());
                    txfmodVo.setTxpaym(txpaym);
                }
                txfmodVo.setTxform(txform);
                logger.info("备案表TXF后台服务,新增备案表日志：付汇确认!");
                savtxflog(txfmodVo, "付汇确认");
                logger.info("备案表TXF后台服务,付汇确认成功!");
            }
        }
    }

    @Override
    public void deltxf(Spt spt) {
        if (spt != null) {
            if ("CPD".equalsIgnoreCase(spt.getObjtyp()) || "BRD".equalsIgnoreCase(spt.getObjtyp()) || "BCD".equalsIgnoreCase(spt.getObjtyp())) {
                String frm = "";
                if ("CPD".equalsIgnoreCase(spt.getObjtyp())) {
                    frm = "CPTOPN";
                } else if("BRD".equalsIgnoreCase(spt.getObjtyp())){
                    frm = "BRTSET";
                } else if("BCD".equalsIgnoreCase(spt.getObjtyp())){
                    frm = "BCTSET";
                }
                logger.info("备案表-经办夹删除操作,当前交易码:{}",frm);
                if (StringUtils.isNotEmpty(frm)) {
                    Trn trn = trnMapper.selectByObjinrAndObjtyp(spt.getObjtyp().toUpperCase(), spt.getObjinr(),frm);
                    if (trn != null) {
                        logger.info("备案表-经办夹删除操作,获取trn记录的inr:{}",trn.getInr());
                        int i = txpaymMapper.selectTxpaymCount(trn.getInr());
                        if(i > 0){
                            logger.info("该业务有备案表信息，请后续TAKE交易后，在交易中先进行“付汇取消”操作！");
                            SettleExceptionUtils.sysDump("该业务有备案表信息，请后续TAKE交易后，在交易中先进行“付汇取消”操作！");
                        }
                    }
                    logger.warn("备案表-经办夹删除操作,获取trn记录为空！");
                }
            }
        }
    }

    @Override
    public List<Bopcod> selectBopcod() {
        List<Bopcod> bopcods = new ArrayList<>();
        SettleSession userSession = SettleContext.getUserSession();
        if (userSession != null) {
            Bch bch = userSession.getBch();
            if (bch != null) {
                if ("X".equalsIgnoreCase(bch.getZmqflg())) {
                    bopcods = bopcodMapper.getBopcodByCodAndZmq();
                } else {
                    bopcods = bopcodMapper.getBopcodByCodNoZmq();
                }
            }
        }
        return bopcods;
    }

    private String callTaxconfirm(String taxpaymentcode,List<Txpreg> reglst,String banksafecode){
        InnerReqTaxconfirm innerReqTaxconfirm = new InnerReqTaxconfirm();
        innerReqTaxconfirm.setTaxpaymentcode(taxpaymentcode);
        List<InnerReqTaxconfirm.ItemPayment> payments = new ArrayList<>();
        for (Txpreg txpreg : reglst) {
            InnerReqTaxconfirm.ItemPayment itemPayment = new InnerReqTaxconfirm.ItemPayment();
            itemPayment.setDeclarecode(txpreg.getItnlincmpaydclrtnno());
            itemPayment.setTransactioncode(txpreg.getTxncd());
            itemPayment.setPaymentcurrency(txpreg.getTxnccy());
            itemPayment.setPaymentamount(MdaUtils.toString(Numerics.toInt(Decimals.mul(txpreg.getPymtamt(),100))));
            itemPayment.setNote(txpreg.getRmk());
            payments.add(itemPayment);
        }
        innerReqTaxconfirm.setPayments(payments);
        innerReqTaxconfirm.setBanksafecode(banksafecode);
        InnerReq<InnerReqTaxconfirm> innerReq = new InnerReq<>(innerReqTaxconfirm);
        InnerRes<InnerResTax> innerRes = whjFeign.callTaxconfirm(innerReq);
        if (innerRes != null && "0".equals(innerRes.header.code) && innerRes.DATA != null) {
            return innerRes.DATA.code;
        } else {
            if (innerRes != null) {
                throw new CommonServiceException(innerRes.header.description);
            }
        }
        return null;
    }


}
