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


import com.brilliance.mda.runtime.mda.IStream;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Strings;
import com.brilliance.isc.bo.*;
import com.brilliance.isc.common.cache.pta.PtaCacheService;
import com.brilliance.isc.common.cache.pty.PtyCacheService;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.component.DyncDaoService;
import com.brilliance.isc.common.component.PtsptaToolComponent;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.ptspta.service.PtsptaService;
import com.brilliance.isc.common.sespay.service.SespayService;
import com.brilliance.isc.common.sespay.vo.SespayVo;
import com.brilliance.isc.common.setgll.vo.SetgllVo;
import com.brilliance.isc.common.setmod.vo.SetmodVo;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.common.vo.BizInfoVo;
import com.brilliance.isc.common.vo.PtsptaVo;
import com.brilliance.isc.mda.dao.BnmMapper;
import com.brilliance.isc.vo.BnmVo;
import com.brilliance.isc.vo.CipmodVo;
import com.brilliance.isc.vo.FxpmodVo;
import com.brilliance.isc.vo.model.SetgrpVo;
import com.brilliance.isc.vo.remit.CpdBizInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

@Service("sespayService")
public class SespayServiceImpl implements SespayService {

    @Resource
    private PtsptaToolComponent ptsptaToolComponent;

    @Autowired
    private PtyCacheService ptyCacheService;

    @Autowired
    private PtaCacheService ptaCacheService;

    @Autowired
    private DyncDaoService dyncDaoService;

    @Autowired
    private CodetableService codetableService;

    @Autowired
    private BnmMapper bnmMapper;

    @Resource
    private PtsptaService ptsptaService;

    /**
     * 給SespayVo和SetgrpVo计算。
     * @param setgll
     * @param setmod
     */
    public void recalcSesPay(SetgllVo setgll, SetmodVo setmod)
    {
        //BEI
        String cmtflg = "";
        int err = 0;
        if( MdaUtils.compareTo(SettleContext.getDirectTransName(),"BRTSET") == 0 || MdaUtils.compareTo(SettleContext.getDirectTransName(),"BCTSET") == 0 || MdaUtils.compareTo(SettleContext.getDirectTransName(),"GITSET") == 0 )
        {
            cmtflg = Utils.getFieldValue(setmod.getRec(),"cmtflg","");
        }
        //if not IsEmpty( SFTMT ) and BEIP\\PANSTA = PanStaShow then
        String hbkinr = NULLSTR;
        if( ! MdaUtils.isEmpty(setgll.getSftmt()) ) {
            // NOSTRO correspondent (server of the NOSTRO-account)
            // beneficary institution
            // - equal beneficiary if beneficiary is a bank (in this case, payment by 202 directly to that bank)
            //跨境人名币代理模式58A可改
            if( MdaUtils.compareTo(cmtflg,"C") != 0 && Strings.pos(setgll.getSetgrp().getRol().getPtytyp(),"B") > 0 && !isModified(setgll.getSetgrp(), "bei") ) {
                setgll.getSetgrp().setBei(deepClonePtspta(setgll.getSetgrp().getRol(), "BEI"));
            }
            else {
                // - if not, its defaulted to the housebank of the beneficiary, if defined
                if( !isModified(setgll.getSetgrp(), "bei") ) {
                    Pty pty = ptyCacheService.getPtyById(setgll.getSetgrp().getRol().getPtyinr());
                    if(pty != null){
                        hbkinr = pty.getHbkinr();
                    }
                    if( ! MdaUtils.isEmpty(hbkinr) ) {
                        if( MdaUtils.compareTo(setgll.getDirindflg(),"X") == 0 && MdaUtils.compareTo(setgll.getSftmt(),"103") == 0 )
                        {
                            setgll.getSetgrp().setAwi(ptsptaToolComponent.getPtsptaFromPtyINR(hbkinr));
                        }
                        else
                        {
                            setgll.getSetgrp().setBei(ptsptaToolComponent.getPtsptaFromPtyINR(hbkinr));

                        }
                    }
                }
            }
        }

        SespayVo sespayVo = setgll.getSespay();

        //------------------
        //756 与400报文的收报行单独处理
        //因为它与202的58a联动,而当58a变成58d时 756就变成letter了
        if( MdaUtils.isEmpty(setgll.getSetgrp().getSnd756().getPts().getExtkey()) ) {
            setgll.getSetgrp().setSnd756(deepClonePtspta(setgll.getSetgrp().getBei(), "SND756"));
        }
        // for direct payment MT 103 disable
        if( MdaUtils.compareTo(setgll.getDirindflg(),"X") == 0 && MdaUtils.compareTo(setgll.getSftmt(),"103") == 0 ) {
            PtsptaVo ptsptaVo = new PtsptaVo();
            ptsptaVo.reset();
            setgll.getSetgrp().setBei(ptsptaVo);
            sespayVo.setBeiacc("");
            //清算费用锁定服务
            String qsfysd = Utils.getFieldValue(setmod.getRec(),"cpdSwiftBizInfo//qsfysd","");
            if ("1".equals(qsfysd)) {
                String fwtgyh = Utils.getFieldValue(setmod.getRec(),"cpdSwiftBizInfo//fwtgyh","");
                if (StringUtils.isNotEmpty(fwtgyh)) {
                    Pta pta = ptaCacheService.selectByPtyextkeyAndUsg(fwtgyh, "MAA");
                    if (pta != null) {
                        PtsptaVo ptspta = ptsptaToolComponent.getPtsptaFromPtaINR(pta.getInr());
                        setgll.getSetgrp().setTmpint(ptspta);
                    }
                }
            } else {
                if (!isModified(setgll.getSetgrp(), "int")) {
                    PtsptaVo ptspta = new PtsptaVo();
                    ptspta.reset();
                    setgll.getSetgrp().setTmpint(ptspta);
                }
            }
        }

        if( !isModified(setgll.getSetgrp(), "rms") ) {
            setgll.getSetgrp().setRms(deepClonePtspta(setgll.getSetgrp().getRol(), "RMS"));
        }
        //境外电汇202cov改造
        //202报文界面58域为亮显必输，而sftmt=202判断条件有俩种情况
        //1、正常202报文界面58域需亮显
        //2、202cov报文采用103报文界面，在报文类型选择MT202后在切换回202cov时，需要此判断逻辑
        //3、202cov中清空灰显BEIACC字段
        //4、202cov中54域灰显54域账号字段灰显
        if( MdaUtils.compareTo(setgll.getSftmt(),"202") == 0 ) {
            if( get202covflg(setgll,setmod) ) {
                sespayVo.setBeiacc("");
            }
        }
        if(!MdaUtils.isEmpty(setgll.getSftmt())){
        //计算ownref Rule(target="det202cov",order=1000)
        if (!sespayVo.isModified("ownref")) {
            String ownref = "";
            String objtyp = setmod.getRec().getObjtyp();
            if ("GCD".equalsIgnoreCase(objtyp)) {
                String gidinr = Utils.getFieldValue(setmod.getRec(), "gidinr");
                ownref = dyncDaoService.dyncReadFieldByInr("gid", gidinr, "ownref");
            } else if ("NCD".equalsIgnoreCase(objtyp)) {
                String nidinr = Utils.getFieldValue(setmod.getRec(), "nidinr");
                ownref = dyncDaoService.dyncReadFieldByInr("nid", nidinr, "ownref");
            } else if ("MCD".equalsIgnoreCase(objtyp)) {
                ownref = Utils.getFieldValue(setmod.getRec(), "subref");
            } else if ("BRD".equalsIgnoreCase(objtyp) || "BDD".equalsIgnoreCase(objtyp)) {
                ownref = dyncDaoService.dyncReadFieldByInr(setmod.getRec().getPnttyp(), setmod.getRec().getPntinr(), "ownref");
            } else if ("BCD".equalsIgnoreCase(objtyp) || "BTD".equalsIgnoreCase(objtyp)) {
                ownref = setmod.getRec().getOwnref();
            }
            if ("DFTSET".equalsIgnoreCase(SettleContext.getTransName()) || "DFTMSG".equalsIgnoreCase(SettleContext.getTransName())) {
                ownref = setmod.getRec().getOwnref();
                String pnttyp = dyncDaoService.dyncReadFieldByInr(setmod.getRec().getObjtyp(), setmod.getRec().getObjinr(), "pnttyp");
                if ("BRD".equals(pnttyp) || "BCD".equals(pnttyp)) {
                    //信用证业务取单据编号
                    ownref = dyncDaoService.dyncReadFieldByInr(setmod.getRec().getObjtyp(), setmod.getRec().getObjinr(), "pntref");
                }
            }
            if (StringUtils.isEmpty(ownref)) {
                ownref = "NONREF";
            }
            sespayVo.setOwnref(ownref);
         }
        }
        //@Rule(target="det202cv",order=1100)
        //索赔赔付 202报文的52场赋值
        if ("756".equalsIgnoreCase(setgll.getSftmt())
                || "400".equalsIgnoreCase(setgll.getSftmt())
                || ("202".equalsIgnoreCase(setgll.getSftmt()) && ("NITSET".equalsIgnoreCase(SettleContext.getTransName()) || "NITPSE".equalsIgnoreCase(SettleContext.getTransName())))) {
            if (StringUtils.isEmpty(setgll.getSetgrp().getOri().getExtkey())) {
                String swfcod = SettleContext.getUserSession().getBch().getSwfcod();
                Pta pta = ptaCacheService.selectByPtyextkeyAndUsg(swfcod, "MAA");
                if (pta != null) {
                    setgll.getSetgrp().setOri(ptsptaToolComponent.getPtsptaFromPtaINR(pta.getInr()));
                }
            }
        }
        this.assertSwift(setgll, setmod);
        this.defaultStrinf202(sespayVo);
        this.defaultStrinf(sespayVo, setmod);
        //试算cips112
        this.assertCipmod(setgll, setmod);
        this.assertFxpmod(setgll, setmod);
    }

    private boolean isModified(SetgrpVo setgrpVo, String role){
        return setgrpVo.isModified(role);
    }


    private boolean get202covflg(SetgllVo setgllVo,SetmodVo setmodVo){
        if(MdaUtils.compareTo(SettleContext.getTransName(),"CPTOPN") == 0){
            String swftyp = Utils.getFieldValue(setmodVo.getRec(),"swftyp","");
            if(MdaUtils.compareTo(swftyp,"202") == 0){
                return true;
            }
        }
        return false;
    }

    /**
     * 复制Ptspta 并修改role
     * @param argPtsptaVo
     * @param srcRole
     * @return
     */
    private PtsptaVo deepClonePtspta(PtsptaVo argPtsptaVo, String srcRole) {
        PtsptaVo ptsptaVo = MdaUtils.deepClone(argPtsptaVo);
        ptsptaVo.setRol(srcRole.toUpperCase());
        if (ptsptaVo.getPts() != null) {
            ptsptaVo.getPts().setRol(srcRole.toUpperCase());
        }
        return ptsptaVo;
    }

    /**
     * @Default(target="strinf202",order=1000)
     * @param sespayVo
     */
    private void defaultStrinf202(SespayVo sespayVo) {
        if ("BRTSET".equals(SettleContext.getDirectTransName())) {
            if (!sespayVo.isModified("strinf202")) {
                String strinf202 = "/DEDUCT/" + CR + "/BNF/CBL CHGS *" + CR + "//SETT FEE *" + CR + "//DISC FEE *" + CR + "//AMENDMENT FEE  *";
                String comsystbl = sespayVo.getComsystbl();
                if (StringUtils.isNotEmpty(comsystbl)) {
                    String label = codetableService.getTblLabel(comsystbl, "COMTBL");
                    strinf202 +=  CR + "//" + label;
                }
                sespayVo.setStrinf202(strinf202);
            }
        }
    }

    /**
     * @Default(target="strinf",order=1000)
     * @param sespayVo
     */
    private void defaultStrinf(SespayVo sespayVo, SetmodVo setmod) {
        if ("CPTOPN".equals(SettleContext.getTransName())) {
            if (!sespayVo.isModified("strinf")) {
                String strinf = "";
                String qsfysd = Utils.getFieldValue(setmod.getRec(),"cpdSwiftBizInfo//qsfysd","");
                if ("1".equals(qsfysd)) {
                    strinf = "/PPRO/";
                }
                String comsystbl = sespayVo.getComsystbl();
                if (StringUtils.isNotEmpty(comsystbl)) {
                    String label = codetableService.getTblLabel(comsystbl, "COMTBL");
                    if (StringUtils.isNotEmpty(strinf)) {
                        strinf += CR + "//" + label;
                    } else {
                        strinf += "//" + label;
                    }
                }
                sespayVo.setStrinf(strinf);
            }
        }
    }

    /**
     * 试算cipmod
     * @param setgll
     */
    private void assertCipmod(SetgllVo setgll, SetmodVo setmodVo) {
        if (!"CIV".equals(setgll.getSftmt()) && !"CIU".equals(setgll.getSftmt())) {
            return;
        }
        BizInfoVo rec = setmodVo.getRec();
        CipmodVo cipmod = setgll.getSespay().getCipmod();
        String tranName = SettleContext.getDirectTransName();
        switch (tranName) {
            case "GITSET":
            case "GITPSE":
            case "NITSET":
            case "NITPSE":
                if ("BEN".equals(setgll.getRol()) && "PAC".equals(setgll.getDsp())) {
                    cipmod.setDafnzh(setgll.getAct());
                }
                break;
            case "BRTSET":
                if ("PRB".equals(setgll.getRol()) && "PAC".equals(setgll.getDsp())) {
                    cipmod.setDafnzh(setgll.getAct());
                }
                break;
            case "BCTSET":
                if ("RMI".equals(setgll.getRol()) && "PAC".equals(setgll.getDsp())) {
                    cipmod.setDafnzh(setgll.getAct());
                }
                break;
            case "DFTMSG":
                if ("DFF".equals(setgll.getRol()) && "PAC".equals(setgll.getDsp())) {
                    cipmod.setDafnzh(setgll.getAct());
                }
                break;
            case "CPTOPN":
            case "CPTECO":
                if ("PYE".equals(setgll.getRol()) && "PAC".equals(setgll.getDsp())) {
                    cipmod.setDafnzh(setgll.getAct());
                }
                break;
            default:
                break;
        }
        String branch = "EVERCNBJXXX";
        cipmod.setStaonebch(branch);
        BnmVo bnmVo = new BnmVo();
        bnmVo.setBch(branch);
        bnmVo.setCyzgbs("DRPT");
        List<Bnm> bnmList = bnmMapper.getCyhhCyzwmc(bnmVo);
        if (bnmList != null && bnmList.size() > 0) {
            cipmod.setStaonebchnam(bnmList.get(0).getCyzwmc());
        }
        cipmod.setDafnmc("国结系统结算款项");
        Bch bch = SettleContext.getUserSession().getBch();
        if(!cipmod.isModified("fkrkhh") && !cipmod.isModified("fukrhm")) {
            //付款人开户行
            if (bch != null) {
                cipmod.setFkrkhh(bch.getSwfcod());
                cipmod.setFukrhm(bch.getBchname());
            }
        }
        //付款行
        if (bch != null) {
            cipmod.setFkhkhh(bch.getSwfcod());
            cipmod.setFkkhmc(bch.getBchname());
        }
        if (StringUtils.isEmpty(cipmod.getDddbsh())) {
            //brtset需要传lid的ownref
            String pntref = rec.getPntref();
            if (StringUtils.isNotEmpty(pntref)) {
                cipmod.setDddbsh(pntref);
            } else {
                cipmod.setDddbsh(rec.getOwnref());
            }
        }
        cipmod.setFkkhzh(cipmod.getDafnzh());
        if(MdaUtils.isEmpty(cipmod.getDdmsu1())) {
            cipmod.setDdmsu1("NA");
        }
        if(MdaUtils.isEmpty(cipmod.getDdmisu())) {
            cipmod.setDdmisu("NA");
        }
        if(MdaUtils.isEmpty(cipmod.getDdbhao())) {
            cipmod.setDdbhao("NA");
        }
        if (!cipmod.isModified("commen")) {
            StringBuilder sb = new StringBuilder();
            String zmqflg = "";
            if (bch != null) {
                zmqflg = bch.getZmqflg();
            }
            if ("X".equals(zmqflg)) {
                String zmqacc = setmodVo.getZmqacc();
                this.appendTxt(sb, zmqacc);
            } else {
                if ("CIU".equals(setgll.getSftmt())) {
                    String orcact = Utils.getFieldValue(rec, "orcact", "");
                    if (StringUtils.isNotEmpty(orcact)) {
                        String addact = "REMITTERS ACC";
                        this.appendTxt(sb, addact);
                        String addact2 = "NO." + orcact;
                        this.appendTxt(sb, addact2);
                    }
                }
            }
            //电汇凭证
            String flg = Utils.getFieldValue(rec, "cpdCipsBizInfo//flg", "");
            if ("X".equals(flg)) {
                String label = Strings.getText("请按$1报文格式发报!", "CIU".equals(setgll.getSftmt())?"cips111":"cips112");
                this.appendTxt(sb, label);
            } else {
                this.appendTxt(sb, rec.getOwnref());
            }
            cipmod.setCommen(sb.toString());
        }
        if (!cipmod.isModified("bustyp")) {
            String bustyp = Utils.getFieldValue(rec, "cpdCipsBizInfo//bustyp", "");
            if (StringUtils.isNotEmpty(bustyp)) {
                cipmod.setBustyp(bustyp);
            }
            if ("CIV".equals(setgll.getSftmt()) && StringUtils.isEmpty(cipmod.getBustyp())) {
                cipmod.setBustyp("FTFX");
            }
        }
        if ("CIU".equals(setgll.getSftmt()) && !cipmod.isModified("feecod")) {
            String feecod = Utils.getFieldValue(rec, "detchgcod", "");
            if (StringUtils.isEmpty(feecod)) {
                feecod = "SHAR";
            }
            cipmod.setFeecod(feecod);
        }
        if ("CIU".equals(setgll.getSftmt())) {
            //汇款人常驻国家/地区代码
            String fkrzgj = Utils.getFieldValue(rec, "draweecountcode", "");
            if (StringUtils.isNotEmpty(fkrzgj)) {
                if (fkrzgj.length() == 3) {
                    String value = codetableService.getTblKey(fkrzgj, "CTYCOD");
                    cipmod.setFkrzgj(value);
                } else {
                    cipmod.setFkrzgj(fkrzgj);
                }
            }
            //收款人常驻国家（地区）代码
            String skrzgj = Utils.getFieldValue(rec, "payeecountcode", "");
            if (StringUtils.isNotEmpty(skrzgj)) {
                if (skrzgj.length() == 3) {
                    String value = codetableService.getTblKey(skrzgj, "CTYCOD");
                    cipmod.setSkrzgj(value);
                } else {
                    cipmod.setSkrzgj(skrzgj);
                }
            }
            //汇款人组织机构代码
            String fkrzhj = Utils.getFieldValue(rec, "cpdCipsBizInfo//fkrzhj", "");
            cipmod.setFkrzhj(fkrzhj);
            //原始金额、币种
            String cur33b = Utils.getFieldValue(rec, "cpdCipsBizInfo//cur33b", "");
            BigDecimal amt33b = Utils.getFieldValue(rec, "cpdCipsBizInfo//amt33b", BigDecimal.ZERO);
            cipmod.setCur33b(cur33b);
            cipmod.setAmt33b(amt33b);
        }
        if ("CIV".equals(setgll.getSftmt())) {
            if ("X".equalsIgnoreCase(cipmod.getCovflg())) {
                String fkrzhj = Utils.getFieldValue(rec, "cpdCipsBizInfo//fkrzhj", "");
                //COV付款人组织机构代码
                cipmod.setCfkrzj(fkrzhj);
            }
        }

        //汇款人名称地址 收款人名称地址
        if (bch != null) {
            cipmod.setOrcact(bch.getBranch() + "0121200000001");
        }
        String transName = SettleContext.getDirectTransName();
        if ("CPTOPN".equals(transName)) {
            CpdBizInfoVo cpdBizInfoVo = (CpdBizInfoVo) rec;
            Cbb max = setmodVo.getCbsMap().getOrDefault("MAX", new Cbb());
            SetgllVo setgllVo = null;
            for (SetgllVo item : setmodVo.getSetglg().getSetgll()) {
                IStream amtidsstm = item.getAmtidsstm();
                boolean onlyfeeflag = false;
                for (String row : amtidsstm.getRows()) {
                    if (row.startsWith("*SETFEG")){
                        onlyfeeflag = true;
                        break;
                    }
                }
                if (onlyfeeflag) {
                    continue;
                }
                if ("LOD".equalsIgnoreCase(item.getDsp()) && "ORC".equalsIgnoreCase(item.getRol()) && item.getCur().equalsIgnoreCase(max.getCur())) {
                    setgllVo = item;
                    break;
                }
            }
            if (bch != null && "X".equalsIgnoreCase(bch.getZmqflg())) {
                cipmod.setRelorcact(setmodVo.getZmqacc());
            } else {
                if (setgllVo != null) {
                    cipmod.setRelorcact(setgllVo.getAct());
                } else {
                    cipmod.setRelorcact(cpdBizInfoVo.getOrcact());
                }
            }
            if (StringUtils.isEmpty(cipmod.getRelorcact())) {
                cipmod.setRelorcact(cpdBizInfoVo.getOrcact());
            }
            cipmod.setOrcnam(cpdBizInfoVo.getOrcnam());
            cipmod.setOrcadr(cpdBizInfoVo.getOrcadr());
            cipmod.setPyeact(cpdBizInfoVo.getPyeact());
            cipmod.setPyenam(cpdBizInfoVo.getPyenam());
            cipmod.setPyeadr(cpdBizInfoVo.getPyeadr());
            if (!cipmod.isModified("pyebchkey")) {
                cipmod.setPyebchkey(Utils.getFieldValue(rec, "pyebchkey", ""));
            }
            if (!cipmod.isModified("reconebch")) {
                cipmod.setReconebch(cpdBizInfoVo.getReconebch());
                BnmVo bnmVoReq = new BnmVo();
                bnmVo.setBch(cpdBizInfoVo.getReconebch());
                bnmVo.setCyzgbs("DRPT");
                List<Bnm> bnmListR = bnmMapper.getCyhhCyzwmc(bnmVoReq);
                if (!cipmod.isModified("reconebchnam") && bnmList != null && bnmListR.size() > 0) {
                    cipmod.setReconebchnam(bnmListR.get(0).getCyzwmc());
                }
            }
            if (!cipmod.isModified("skfyzh")) {
                cipmod.setSkfyzh(Utils.getFieldValue(rec, "cpdCipsBizInfo//skfyzh", ""));
            }
        } else {
            List<PtsptaVo> ptsList = setmodVo.getPtsList();
            String orcrol = "";
            String pyerol = "";
            switch (transName) {
                case "BCTSET":
                    orcrol = "DRE";
                    pyerol = "DRR";
                    break;
                case "BRTSET":
                    orcrol = "APL";
                    pyerol = "BEN";
                    break;
                case "GITSET":
                case "GITPSE":
                case "NITSET":
                case "NITPSE":
                    orcrol = "APL";
                    pyerol = "BEN";
                    break;
                case "DFTMSG":
                    break;
                default:
                    break;
            }
            if (StringUtils.isNotEmpty(orcrol)) {
                PtsptaVo orc = ptsptaToolComponent.getPtsFromListByRol(ptsList, orcrol);
                if (orc != null) {
                    Pta pta = ptaCacheService.getPtaByInr(orc.getPtainr());
                    if (pta != null) {
                        cipmod.setOrcnam(pta.getNam());
                    }
                    if (orc.getPts() != null) {
                        String address = StringUtils.isEmpty(orc.getPts().getCnadr()) ? orc.getPts().getEnadr() : orc.getPts().getCnadr();
                        cipmod.setOrcadr(address);
                    }
                }
            }
            //this.getTrnmod().getCnd().setPyeact( this.getTrnmod().getPyeact());
            //@Default(target="trnmod.pyenam",order=1000)
            PtsptaVo pye = ptsptaToolComponent.getPtsFromListByRol(ptsList, pyerol);
            if (pye != null) {
                Pta pta = ptaCacheService.getPtaByInr(pye.getPtainr());
                if (pta != null) {
                    cipmod.setPyenam(pta.getNam());
                }
                if (pye.getPts() != null) {
                    String address = StringUtils.isEmpty(pye.getPts().getCnadr()) ? pye.getPts().getEnadr() : pye.getPts().getCnadr();
                    cipmod.setPyeadr(address);
                }
            }
        }
    }

    /**
     * 试算fxpmod
     * @param setgll
     * @param setmodVo
     */
    private void assertFxpmod(SetgllVo setgll, SetmodVo setmodVo) {
        if (!"111".equals(setgll.getSftmt()) && !"112".equals(setgll.getSftmt())) {
            return;
        }
        FxpmodVo fxpmod = setgll.getSespay().getFxpmod();
        Bch bch = SettleContext.getUserSession().getBch();
        if (bch != null) {
            fxpmod.setSndbch(bch.getSwfcod());
            fxpmod.setSndbchnam(bch.getBchname());
        }
        fxpmod.setFmttyp(setgll.getSftmt());
        if(StringUtils.isEmpty(fxpmod.getRelatedref()) && !fxpmod.isModified("relatedref")) {
            fxpmod.setRelatedref("NONREF");
        }
        fxpmod.setCur(setgll.getAcccur());
        fxpmod.setAmt(setgll.getAccamt().abs());
        BizInfoVo rec = setmodVo.getRec();
        String tranName = SettleContext.getDirectTransName();
        if ("CPTOPN".equalsIgnoreCase(tranName)) {
            Cbb max = setmodVo.getCbsMap().getOrDefault("MAX", new Cbb());
            SetgllVo setgllVo = null;
            for (SetgllVo item : setmodVo.getSetglg().getSetgll()) {
                IStream amtidsstm = item.getAmtidsstm();
                boolean onlyfeeflag = false;
                for (String row : amtidsstm.getRows()) {
                    if (row.startsWith("*SETFEG")){
                        onlyfeeflag = true;
                        break;
                    }
                }
                if (onlyfeeflag) {
                    continue;
                }
                if ("LOD".equalsIgnoreCase(item.getDsp()) && "ORC".equalsIgnoreCase(item.getRol()) && item.getCur().equalsIgnoreCase(max.getCur())) {
                    setgllVo = item;
                    break;
                }
            }
            if (bch != null && "X".equalsIgnoreCase(bch.getZmqflg())) {
                fxpmod.setOrcact(setmodVo.getZmqacc());
            } else {
                if (setgllVo != null) {
                    if (!fxpmod.isModified("orcact")) {
                        fxpmod.setOrcact(setgllVo.getAct());
                    }
                } else {
                    if (!fxpmod.isModified("orcact")) {
                        fxpmod.setOrcact(Utils.getFieldValue(rec, "orcact", ""));
                    }
                }
            }
            if (StringUtils.isEmpty(fxpmod.getOrcact())) {
                if (!fxpmod.isModified("orcact")) {
                    fxpmod.setOrcact(Utils.getFieldValue(rec, "orcact", ""));
                }
            }
        } else {
            if (!fxpmod.isModified("orcact")) {
                fxpmod.setOrcact(Utils.getFieldValue(rec, "orcact", ""));
            }
        }
        if (!fxpmod.isModified("orcnam")) {
            fxpmod.setOrcnam(Utils.getFieldValue(rec, "cpdJnwbBizInfo//orcnam", ""));
        }
        if (!fxpmod.isModified("orcadr")) {
            fxpmod.setOrcadr(Utils.getFieldValue(rec, "cpdJnwbBizInfo//orcadr", ""));
        }
        if (!fxpmod.isModified("resbch")) {
            fxpmod.setResbch(Utils.getFieldValue(rec, "cpdJnwbBizInfo//resbch", ""));
        }
        if (!fxpmod.isModified("resbchnam")) {
            fxpmod.setResbchnam(Utils.getFieldValue(rec, "cpdJnwbBizInfo//resbchnam", ""));
        }
        PtsptaVo ptsptaVo = ptsptaToolComponent.getPtsFromListByRol(setmodVo.getPtsList(), "ORC");
        if (ptsptaVo != null) {
            Pty pty = ptyCacheService.getPtyById(ptsptaVo.getPtyinr());
            if (pty != null) {
                fxpmod.setOrcext(pty.getExtkey());
            }
        }
        if(ptsptaToolComponent.ptsIsRolSet(setmodVo.getPtsList(), "PYB")){
            PtsptaVo pyb = ptsptaToolComponent.getPtsFromListByRol(setmodVo.getPtsList(), "PYB");
            fxpmod.setPyb(pyb);
        }
        if (!fxpmod.isModified("commet")) {
            fxpmod.setCommet(Utils.getFieldValue(rec, "cpdJnwbBizInfo//commet", ""));
        }
        if (!fxpmod.isModified("pyeact")) {
            fxpmod.setPyeact(Utils.getFieldValue(rec, "pyeact", ""));
        }
        if (!fxpmod.isModified("pyenam")) {
            fxpmod.setPyenam(Utils.getFieldValue(rec, "cpdJnwbBizInfo//pyenam", ""));
        }
        if (!fxpmod.isModified("pyeadr")) {
            fxpmod.setPyeadr(Utils.getFieldValue(rec, "cpdJnwbBizInfo//pyeadr", ""));
        }
        Date valdat = Utils.getFieldValue(rec, "valdat", null);
        if (valdat == null) {
            valdat = Utils.getFieldValue(rec, "stttendat", null);
        }
        fxpmod.setValdat(valdat);
        Date opndat = Utils.getFieldValue(rec, "cpdJnwbBizInfo//opndat", null);
        if (opndat != null) {
            fxpmod.setOpndat(opndat);
        }
        if (fxpmod.getOpndat() == null) {
            fxpmod.setOpndat(valdat);
        }
        fxpmod.setFeetyp(Utils.getFieldValue(rec, "detchgcod", ""));
        if ("112".equals(fxpmod.getFmttyp())) {
            fxpmod.setTxntyp("A200");
            fxpmod.setBustyp("09110");
        } else if ("111".equals(fxpmod.getFmttyp())) {
            fxpmod.setTxntyp("A100");
            fxpmod.setBustyp(Utils.getFieldValue(rec, "cpdJnwbBizInfo//bustyp"));
            fxpmod.setAcctyp(Utils.getFieldValue(rec, "cpdJnwbBizInfo//acctyp"));
        }
    }

    private void assertSwift(SetgllVo setgll, SetmodVo setmodVo){
        if (("103".equalsIgnoreCase(setgll.getSftmt()) || "202".equalsIgnoreCase(setgll.getSftmt())) && "CPTOPN".equalsIgnoreCase(SettleContext.getTransName())) {
            if (StringUtils.isEmpty(setgll.getSetgrp().getOri().getExtkey())) {
                String swfcod = SettleContext.getUserSession().getBch().getSwfcod();
                Pta pta = ptaCacheService.selectByPtyextkeyAndUsg(swfcod, "MAA");
                if (pta != null) {
                    setgll.getSetgrp().setOri(ptsptaToolComponent.getPtsptaFromPtaINR(pta.getInr()));
                }
            }
            // 汇出汇款 报文类型为MT103、MT202COV
            if ("103".equalsIgnoreCase(setmodVo.getRec().getSwftyp()) || "202".equalsIgnoreCase(setmodVo.getRec().getSwftyp())) {
                String blkt70 = Utils.getFieldValue(setmodVo.getRec(), "cpdSwiftBizInfo//blkt70", "");
                if (!setgll.getSespay().isModified("blkt70")) {
                    setgll.getSespay().setBlkt70(blkt70);
                }
                String pyebchkey = Utils.getFieldValue(setmodVo.getRec(), "pyebchkey", "");
                String pyebchadr = Utils.getFieldValue(setmodVo.getRec(), "pyebchadr", "");
                if (!isModified(setgll.getSetgrp(), "awi")) {
                    if (StringUtils.isNotEmpty(pyebchkey)) {
                        Pta pta = ptaCacheService.selectByPtyextkeyAndUsg(pyebchkey, "MAA");
                        if (pta != null) {
                            setgll.getSetgrp().setAwi(ptsptaToolComponent.getPtsptaFromPtaINR(pta.getInr()));
                        } else {
                            if (StringUtils.isNotEmpty(pyebchadr)) {
                                PtsptaVo ptsptaVo = new PtsptaVo();
                                ptsptaVo.setRol("AWI");
                                ptsptaVo.setFlg(false);
                                ptsptaVo.setTypflg("C");
                                ptsptaVo.setLanguage("EN");
                                ptsptaVo.setPtainr("");
                                ptsptaVo.setAdrblk(pyebchadr);
                                Map<String, Object> stringObjectMap = ptsptaService.ptsTmpAdrAddAuto(ptsptaVo);
                                if (!stringObjectMap.containsKey("errorMsg")) {
                                    PtsptaVo ptsptaVoTmp = (PtsptaVo) stringObjectMap.get("ptsptaVo");
                                    if (ptsptaVoTmp != null) {
                                        setgll.getSetgrp().setAwi(ptsptaVoTmp);
                                        ptsptaToolComponent.fillPtsptaAllProperties(setgll.getSetgrp().getAwi());
                                    }
                                }
                            }
                        }
                    } else {
                        if (StringUtils.isNotEmpty(pyebchadr)) {
                            PtsptaVo ptsptaVo = new PtsptaVo();
                            ptsptaVo.setRol("AWI");
                            ptsptaVo.setFlg(false);
                            ptsptaVo.setTypflg("C");
                            ptsptaVo.setLanguage("EN");
                            ptsptaVo.setPtainr("");
                            ptsptaVo.setAdrblk(pyebchadr);
                            Map<String, Object> stringObjectMap = ptsptaService.ptsTmpAdrAddAuto(ptsptaVo);
                            if (!stringObjectMap.containsKey("errorMsg")) {
                                PtsptaVo ptsptaVoTmp = (PtsptaVo) stringObjectMap.get("ptsptaVo");
                                if (ptsptaVoTmp != null) {
                                    setgll.getSetgrp().setAwi(ptsptaVoTmp);
                                    ptsptaToolComponent.fillPtsptaAllProperties(setgll.getSetgrp().getAwi());
                                }
                            }
                        }
                    }
                }
                // T22来报 将【收款人开户银行在其代理行账号】带入新国结57a上方栏位的account
                String acc54 = Utils.getFieldValue(setmodVo.getRec(), "acc54", "");
                if (!setgll.getSespay().isModified("awiacc") && StringUtils.isNotEmpty(acc54)) {
                    setgll.getSespay().setAwiacc(acc54);
                }
                String bic54 = Utils.getFieldValue(setmodVo.getRec(), "bic54", "");
                String adr54 = Utils.getFieldValue(setmodVo.getRec(), "adr54", "");
                if (!isModified(setgll.getSetgrp(), "int")) {
                    if (StringUtils.isNotEmpty(bic54)) {
                        Pta pta = ptaCacheService.selectByPtyextkeyAndUsg(bic54, "MAA");
                        if (pta != null) {
                            setgll.getSetgrp().setTmpint(ptsptaToolComponent.getPtsptaFromPtaINR(pta.getInr()));
                        } else {
                            if (StringUtils.isNotEmpty(adr54)) {
                                PtsptaVo ptsptaVo = new PtsptaVo();
                                ptsptaVo.setRol("INT");
                                ptsptaVo.setFlg(false);
                                ptsptaVo.setTypflg("C");
                                ptsptaVo.setLanguage("EN");
                                ptsptaVo.setPtainr("");
                                ptsptaVo.setAdrblk(adr54);
                                Map<String, Object> stringObjectMap = ptsptaService.ptsTmpAdrAddAuto(ptsptaVo);
                                if (!stringObjectMap.containsKey("errorMsg")) {
                                    PtsptaVo ptsptaVoTmp = (PtsptaVo) stringObjectMap.get("ptsptaVo");
                                    if (ptsptaVoTmp != null) {
                                        setgll.getSetgrp().setTmpint(ptsptaVoTmp);
                                        ptsptaToolComponent.fillPtsptaAllProperties(setgll.getSetgrp().getTmpint());
                                    }
                                }
                            }
                        }
                    } else {
                        if (StringUtils.isNotEmpty(adr54)) {
                            PtsptaVo ptsptaVo = new PtsptaVo();
                            ptsptaVo.setRol("INT");
                            ptsptaVo.setFlg(false);
                            ptsptaVo.setTypflg("C");
                            ptsptaVo.setLanguage("EN");
                            ptsptaVo.setPtainr("");
                            ptsptaVo.setAdrblk(adr54);
                            Map<String, Object> stringObjectMap = ptsptaService.ptsTmpAdrAddAuto(ptsptaVo);
                            if (!stringObjectMap.containsKey("errorMsg")) {
                                PtsptaVo ptsptaVoTmp = (PtsptaVo) stringObjectMap.get("ptsptaVo");
                                if (ptsptaVoTmp != null) {
                                    setgll.getSetgrp().setTmpint(ptsptaVoTmp);
                                    ptsptaToolComponent.fillPtsptaAllProperties(setgll.getSetgrp().getTmpint());
                                }
                            }
                        }
                    }
                }

            }
            //  汇出汇款 报文类型为MT202
            if ("200".equalsIgnoreCase(setmodVo.getRec().getSwftyp())) {
                String ownref = Utils.getFieldValue(setmodVo.getRec(), "cpdSwiftBizInfo//ownref", "NONREF");
                if (StringUtils.isEmpty(ownref)) {
                    ownref = "NONREF";
                }
                setgll.getSespay().setOwnref(ownref);
            }


        }
    }

    private void appendTxt(StringBuilder sb, String txt) {
        if (StringUtils.isNotEmpty(txt)) {
            if (sb.length() == 0) {
                sb.append(txt);
            } else {
                sb.append(CR).append(txt);
            }
        }
    }

}
