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

import com.brilliance.mda.runtime.mda.impl.Argument;
import com.brilliance.mda.runtime.mda.util.*;
import com.brilliance.isc.bo.Act;
import com.brilliance.isc.bo.Cbe;
import com.brilliance.isc.bo.Pty;
import com.brilliance.isc.common.cache.pty.PtyCacheService;
import com.brilliance.isc.common.cbsmod.service.CbsmodService;
import com.brilliance.isc.common.cbsmod.service.LscmodService;
import com.brilliance.isc.common.cbsmod.service.XrtmodService;
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.glemod.service.GlemodService;
import com.brilliance.isc.common.glemod.vo.GlemodVo;
import com.brilliance.isc.common.liaall.service.LiaallService;
import com.brilliance.isc.common.liaallg.vo.LiaallgVo;
import com.brilliance.isc.common.liaone.service.LiaoneService;
import com.brilliance.isc.common.liaone.vo.AcpliaVo;
import com.brilliance.isc.common.transaction.help.TransactionHelpService;
import com.brilliance.isc.common.trnism.service.TrnismService;
import com.brilliance.isc.common.trnmod.vo.TrnmodVo;
import com.brilliance.isc.common.util.SettleExceptionUtils;
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.common.vo.SimpleModuleVo;
import com.brilliance.isc.mda.dao.ActMapper;
import com.brilliance.isc.mda.dao.CbeMapper;
import com.brilliance.isc.mda.dao.PublicMapper;
import com.brilliance.isc.utils.StringUtils;
import com.google.common.collect.ImmutableBiMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

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

@Service("liaoneService")
public class LiaoneServiceImpl implements LiaoneService {

    private static Logger log = LoggerFactory.getLogger(LiaoneServiceImpl.class);

    @Autowired
    private GlemodService glemodService;

    @Autowired
    private XrtmodService xrtmodService;

    @Autowired
    private LiaallService liaallService;

    @Autowired
    private CbsmodService cbsmodService;

    @Autowired
    private TrnismService trnismService;

    @Autowired
    private LscmodService lscmodService;

    @Autowired
    private PtsptaToolComponent ptsptaToolComponent;

    @Autowired
    private TransactionHelpService transactionHelpService;

    @Autowired
    private ActMapper actMapper;

    @Autowired
    private PublicMapper publicMapper;

    @Autowired
    private PtyCacheService ptyCacheService;

    @Autowired
    private DyncDaoService dyncDaoService;

    @Autowired
    private CbeMapper cbeMapper;

    @Override
    public String getAvailAcc(AcpliaVo acpliaVO) {
        String actval = "";
        String termType = NULLSTR;
        String termId = NULLSTR;
        String acc = NULLSTR;
        Argument<String> _accBox = Argument.box(acc);
        String objinr = NULLSTR;
        String sql = NULLSTR;
        String trmCod = NULLSTR;
        String trmTyp = NULLSTR;
        Argument<String> _trmTypBox = Argument.box(trmTyp);
        String hndTyp = NULLSTR;
        String gartyp = NULLSTR;
        String segtyp = NULLSTR;
        String ptyinr = NULLSTR;
        BizInfoVo rec = transactionHelpService.getLiaallSet().getRec();
        Argument<String> _ptyinrBox = Argument.box(ptyinr);
//        if (MdaUtils.isEmpty(actval)) {
        // account Defaulting
        termType = "AS"; // 5.01有判断，5.05应该是根据正负号判断借贷
        termId = getLiaTermKey(termType,acpliaVO);
        if (!MdaUtils.isEmpty(termId)) {
            acc = "";
            //根据objtyp在注册的simpleModuleList中查找对应的objinr
            List<SimpleModuleVo> allSimpelModuleList = new ArrayList<>();
            allSimpelModuleList.add(SimpleModuleVo.buildModule(rec));
            List<SimpleModuleVo> simpleModuleList = Utils.toListObject(SimpleModuleVo.class, liaallService.liaallParGet("ADDMODULE", "ALL"));
            if (simpleModuleList != null && simpleModuleList.size() > 0) {
                allSimpelModuleList.addAll(simpleModuleList);
            }
            for(SimpleModuleVo simpleModuleVo : allSimpelModuleList) {
                if (StringUtils.isNotEmpty(simpleModuleVo.getObjtyp())
                        && simpleModuleVo.getObjtyp().equals(acpliaVO.getBussec() + "D")) {
                    objinr = simpleModuleVo.getObjinr();
                    break;
                }
            }
            if (!MdaUtils.isEmpty(objinr)) {
                sql = "SELECT CBE.ACC FROM CBE, TRN, PTS, PTE " +
                        "WHERE CBE.OBJTYP='PTE' AND CBE.OBJINR=PTE.INR AND PTE.OBJTYP='PTS' " +
                        "  AND PTE.OBJINR=PTS.INR AND PTE.CBTPFX = '" + acpliaVO.getCbtpfx() + "'" +
                        "  AND CBE.ACC IS NOT NULL AND PTS.OBJTYP='" + acpliaVO.getBussec() + "D'" +
                        "  AND PTS.OBJINR='" + objinr + "' AND PTS.PTYINR='" + acpliaVO.getLiaptyinr() + "'" +
                        "  AND CBE.TRNINR=TRN.INR AND TRN.RELFLG IN ('R', 'F', 'W') ORDER BY CBE.INR DESC LIMIT 1";
                //      $Sql = "SELECT CBE.ACC, CBE.INR FROM CBE, PTS, PTE WHERE CBE.OBJTYP='RF000001
                acc = publicMapper.dyncQueryStr(ImmutableBiMap.of("sql", sql));
//                    daoSession.dbExecuteSQL(sql);
//                    ctx.getDaoSession().dbFetchFields("", _accBox);
//                    acc = _accBox.value;
            }
            if (!MdaUtils.isEmpty(acc)) {
                trmCod = Strings.mid(acc, 7, 4);
//                    trmTyp = "";
//                    ctx.getDaoSession().dbExecuteSQL("SELECT TRMTYP FROM TRM WHERE TRMCOD='" + trmCod + "' AND TRMTYP<>'AS-GAO'");
//                    ctx.getDaoSession().dbFetchFields("", _trmTypBox);
//                    trmTyp = _trmTypBox.value;
                sql = "SELECT TRMTYP FROM TRM WHERE TRMCOD='" + trmCod + "' AND TRMTYP<>'AS-GAO' AND TRMTYP<>'AS-GAH' limit 1";
                trmTyp = publicMapper.dyncQueryStr(ImmutableBiMap.of("sql", sql));
                hndTyp = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "hndtyp");
                if (MdaUtils.compareTo(trmTyp, termId) == 0 && MdaUtils.compareTo(hndTyp, "OT") != 0) {
                    return acc;
                }
            }
//            gartyp = Datas.getContent(this, "\\GIDGRP\\REC\\GARTYP");
//            ignore = ctx.getErrorCode();
//            segtyp = Datas.getContent(this, "\\GIDGRP\\GHD\\SEGTYP ");
//            ignore = ctx.getErrorCode();
            gartyp = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "gartyp");
            segtyp = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "segtyp");
            if (MdaUtils.compareTo(SettleContext.getTransName(), "GITCAN") == 0 && (MdaUtils.compareTo(gartyp, "U") == 0 || MdaUtils.compareTo(segtyp, "02") == 0)) {
                return actval;
            }
            actval = glemodService.getAvailAcc(termId, acpliaVO.getCbe().getCur(), acpliaVO.getLiaptyinr(), acpliaVO.getCbe().getAmt());
        }
        return actval;

    }

    @Override
    public String getLiaTermKey(String accTyp,AcpliaVo acpliaVo)
    {
        String fixCod = "-";
        String avb = NULLSTR;
        int day = -1;
        String hndTyp = NULLSTR;
        String garTyp = NULLSTR;
        String segTyp = NULLSTR;
        String issBnk = NULLSTR;
        String aplptyinr = NULLSTR;
        String aplpty = NULLSTR;
        Argument<String> _aplptyBox = Argument.box(aplpty);
        String finOrgTyp = NULLSTR;
        Argument<String> _finOrgTypBox = Argument.box(finOrgTyp);
        String sql = NULLSTR;
        switch (acpliaVo.getBussec()) {
            //---DZTEST------
            case "DI":
            case "BD":
                avb = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(),"avbby", "");
                day = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "tenmaxday", -1);
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AVL") == 0 && MdaUtils.compareTo(acpliaVo.getBussec(), "BR") != 0) {
                    if (StringUtils.isEmpty(avb)) {
                        avb = this.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "avbby", "");
                    }
                    if (day == -1) {
                        day = this.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "tenmaxday", new BigDecimal(-1)).intValue();
                    }
                    if (MdaUtils.compareTo(day, 0) == 0 && (MdaUtils.compareTo(avb, "P") == 0 || MdaUtils.compareTo(avb, "N") == 0)) {
                        if (MdaUtils.compareTo(accTyp, "LA") == 0) {
                            fixCod = fixCod + "DIS";
                        } else {
                            fixCod = fixCod + "LIS";
                        }
                    } else {
                        if (MdaUtils.compareTo(accTyp, "LA") == 0) {
                            fixCod = fixCod + "DIU";
                        } else {
                            fixCod = fixCod + "LIU";
                        }
                    }
                }
                // 押汇的或有账，需要进一步确认
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "DPZ") == 0 || MdaUtils.compareTo(acpliaVo.getCbtpfx(), "DPU") == 0 || MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AKZ") == 0) {
                    if (MdaUtils.compareTo(accTyp, "LA") == 0) {
                        fixCod = fixCod + "DCP";
                    } else {
                        fixCod = fixCod + "ACP";
                    }
                }
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AVG") == 0 || (MdaUtils.compareTo(acpliaVo.getBussec(), "BD") == 0 && MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AVL") == 0)) {  // 提货担保
                    fixCod = fixCod + "GAT";
                }
                break;
            case "LI":
            case "BR":
                avb = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(),"avbby", "");
                day = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "tenmaxday", -1);
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AVL") == 0 && MdaUtils.compareTo(acpliaVo.getBussec(), "BR") != 0) {
                    if (StringUtils.isEmpty(avb)) {
                        avb = this.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "avbby", "");
                    }
                    if (day == -1) {
                        day = this.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "tenmaxday", new BigDecimal(-1)).intValue();
                    }
                    if (MdaUtils.compareTo(day, 0) == 0 && (MdaUtils.compareTo(avb, "P") == 0 || MdaUtils.compareTo(avb, "N") == 0)) {
                        fixCod = fixCod + "LIS";
                    } else {
                        fixCod = fixCod + "LIU";
                    }
                }
                // 押汇的或有账，需要进一步确认
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "DPZ") == 0 || MdaUtils.compareTo(acpliaVo.getCbtpfx(), "DPU") == 0 || MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AKZ") == 0) {
                    fixCod = fixCod + "ACP";
                }
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AVG") == 0 || (MdaUtils.compareTo(acpliaVo.getBussec(), "BR") == 0 && MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AVL") == 0)) {  // 提货担保
                    fixCod = fixCod + "GAT";
                }
                break;
            case "DF":
                //同业代付
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "DFU") == 0) {
                    hndTyp = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "hndtyp");
                    if (MdaUtils.compareTo(hndTyp, "BF") == 0) {
                        if (MdaUtils.compareTo(accTyp, "AS") == 0) {
                            fixCod = fixCod + "DF2";
                        } else {
                            fixCod = fixCod + "DF1";
                        }
                    } else {
                        fixCod = fixCod + "DF1";
                    }
                }
                //---DZTEST------
                break;
            case "DE":
            case "BF":
            case "DT":
            case "MT":
                avb = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(),"avbby", "");
                day = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "tenmaxday", -1);
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AVS") == 0 && (MdaUtils.compareTo(acpliaVo.getBussec(), "BF") == 0 || MdaUtils.compareTo(acpliaVo.getBussec(), "MT") == 0)) {
                    if (MdaUtils.compareTo(Strings.mid(SettleContext.getTransName(), 1, 2), "BF") == 0 || MdaUtils.compareTo(Strings.mid(SettleContext.getTransName(), 1, 2), "BP") == 0) {
                        return "";
                    } else {
                        if (StringUtils.isEmpty(avb)) {
                            avb = this.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "avbby", "");
                        }
                        if (day == -1) {
                            day = this.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "tenmaxday", new BigDecimal(-1)).intValue();
                        }
                        if (MdaUtils.compareTo(day, 0) == 0 && (MdaUtils.compareTo(avb, "P") == 0 || MdaUtils.compareTo(avb, "N") == 0)) {
                            fixCod = fixCod + "LES";
                        } else {
                            fixCod = fixCod + "LEU";
                        }
                    }
                }
                // 转卖票据的特殊处理
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "FOR") == 0) {
                    return "OB-DTT";
                }
                break;
            case "LE":
            case "BE":
            case "LT":
            case "BT":
                avb = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(),"avbby", "");
                day = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "tenmaxday", -1);
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AVS") == 0 && (MdaUtils.compareTo(acpliaVo.getBussec(), "BE") == 0 || MdaUtils.compareTo(acpliaVo.getBussec(), "BT") == 0)) {
                    if (StringUtils.isEmpty(avb)) {
                        avb = this.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "avbby", "");
                    }
                    if (day == -1) {
                        day = this.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "tenmaxday", new BigDecimal(-1)).intValue();
                    }
                    if (MdaUtils.compareTo(day, 0) == 0 && (MdaUtils.compareTo(avb, "P") == 0 || MdaUtils.compareTo(avb, "N") == 0)) {
                        fixCod = fixCod + "LES";
                    } else {
                        fixCod = fixCod + "LEU";
                    }
                }
                // 转卖票据的特殊处理
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "FOR") == 0) {
                    return "OB-LTT";
                }
                break;
            case "NI":
            case "GI":
                // 出口保函不出账
                if (MdaUtils.compareTo(Strings.mid(SettleContext.getTransName(), 1, 2), "GE") != 0 && MdaUtils.compareTo(Strings.mid(SettleContext.getTransName(), 1, 2), "NE") != 0 && MdaUtils.compareTo(acpliaVo.getCbtpfx(), "FIN") != 0) {
                    garTyp = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(),"gartyp");
                    hndTyp = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "hndtyp");
                    segTyp = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "segtyp");
                    List<PtsptaVo> ptsptas = transactionHelpService.getLiaallSet().getPtsptas();
                    PtsptaVo ptspta = ptsptaToolComponent.getPtsFromListByRol(ptsptas, "ISS");
                    if (ptspta != null) {
                        issBnk = ptspta.getExtkey();
                    }
                    ptspta = ptsptaToolComponent.getPtsFromListByRol(ptsptas, "APL");
                    if (ptspta != null) {
                        aplptyinr = ptspta.getPtyinr();
                    }
                    if (MdaUtils.compareTo(hndTyp, "OT") == 0) {
                        ptspta = ptsptaToolComponent.getPtsFromListByRol(ptsptas, "BEN");
                        if (ptspta != null) {
                            aplptyinr = ptspta.getPtyinr();
                        }
                    }
                    aplpty = "";
                    finOrgTyp = "";
                    if (!MdaUtils.isEmpty(aplptyinr)) {
                        //        $SQL = "select idtype,finorgtyp from pty where inr = " + $Aplptyinr
                        Pty aplPtyObject = ptyCacheService.getPtyById(aplptyinr);
                        if (aplPtyObject != null) {
                            aplpty = aplPtyObject.getIdtype();
                            finOrgTyp = aplPtyObject.getAkkcom();
                        }
//                        sql = "select idtype,akkcom from pty where inr = '" + aplptyinr+"'";
//                        Map<String,Object> result = publicMapper.dyncQueryMap(ImmutableBiMap.of("sql",sql));
//                        aplpty = (String) result.get("idtype");
//                        finOrgTyp = (String)result.get("akkcom");
                    }
                    //-------------------表外逻辑-------------------------
                    if (MdaUtils.compareTo(garTyp, "U") == 0 || MdaUtils.compareTo(segTyp, "02") == 0 || MdaUtils.compareTo(garTyp, "V") == 0) {
                        if (MdaUtils.compareTo(garTyp, "U") == 0 || MdaUtils.compareTo(segTyp, "02") == 0) {
                            if (MdaUtils.compareTo(hndTyp, "OT") == 0 && "AS".equals(accTyp)) {
                                fixCod = fixCod + "GAH";
                            } else {
                                fixCod = fixCod + "GAG";
                            }
                        }
                        if (MdaUtils.compareTo(garTyp, "V") == 0) {
                            //信贷证明保函不受转开与同业控制2239/2240
                            if (MdaUtils.compareTo(hndTyp, "OT") == 0) {
                                if (MdaUtils.compareTo(accTyp, "AS") == 0) {
                                    fixCod = fixCod + "GAC";
                                } else {
                                    fixCod = fixCod + "GAB";
                                }
                            } else {
                                fixCod = fixCod + "GAB";
                            }
                        }
                    } else {
                        if (MdaUtils.compareTo(hndTyp, "OT") == 0) {
                            if (MdaUtils.compareTo(accTyp, "AS") == 0) {
                                if (MdaUtils.compareTo(Strings.mid(issBnk, 1, 4), "EVER") == 0) {
                                    //转开我行保函借记帐2597
                                    fixCod = fixCod + "GAN";
                                } else {
                                    //转开0158
                                    fixCod = fixCod + "GAO";
                                }
                            } else {
                                //转开非AS
                                if (MdaUtils.compareTo(Strings.mid(issBnk, 1, 4), "EVER") == 0) {
                                    //转开我行保函借记帐2598
                                    fixCod = fixCod + "GAN";
                                } else {
                                    //0458
                                    fixCod = fixCod + "GAT";
                                }
                            }
                        } else {
                            //非转开
                            //if (!MdaUtils.isEmpty(aplpty)) {
                                if (MdaUtils.compareTo(aplpty, "2") == 0 && MdaUtils.compareTo(Strings.trim(finOrgTyp), "10313") != 0) {
                                    //刘文青要求：判断客户号为同业客户时(财务公司除外)，318704（2870）应收非银行同业保函款项；338704（2871）应付非银行同业保函款项
                                    fixCod = fixCod + "GAY";
                                } else {
                                    switch (garTyp) {
                                        case "X":
                                            //加贸保函2743/2744
                                            fixCod = fixCod + "GAM";
                                            break;
                                        default:
                                            //0158、0458
                                            fixCod = fixCod + "GAT";
                                    }
                                }
                            //}
                        }
                    }
                }
                break;
            case "GC":// 5.01没有或有账
            case "GE":// GE没有或有账
                return "";
            case "BO":
                fixCod = fixCod + "OCT";
                break;
            case "BC":
                if (MdaUtils.compareTo(acpliaVo.getCbtpfx(), "AVL") == 0) {
                    fixCod = fixCod + "ICT";
                }
                break;
            case "CC":
                fixCod = fixCod + "CCP";
                break;
        }
        if (MdaUtils.compareTo(fixCod, "-") == 0) {
            return "";
        } else {
            return accTyp + fixCod;
        }

    }

    @Override
    public void defaultCbeXrfCurAmt(AcpliaVo acpliaVo) {
        acpliaVo.getCbe().setXrfcur(xrtmodService.sysiso());
        if(MdaUtils.compareTo(acpliaVo.getCbe().getAmt(),0) < 0) {
            BigDecimal part = null;
            if(MdaUtils.compareTo(acpliaVo.getWrkcbb().getAmt(), 0) == 0) {
                part = new BigDecimal("1");
            } else {
                part = Decimals.div(acpliaVo.getCbe().getAmt(), acpliaVo.getWrkcbb().getAmt());
            }
            acpliaVo.getCbe().setXrfamt(xrtmodService.amtRnd(Decimals.mul(acpliaVo.getWrkcbb().getXrfamt(), part), acpliaVo.getWrkcbb().getXrfcur()));
        } else {
            acpliaVo.getCbe().setXrfamt(xrtmodService.sysCurEqu(acpliaVo.getCbe().getCur(), acpliaVo.getCbe().getAmt(), Dates.today()));
        }
    }

    public void defaultCbeAcc(AcpliaVo acpliaVO) {
        String actval = "";
        if(!MdaUtils.isEmpty(acpliaVO.getWrkcbe().getInr()) && MdaUtils.compareTo(acpliaVO.getWrkcbb().getAmt(),0) != 0 ) {
            acpliaVO.getCbe().setAcc(acpliaVO.getWrkcbe().getAcc());
            return;
        }
        if( MdaUtils.isEmpty(acpliaVO.getCbe().getCur()) ) {
            acpliaVO.getCbe().setAcc("");
            acpliaVO.setAccSet(new HashSet<>());
            return;
        }
        if((MdaUtils.isEmpty(acpliaVO.getLiaptyinr()) || MdaUtils.compareTo(acpliaVO.getCbe().getAmt(),0) == 0)
                && MdaUtils.compareTo(acpliaVO.getWrkcbb().getAmt(),0) == 0) {
            acpliaVO.getCbe().setAcc("");
            acpliaVO.setAccSet(new HashSet<>());
            return;
        } else {
            // check if set by LiaallSetRefAct
            actval = getAvailAcc(acpliaVO);
            //重置下拉框
            Set<String> accSet = new HashSet<>();
            if (StringUtils.isNotEmpty(actval)) {
                acpliaVO.getCbe().setAcc(Strings.getLine(actval,1));
                Arrays.stream(actval.split("[\\r\\n]{1,2}")).forEach(account -> {
                    if (!accSet.contains(account)) {
                        accSet.add(account);
                    }
                });
            } else {
                acpliaVO.getCbe().setAcc("");
            }
            acpliaVO.setAccSet(accSet);
        }
    }

    public boolean defaultActrec(AcpliaVo acpliaVO){
        if( MdaUtils.isEmpty(acpliaVO.getCbe().getAcc()) ) {
            //MdaUtils.clear(acpliaVO.getActrec());
            acpliaVO.setActrec(new Act());
        } else {
            String conditionSql = Utils.sdbEtyGenSql("ACT", "EXTKEY = '" + acpliaVO.getCbe().getAcc() + "'");
            List<Act> actList = actMapper.getActByConditionSql(conditionSql);
            if (actList != null && actList.size() > 0) {
                acpliaVO.setActrec(actList.get(0));
            }
        }
        return true;
    }

    public void defaultCbeAcc2(AcpliaVo acpliaVO){
        String actval = "";
        if( ! MdaUtils.isEmpty(acpliaVO.getWrkcbe().getInr()) && MdaUtils.compareTo(acpliaVO.getWrkcbb().getAmt(),0) != 0 ) {
            acpliaVO.getCbe().setAcc2(  acpliaVO.getWrkcbe().getAcc2());
            return;
        }
        if( MdaUtils.isEmpty(acpliaVO.getCbe().getCur()) || ! MdaUtils.isEmpty(acpliaVO.getNobookcat()) ) {
            acpliaVO.getCbe().setAcc2("");
            acpliaVO.setAcc2Set(new HashSet<>());
            return;
        }
        String trmtyp = NULLSTR;
        String gartyp = NULLSTR;
        String segtyp = NULLSTR;
        if( ( MdaUtils.isEmpty(getLiaacc2ptyinr(acpliaVO)) ||
                ( MdaUtils.compareTo(acpliaVO.getCbe().getAmt(),0) == 0 ) ) &&
                ( MdaUtils.compareTo(acpliaVO.getWrkcbb().getAmt(),0) == 0 ) ) {
            acpliaVO.getCbe().setAcc2("");
            acpliaVO.setAcc2Set(new HashSet<>());
            return;
        } else {
            // check if set by LiaallSetRefAct
            actval = liaallService.liaallParGet("REFACT.ACC2", acpliaVO.getCbtpfx());
            // Modified by ZJ on Mar 2008
            // 取账号的Trmtyp需要重新赋值
            trmtyp = getLiaTermKey( "LA" ,acpliaVO );
            if( MdaUtils.isEmpty(actval) ) {
                /*gartyp = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "gartyp");
                segtyp = Utils.getFieldValue(transactionHelpService.getLiaallSet().getRec(), "segtyp");
                if( MdaUtils.compareTo(gartyp,"U") == 0 || MdaUtils.compareTo(segtyp,"02") == 0 ) {
                    actval = "";
                } else {*/
                    actval = glemodService.getAvailAcc( trmtyp, acpliaVO.getCbe().getCur(), getLiaacc2ptyinr(acpliaVO),  acpliaVO.getCbe().getAmt() );
                /*}*/
            }
            //重置下拉框
            Set<String> acc2Set = new HashSet<>();
            if (StringUtils.isNotEmpty(actval)) {
                acpliaVO.getCbe().setAcc2( Strings.getLine(actval,1));
                Arrays.stream(actval.split("[\\r\\n]{1,2}")).forEach(account -> {
                    if (!acc2Set.contains(account)) {
                        acc2Set.add(account);
                    }
                });
            } else {
                acpliaVO.getCbe().setAcc2("");
            }
            acpliaVO.setAcc2Set(acc2Set);
        }
        return;
    }

    public void glesavlia(GlemodVo glemod, LiaallgVo liaallg) {
        // save transaction accounting entries
        // Modified by ZJ on Feb 2008
        // 会计移植
        String ref = glemod.getRec().getOwnref();
        //String transName = SettleContext.getTransName();
        String transName = SettleContext.getDirectTransName();
        //if(!MdaUtils.isEmpty(acplia.getCbe().getAmt()) ) {
            // 出口托收承兑不出账
            if( MdaUtils.compareTo(transName,"BOTACC") != 0 ) {
                // 5.01调用了cbe\\gletxt2，而cbe表中gletxt2均为空，因此用空值代替
                if( MdaUtils.compareTo(transName,"BRTSET") == 0 && MdaUtils.compareTo(liaallg.getBussec(),"BR") == 0 && ( MdaUtils.compareTo(liaallg.getCbtpfx(),"AVG") == 0 || MdaUtils.compareTo(liaallg.getCbtpfx(),"AVL") == 0 ) ) {
                    // 进口付汇,不处理提货担保账
                } else {
                    if( ( MdaUtils.compareTo(transName,"BFTSET") == 0 || MdaUtils.compareTo(transName,"BFTSND") == 0 ) && MdaUtils.compareTo(liaallg.getCbtpfx(),"AVS") == 0 ) {

                    } else {
                        String extKey = "";
                        Pty pty = ptyCacheService.getPtyById(liaallg.getLiaptyinr());
                        if (pty != null) {
                            extKey = pty.getExtkey();
                        }
                        transactionHelpService.getLiaallSet().setRec(glemod.getRec());
                        transactionHelpService.getLiaallSet().setPtsptas(glemod.getPtsList());
                        String trmTyp1 = getLiaTermKey("AS", liaallg.getAcplia());
                        String trmTyp2 = getLiaTermKey("LA", liaallg.getAcplia());
                        glemodService.liaglesavCeb(glemod, liaallg.getCur(), liaallg.getAmt(), liaallg.getAcc(), liaallg.getAcc2(), ref, liaallg.getAcplia().getLiatyp(), /*acplia.getCbe().getDat()*/null, liaallg.getCbtpfx(), extKey, trmTyp1, trmTyp2);
                    }
                }
            }
        //}
    }

    public String getLiaacc2ptyinr(AcpliaVo acplia) {
        String catPar = liaallService.liaallParGet ( "CATACTPTYINR", acplia.getCbtpfx() );
        if( MdaUtils.isEmpty(catPar) ) {
            return acplia.getLiaptyinr();
        } else {
            return catPar;
        }
    }

    public String getLiaaccptyinr(AcpliaVo acplia) {
        return acplia.getLiaptyinr();
    }

    /**
     *   source:liaone.0002.script
     */
    public void cbsstore(LiaallgVo liaallg, Object argObj, String trninr) {
        AcpliaVo acplia = liaallg.getAcplia();
        if( MdaUtils.isEmpty(acplia.getCbe().getAmt()) && MdaUtils.isEmpty(acplia.getCbe().getOptdat()) ) {
            return;
        }
        if (argObj == null) {
            SettleExceptionUtils.sysDump(Strings.formatText("Can\'t find module"));
        }
        BigDecimal amt = acplia.getCbe().getAmt();
        BigDecimal xrf = acplia.getCbe().getXrfamt();
        //MdaUtils.clear(ctx.absGet(Trnmod.class).getWrkcbe());
        acplia.getCbe().setTrninr( trninr);
        acplia.getCbe().setTrntyp( "TRN");
        acplia.getCbe().setExtid( "AMT1");
        if (acplia.getCbe().getDat() == null) {
            acplia.getCbe().setDat(new Date());
        }
        acplia.getCbe().setCredat(new Date());
        if( MdaUtils.compareTo(acplia.getCbe().getAmt(),0)>=0 ) {
            acplia.getCbe().setCbt( "LIAIN");
            acplia.getCbe().setNam( "inbooking " + acplia.getNamsfx());
            cbsmodService.cbsStoreEntry( acplia.getCbe(),argObj);
        } else {
            acplia.getCbe().setCbt( "LIAOUT");
            acplia.getCbe().setNam( "outbooking " + acplia.getNamsfx());
            acplia.getCbe().setAmt( Numerics.abs(acplia.getCbe().getAmt()));
            acplia.getCbe().setXrfamt( Numerics.abs(acplia.getCbe().getXrfamt()));
            cbsmodService.cbsStoreEntry(acplia.getCbe(),argObj);
        }
        acplia.getCbe().setAmt( amt);
        acplia.getCbe().setXrfamt( xrf);
        glesavlia(transactionHelpService.getTransactionStoreSet().getGlemodVo(), liaallg);
        String status = NULLSTR;
        if( MdaUtils.compareTo(acplia.getCbe().getAmt(),0)>=0 )
        {
            status = lscmodService.lsiGetCBEStatus( acplia.getCbe());
            if( MdaUtils.compareTo(status,LscAccepted) != 0 ) {
                if( MdaUtils.compareTo(acplia.getCbe().getAmt(),0)>0 ) {
                    log.warn(Strings.getText("The open limit amount is not sufficient to accept the request of $2 $1!", Utils.fmtAmount(acplia.getCbe().getAmt(),acplia.getCbe().getCur()),acplia.getCbe().getCur()), "LIA" + acplia.getCbe().getCbt() + acplia.getCbe().getObjtyp() + acplia.getCbe().getObjinr());
                }
                TrnmodVo trnmod = transactionHelpService.getTransactionStoreSet().getTrnmodVo();
                trnismService.wfmAdd_LimitCheck(trnmod.getTrnism().getWfmmod(), trnmod);
            }
        }

    }

    /**
     * source:liaone.0000.script
     */
    //@Default(value={"wrkcbb","liagrdinr"},order=1000)
    public void defaultWrkcbb(AcpliaVo acpliaVo, String objTyp, String objInr) {
        acpliaVo.setLiagrdinr(objInr);
        Date date = Dates.add(Utils.getMaxDate(), -1);
        switch (acpliaVo.getCbtpfx()) {
            case "CCV":
                cbsmodService.cbsGetBalance(acpliaVo.getWrkcbb(), objTyp, objInr, "CCVSUM", acpliaVo.getCbe().getExtid(), date);
                break;
            default:
                cbsmodService.cbsGetBalance(acpliaVo.getWrkcbb(), objTyp, objInr, "LIASUM", "AMT1", date);
        }
    }

    public void defaultWrkcbe(AcpliaVo acpliaVo) {
        Cbe cbe = new Cbe();
        cbe.setInr(acpliaVo.getWrkcbb().getCbeinr());
        cbe = cbeMapper.selectByPrimaryKey(cbe);
        if (cbe != null) {
            acpliaVo.setWrkcbe(cbe);
        }
    }

    private <T> T getFieldValue(BizInfoVo rec, String field, T defaultValue) {
        T value = null;
        try {
            if ("LID".equals(rec.getObjtyp())
                    || "LED".equals(rec.getObjtyp())
                    || "LTD".equals(rec.getObjtyp())
                    || "DID".equals(rec.getObjtyp())
                    || "DED".equals(rec.getObjtyp())) {
                value = dyncDaoService.dyncReadFieldByInr(rec.getObjtyp(), rec.getObjinr(), field);
            } else if ("BRD".equals(rec.getObjtyp())
                    || "BED".equals(rec.getObjtyp())
                    || "BTD".equals(rec.getObjtyp())
                    || "BDD".equals(rec.getObjtyp())
                    || "BFD".equals(rec.getObjtyp())) {
                value = dyncDaoService.dyncReadFieldByInr(rec.getPnttyp(), rec.getPntinr(), field);
            }
        } catch (Exception e) {
            log.error("获取即期远期配置错误", e);
            value = null;
        }
        if (value == null) {
            value = defaultValue;
        }
        return value;
    }
}
