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

import com.brilliance.mda.runtime.mda.CodetableItem;
import com.brilliance.mda.runtime.mda.impl.Argument;
import com.brilliance.mda.runtime.mda.util.*;
import com.brilliance.isc.bo.*;
import com.brilliance.isc.common.cache.atpbch.AtpBchCacheService;
import com.brilliance.isc.common.cbsmod.service.CbsmodService;
import com.brilliance.isc.common.cbsmod.service.XrtmodService;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.context.SpringEnvContext;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.common.lgbdet.service.LgbdetService;
import com.brilliance.isc.common.lgbdet.vo.LgbdetRegisterVo;
import com.brilliance.isc.common.lgbdet.vo.LgbdetVo;
import com.brilliance.isc.common.lgbdet.vo.LgbdetgVo;
import com.brilliance.isc.common.lgbdet.vo.LgbismVo;
import com.brilliance.isc.common.register.lgbdet.ILgbdetRegister;
import com.brilliance.isc.common.sysmod.SysmodService;
import com.brilliance.isc.common.transaction.help.LiaallSet;
import com.brilliance.isc.common.transaction.help.TransactionHelpService;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.common.vo.SimpleModuleVo;
import com.brilliance.isc.mda.dao.*;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.*;

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

@Service
public class LgbdetServiceImpl implements LgbdetService {

    @Autowired
    private PtyMapper ptyMapper;

    @Autowired
    private AtpBchCacheService atpBchCacheService;

    @Autowired
    private TransactionHelpService transactionHelpService;

    @Autowired
    private LgoMapper lgoMapper;

    @Autowired
    private LglMapper lglMapper;

    @Autowired
    private LgbMapper lgbMapper;

    @Autowired
    private LgaMapper lgaMapper;

    @Autowired
    private LgeMapper lgeMapper;

    @Autowired
    private CbsmodService cbsmodService;

    @Autowired
    private XrtmodService xrtmodService;

    @Autowired
    private SysmodService sysmodService;

    @Autowired
    private PublicMapper publicMapper;

    private static List<CodetableItem> typList;

    @PostConstruct
    public void initTypList() {
        typList = new ArrayList<>();
        typList.add(new CodetableItem("融资性对外担保总额度", "OVR"));
        typList.add(new CodetableItem("二级福费廷总额度", "FFT"));
    }

    @Override
    public void assertLgbdet(LgbdetVo lgbdetVo) {
        //! 融资性对外担保主体函数
        //  由于不产生额度界面，因此只在存盘时调用
        lgbdetVo.setErrsta(NULLSTR);
        lgbdetVo.setErrmsg(NULLSTR);
        lgbdetVo.getLgbdetRegisterList().clear();
        //1. 调用所有RegisterLGBDET函数产生额度数据流PARSTM
        lgbdetRegister(lgbdetVo);
        //2. 根据模型获取前手交易额度数据
        if (StringUtils.isEmpty(lgbdetVo.getOldredflg())) {
            getold(lgbdetVo);
            lgbdetVo.setOldredflg("X");
        }
        //! 3. 遍历LgbdetRegister，产生额度请求数据
        // PARSTM结构如下：
        //   第一行：额度的Group Key，格式为PTYINR+额度品种
        //   第二行：额度品种，目前只有OVR一种
        //   第三行：额度主体INR，目前全部为总行的INR
        //   第四行：额度请求币种
        //   第五行：额度请求金额
        //   第六行：产生额度请求的业务模块路径
        lgbdetVo.getLgbdetRegisterList().forEach(lgbdetRegisterVo -> {
            String typ = lgbdetRegisterVo.getExtID();
            String ptyInr = lgbdetRegisterVo.getPtyInr();
            String cur = lgbdetRegisterVo.getCur();
            BigDecimal amt = lgbdetRegisterVo.getAmt();
            SimpleModuleVo linkModule = lgbdetRegisterVo.getLinkModule();
            String grpKey = typ + TAB + ptyInr;
            int find = -1;
            for (int i=0; i<lgbdetVo.getLgbdetg().size(); i++) {
                if( MdaUtils.compareTo(grpKey, lgbdetVo.getLgbdetg().get(i).getGrpkey()) == 0
                        && (MdaUtils.compareTo(cur, lgbdetVo.getLgbdetg().get(i).getCur()) == 0
                        || MdaUtils.compareTo(lgbdetVo.getLgbdetg().get(i).getOldamt(),0) == 0 ) ) {
                    find = i;
                    break;
                }
            }
            //没有找到，新增一条Lbgdetg
            if (find == -1) {
                LgbdetgVo lgbdetgVo = new LgbdetgVo();
                lgbdetgVo.setGrpkey(grpKey);
                lgbdetgVo.setOldamt(new BigDecimal("0"));
                if(MdaUtils.compareTo(SettleContext.getTransName(),"BPTSET") == 0
                        && MdaUtils.compareTo(lgbdetgVo.getOldamt(),0) == 0) {
                    Cbb max = new Cbb();
                    Date date = Dates.add(Utils.getMaxDate(), -1);
                    cbsmodService.cbsGetBalance(max, linkModule.getObjtyp(), linkModule.getObjinr(), "MAXSUM", "AMT1", date);
                    lgbdetgVo.setOldamt(max.getAmt());
                    lgbdetgVo.setOldxrfamt(max.getAmt());
                }
                lgbdetgVo.setCur(cur);
                lgbdetgVo.setAmt(amt);
                lgbdetgVo.setLgoinr("NEW");
                lgbdetgVo.setObjmodpth(Utils.toJson(linkModule));
                lgbdetgVo.setTyp(typ);
                lgbdetgVo.setPtyinr(ptyInr);
                lgbdetVo.addLgbdetg(lgbdetgVo);
            } else {
                lgbdetVo.getLgbdetg().get(find).setCur(cur);
                lgbdetVo.getLgbdetg().get(find).setAmt(amt);
            }
        });
        //! 4. 根据请求信息设置LGO对应的LGB/LGA信息并赋值到LSBISM模块中
        internalSetLGBISM(lgbdetVo);
        //! 5. 计算发生额Pending Amount
        if(MdaUtils.compareTo(lgbdetVo.getErrsta(),"E") != 0) {
            internalSetAmount(lgbdetVo);
        }
    }

    /**
     *   source:lgbdet.0006.script
     */
    public void saveLGBDET(LgbdetVo lgbdetVo) {
        if(MdaUtils.compareTo(Strings.mid(SettleContext.getTransName(),1,2),"BP") == 0) {
            String fintyp = Utils.getFieldValue(lgbdetVo.getRec(), "fintyp", "");
            String fortyp = Utils.getFieldValue(lgbdetVo.getRec(), "fortyp", "");
            String cur = lgbdetVo.getCbsMap().getOrDefault("MAX", new Cbb()).getCur();
            if((MdaUtils.compareTo(fintyp,"G") == 0 && MdaUtils.compareTo(fortyp,"2") == 0)
                    || (MdaUtils.compareTo(cur,"CNY") == 0 && MdaUtils.compareTo(fintyp,"F") == 0 && MdaUtils.compareTo(fortyp,"2") == 0)) {
                //assertLGBDET();
                for(int i=0; i<lgbdetVo.getLgbdetg().size(); i++) {
                    if (StringUtils.isEmpty(lgbdetVo.getLgbdetg().get(i).getLgo().getObjinr())) {
                        Object rec = transactionHelpService.getTransactionStoreSet().getRec();
                        lgbdetVo.getLgbdetg().get(i).getLgo().setObjinr(Utils.getFieldValue(rec, "inr", ""));
                    }
                    if(MdaUtils.compareTo(lgbdetVo.getLgbdetg().get(i).getLgo().getInr(), "NEW") == 0) {
                        sysmodService.sdbInsertWithLog(lgbdetVo.getLgbdetg().get(i).getLgo());
                    } else {
                        sysmodService.sdbUpdateWithLog(lgbdetVo.getLgbdetg().get(i).getLgo());
                    }
                    lgbdetVo.getLgbdetg().get(i).getLge().setObjtyp("ORD");
                    lgbdetVo.getLgbdetg().get(i).getLge().setObjinr(transactionHelpService.getTransactionStoreSet().getTrnmodVo().getOrdmod().getOrd().getInr());
                    lgbdetVo.getLgbdetg().get(i).getLge().setLgoinr(lgbdetVo.getLgbdetg().get(i).getLgo().getInr());
                    sysmodService.sdbInsertWithLog(lgbdetVo.getLgbdetg().get(i).getLge());
                    if(MdaUtils.isEmpty(lgbdetVo.getLgbdetg().get(i).getLgl().getLgoinr())) {
                        lgbdetVo.getLgbdetg().get(i).getLgl().setLgoinr(lgbdetVo.getLgbdetg().get(i).getLgo().getInr());
                        lglMapper.insert(lgbdetVo.getLgbdetg().get(i).getLgl());
                    }
                }
                for(int i=0; i<lgbdetVo.getLgbism().size(); i++) {
                    lgbdetVo.getLgbism().get(i).getLga().setXrfdat(Dates.today());
                    if(MdaUtils.isEmpty(lgbdetVo.getLgbism().get(i).getLga().getInr())) {
                        lgbdetVo.getLgbism().get(i).getLga().setLgbinr(lgbdetVo.getLgbism().get(i).getLgb().getInr());
                        lgbdetVo.getLgbism().get(i).getLga().setUsecur(lgbdetVo.getLgbism().get(i).getLgb().getCur());
                        lgbdetVo.getLgbism().get(i).getLga().setNaccur(lgbdetVo.getLgbism().get(i).getLgb().getCur());
                        sysmodService.sdbInsert(lgbdetVo.getLgbism().get(i).getLga());
                    } else {
                        sysmodService.sdbUpdate(lgbdetVo.getLgbism().get(i).getLga());
                    }
                }
            }
        }

    }

    /**
     * lgbdet注册方法
     *
     * @param lgbdetVo
     */
    private void lgbdetRegister(LgbdetVo lgbdetVo) {
        //! recreates parameter stream by posting all liaallset-methods
        //! The names of all subs setting parameters for LIAALL have to start with liaallset
        //! CAUTION: As the names are loaded at the beginning of transaction, the transaction has to be reloaded.
        //getLiaallSet().clearLiaall();
        //按照交易码，获取注册Spring的交易Bean
        String transName = SettleContext.getTransName();
        try {
            ILgbdetRegister lgbdetRegister = SpringEnvContext.getBean(atpBchCacheService.getSdTransNameForRegister().toLowerCase() + "." + "lgbdetRegister");
            lgbdetRegister.registerLgbdet(lgbdetVo);
        } catch (NoSuchBeanDefinitionException e) {
            throw new CommonServiceException("二级福费廷融资没有找到交易注册类");
        }
    }
    /**
     *   source:lgbdet.0013.script
     */
    public void lgbDetSetLimitAmount(LgbdetVo lgbdetVo, String extID, String cur, BigDecimal amt, SimpleModuleVo linkModule) {
        // 刘文青2013-12-17需求：人民币不扣减额度
        // 考虑到已占用的需要归还
        Bch bch = SettleContext.getUserSession().getBch();
        if (bch == null) {
            throw new CommonServiceException("无法获取当前经办机构");
        }
        Pty pty = ptyMapper.queryDetailByExtkey(bch.getSwfcod());
        if (pty == null) {
            throw new CommonServiceException("无法获取当前经办机构的客户信息");
        }
        String ptyInr = pty.getInr();
        String grpKey = extID + TAB + pty.getInr();
        boolean findFlag = false;
        List<LgbdetRegisterVo> lgbdetRegisterList = lgbdetVo.getLgbdetRegisterList();
        for (int i=0; i<lgbdetRegisterList.size(); i++) {
            LgbdetRegisterVo tempLgbdetRegister = lgbdetRegisterList.get(i);
            if (grpKey.equals(tempLgbdetRegister.getGrpKey())) {
                BigDecimal newAmt = tempLgbdetRegister.getAmt().add(amt);
                tempLgbdetRegister.setAmt(newAmt);
                findFlag = true;
                break;
            }
        }
        //没有找到注册信息条目，需要新增LgbdetRegisterVo
        if (!findFlag) {
            LgbdetRegisterVo lgbdetRegisterVo = new LgbdetRegisterVo();
            lgbdetRegisterVo.setGrpKey(grpKey);
            lgbdetRegisterVo.setExtID(extID);
            lgbdetRegisterVo.setPtyInr(ptyInr);
            lgbdetRegisterVo.setCur(cur);
            lgbdetRegisterVo.setAmt(amt);
            lgbdetRegisterVo.setLinkModule(linkModule);
            lgbdetVo.addLgbdetRegister(lgbdetRegisterVo);
        }
    }

    /**
     *   source:lgbdet.0010.script
     */
    public void getold(LgbdetVo lgbdetVo) {
        lgbdetVo.getLgbdetg().clear();
        List<SimpleModuleVo> simpleModuleList = Utils.toListObject(SimpleModuleVo.class, lgbdetParGet("ADDMODULE", "ALL"));
        if (simpleModuleList != null && simpleModuleList.size() > 0) {
            simpleModuleList.forEach(simpleModuleVo -> getOldForContract(lgbdetVo, simpleModuleVo));
        }
    }

    /**
     *   source:lgbdet.0012.script
     */
    public void getOldForContract(LgbdetVo lgbdetVo, SimpleModuleVo linkModule) {
        String objTyp = linkModule.getObjtyp();
        String objInr = linkModule.getObjinr();
        if(MdaUtils.isEmpty(objInr) || MdaUtils.isEmpty(objTyp)) {
            return;
        }
        List<Lgo> lgoList = lgoMapper.getLgoByObjtypAndObjinr(objTyp, objInr);
        lgoList.forEach(lgo -> {
            LgbdetgVo lgbdetgVo = new LgbdetgVo();
            lgbdetgVo.setLgo(lgo);
            lgbdetgVo.setGrpkey(lgo.getExtid() + TAB + lgo.getPtyinr());
            lgbdetgVo.setOldamt(lgo.getAmt());
            lgbdetgVo.setOldxrfamt(lgo.getXrfamt());
            if(MdaUtils.compareTo(SettleContext.getTransName(), "BPTSET") == 0
                    && MdaUtils.compareTo(lgbdetgVo.getOldamt(),0) == 0) {
                Cbb max = new Cbb();
                Date date = Dates.add(Utils.getMaxDate(), -1);
                cbsmodService.cbsGetBalance(max, objTyp, objInr, "MAXSUM", "AMT1", date);
                lgbdetgVo.setOldamt(max.getAmt());
                lgbdetgVo.setOldxrfamt(max.getAmt());
            }
            lgbdetgVo.setTyp(lgo.getExtid());
            lgbdetgVo.setPtyinr(lgo.getPtyinr());
            lgbdetgVo.setLgoinr(lgo.getInr());
            lgbdetgVo.setCur(lgo.getCur());
            Lgl lgl = lglMapper.getLglByLgoinr(lgo.getInr());
            lgbdetgVo.setLgl(lgl);
            lgbdetVo.addLgbdetg(lgbdetgVo);
        });
    }

    /**
     *   source:lgbdet.0003.script
     */
    public void internalSetLGBISM(LgbdetVo lgbdetVo) {
        //! 根据请求信息设置LGO对应的LGB/LGA信息并赋值到LSBISM模块中
        lgbdetVo.getLgbism().clear();
        for (int i=0; i<lgbdetVo.getLgbdetg().size(); i++) {
            LgbdetgVo lgbdetgVo = lgbdetVo.getLgbdetg().get(i);
            if(MdaUtils.compareTo(lgbdetgVo.getLgoinr(),"NEW") == 0) {
                // 如果是起手交易，则给相关栏位初始化
                this.setLgo(lgbdetgVo, lgbdetVo);
                this.setLge(lgbdetgVo);
                lgbdetgVo.setLgl(new Lgl());
            } else {
                // 非起手交易，LGO/LGL均有值，只需新增LGE
                lgbdetgVo.getLgo().setCur(lgbdetgVo.getCur());
                this.setLge(lgbdetgVo);
            }
            String lgbInr = getLgbInr(lgbdetgVo);
            if(MdaUtils.isEmpty(lgbInr)) {
                lgbdetVo.setErrsta("E");
                /**
                 ERRMSG = "融资性对外担保额度未维护或状态不正常"

                 **/
                lgbdetVo.setErrmsg("二级福费廷额度未维护或状态不正常");
                return;
            }
            setLgb(lgbdetVo, lgbInr, i);
        }
    }

    /**
     *   source:lgbdet.0005.script
     */
    public void internalSetAmount(LgbdetVo lgbdetVo) {
        //! 计算发生额Pending Amount
        for (int i=0; i<lgbdetVo.getLgbism().size(); i++) {
            for(int j=1; j<=Streams.streamCount(lgbdetVo.getLgbism().get(i).getIdxstm()); j++){
                int idx = Integer.parseInt(Strings.getLine(lgbdetVo.getLgbism().get(i).getIdxstm(), j));
                lgbdetVo.getLgbdetg().get(idx).getLgl().setLgbinr(lgbdetVo.getLgbism().get(i).getLgb().getInr());
                if(MdaUtils.isEmpty(lgbdetVo.getLgbdetg().get(idx).getLgo().getXrfcur())) {
                    lgbdetVo.getLgbdetg().get(idx).getLgo().setXrfcur(lgbdetVo.getLgbism().get(i).getLgb().getCur());
                }
                if(MdaUtils.isEmpty(lgbdetVo.getLgbdetg().get(idx).getLge().getXrfcur())) {
                    lgbdetVo.getLgbdetg().get(idx).getLge().setXrfcur(lgbdetVo.getLgbism().get(i).getLgb().getCur());
                }
                BigDecimal totAmt = lgbdetVo.getLgbism().get(i).getTotamt();
                Argument<BigDecimal> totAmtBox = new Argument<BigDecimal>("",totAmt);
                this.setAmount(lgbdetVo.getLgbdetg().get(idx), totAmtBox);
                totAmt = totAmtBox.value;
                lgbdetVo.getLgbism().get(i).setTotamt(totAmt);
            }
            if(MdaUtils.compareTo(lgbdetVo.getLgbism().get(i).getTotamt(), 0) >= 0) {
                String cr = "";
                String text = "";
                if(MdaUtils.isEmpty(lgbdetVo.getErrmsg())) {
                    cr = "";
                } else {
                    cr = CR;
                }
                lgbdetVo.getLgbism().get(i).getLga().setNacamt(Decimals.add(lgbdetVo.getLgbism().get(i).getLga().getNacamt(), lgbdetVo.getLgbism().get(i).getTotamt()));
                if(MdaUtils.compareTo(lgbdetVo.getLgbism().get(i).getTotamt(),0) > 0) {
                    String typ = lgbdetVo.getLgbism().get(i).getLgb().getTyp();
                    Optional<CodetableItem> item = typList.stream().filter(f -> typ.equals(f.getValue())).findFirst();
                    if (item.isPresent()) {
                        text = item.get().getLabel();
                    }
                    if(MdaUtils.compareTo(Decimals.add(lgbdetVo.getLgbism().get(i).getLga().getNacamt(), lgbdetVo.getLgbism().get(i).getLga().getUseamt()),
                            lgbdetVo.getLgbism().get(i).getLgb().getAmt()) > 0) {
                        if(MdaUtils.isEmpty(lgbdetVo.getErrsta())) {
                            //this.setErrsta( "W");
                            //---经办控制不让SAVE---
                            lgbdetVo.setErrsta( "E");
                        }
                        lgbdetVo.setErrmsg(lgbdetVo.getErrmsg() + cr + text + "额度不足");
                        cr = CR;
                    }
                    if(Dates.diff(lgbdetVo.getLgbism().get(i).getLgb().getExpdat(), Dates.today()) < 0) {
                        if(MdaUtils.isEmpty(lgbdetVo.getErrsta())) {
                            lgbdetVo.setErrsta( "W");
                        }
                        lgbdetVo.setErrmsg(lgbdetVo.getErrmsg() + cr + text + "额度已过期");
                    }
                }
            } else {
                for(int j=1; j<=Streams.streamCount(lgbdetVo.getLgbism().get(i).getIdxstm()); j++) {
                    int idx = Integer.parseInt(Strings.getLine(lgbdetVo.getLgbism().get(i).getIdxstm(), j));
                    lgbdetVo.getLgbdetg().get(idx).getLge().setLgeflg(NULLSTR);
                }
            }
        }
    }

    /**
     *   source:lgbdet.0018.script
     */
    public void lgbDetSetCancel(LgbdetVo lgbdetVo, String extID, SimpleModuleVo linkModule) {
        String cur;
        Argument<String> curBox = new Argument<String>();
        BigDecimal amt;
        Argument<BigDecimal> amtBox = new Argument<BigDecimal>();
        this.lgbGetOldCurAmt(lgbdetVo, extID, curBox, amtBox );

        cur = curBox.value;
        amt = amtBox.value;

        if(MdaUtils.compareTo(amt,0) > 0) {
            this.lgbDetSetLimitAmount(lgbdetVo,"FFT", cur, amt.negate(), linkModule);
        }
    }

    /**
     *   source:lgbdet.0019.script
     */
    public void lgbGetOldCurAmt(LgbdetVo lgbdetVo, String extID, Argument<String> cur, Argument<BigDecimal> amt) {
        cur.value = "";
        amt.value = new BigDecimal("0");
        Bch bch = SettleContext.getUserSession().getBch();
        if (bch == null) {
            throw new CommonServiceException("无法获取当前经办机构");
        }
        Pty pty = ptyMapper.queryDetailByExtkey(bch.getSwfcod());
        if (pty == null) {
            throw new CommonServiceException("无法获取当前经办机构的客户信息");
        }
        String ptyInr = pty.getInr();
        String grpKey = extID + TAB + ptyInr;
        for (int i=0; i<lgbdetVo.getLgbdetg().size(); i++) {
            if( MdaUtils.compareTo(lgbdetVo.getLgbdetg().get(i).getGrpkey(), grpKey) == 0 ) {
                cur.value = lgbdetVo.getLgbdetg().get(i).getCur();
                amt.value = lgbdetVo.getLgbdetg().get(i).getOldamt();
                break;
            }
        }
    }

    /**
     *   source:lgbdet.0016.script
     */
    public void lgbDetSetModule(SimpleModuleVo linkModule) {
        this.lgbdetParSet(Utils.toJson(linkModule), "ADDMODULE", "ALL");
    }

    /**
     *   source:lgbdetg.0000.script
     */
    public void setLgo(LgbdetgVo lgbdetgVo, LgbdetVo lgbdetVo) {
        //! 初始化LGO栏位
        Lgo lgo = new Lgo();
        lgo.setInr(lgbdetgVo.getLgoinr());
        SimpleModuleVo linkModule = Utils.toObject(SimpleModuleVo.class, lgbdetgVo.getObjmodpth());
        lgo.setObjtyp(linkModule.getObjtyp());
        lgo.setObjinr(linkModule.getObjinr());
        lgo.setExtid(lgbdetgVo.getTyp());
        lgo.setCur(lgbdetgVo.getCur());
        lgo.setMatdat(lgbdetVo.getRec().getMatdat());
        lgo.setOwnref(lgbdetVo.getRec().getOwnref());
        Bch wrkbch = SettleContext.getUserSession().getWrkbch();
        if (wrkbch != null) {
            lgo.setBchkeyinr(wrkbch.getInr());
        }
        lgo.setPtyinr(lgbdetgVo.getPtyinr());
        lgbdetgVo.setLgo(lgo);
    }

    /**
     *   source:lgbdetg.0001.script
     */
    public void setLge(LgbdetgVo lgbdetgVo) {
        //! 初始化LGE栏位
        Lge lge = new Lge();
        lge.setObjtyp("ORD");
        lge.setObjinr(transactionHelpService.getTransactionStoreSet().getTrnmodVo().getOrdmod().getOrdinr());
        lge.setExtid(lgbdetgVo.getTyp());
        lge.setCur(lgbdetgVo.getCur());
        lge.setAmt(lgbdetgVo.getAmt());
        lge.setLgeflg("N");
        lge.setDattim(Dates.now());
        lgbdetgVo.setLge(lge);
    }

    /**
     *   source:lgbdetg.0002.script
     */
    public String getLgbInr(LgbdetgVo lgbdetgVo) {
        //! 根据LGO/LGL的赋值情况确定对应的LGB的INR
        String lgbInr = "";
        if(!MdaUtils.isEmpty(lgbdetgVo.getLgl().getLgbinr())) {
            lgbInr = lgbdetgVo.getLgl().getLgbinr();
        } else {
            Lgb lgb = lgbMapper.queryLgbByPtyInrAndTypAndSta(lgbdetgVo.getTyp(), lgbdetgVo.getPtyinr(), "N");
            if (lgb != null) {
                lgbInr = lgb.getInr();
            }
        }
        return lgbInr;

    }

    /**
     *   source:lgbdet.0004.script
     */
    public void setLgb(LgbdetVo lgbdetVo, String lgbInr, int idx) {
        int find = -1;
        for (int i=0; i<lgbdetVo.getLgbism().size(); i++) {
            if(MdaUtils.compareTo(lgbdetVo.getLgbism().get(i).getLgb().getInr(), lgbInr) == 0) {
                find = i;
                break;
            }
        }
        if (find == -1) {
            //没有找到新增一条lbgism
            LgbismVo lgbismVo = new LgbismVo();
            Lgb lgb = lgbMapper.selectByInr(lgbInr);
            lgbismVo.setLgb(lgb);
            Lga lga = lgaMapper.selectByLgbInr(lgbInr);
            if (lga == null) {
                lga = new Lga();
            }
            lgbismVo.setLga(lga);
            Streams.streamInsert(lgbismVo.getIdxstm(), 0, MdaUtils.toString(idx));
            lgbdetVo.addLgbism(lgbismVo);
        } else {
            Streams.streamInsert(lgbdetVo.getLgbism().get(find).getIdxstm(), 0, MdaUtils.toString(idx));
        }
    }

    /**
     *   source:lgbdetg.0003.script
     */
    public void setAmount(LgbdetgVo lgbdetgVo, Argument<BigDecimal> totAmt) {
        //! 计算LGO\\LGE的XrfAmt
        lgbdetgVo.getLgo().setAmt(Decimals.add(lgbdetgVo.getOldamt(), lgbdetgVo.getLge().getAmt()));
        if(MdaUtils.compareTo(lgbdetgVo.getLgo().getAmt(), 0) < 0) {
            lgbdetgVo.getLgo().setAmt(new BigDecimal("0"));
            lgbdetgVo.getLge().setAmt(lgbdetgVo.getOldamt().negate());
        }
        BigDecimal xrfAmt = null;
        if( MdaUtils.compareTo(lgbdetgVo.getLgo().getCur(), lgbdetgVo.getLgo().getXrfcur()) == 0 ) {
            xrfAmt = lgbdetgVo.getLgo().getAmt();
        } else {
            xrfAmt = xrtmodService.amtConvTypes(lgbdetgVo.getLgo().getCur(), lgbdetgVo.getLgo().getAmt(), "M", lgbdetgVo.getLgo().getXrfcur(), "M", Dates.today() );
        }
        lgbdetgVo.getLge().setXrfamt(Decimals.sub(xrfAmt, lgbdetgVo.getOldxrfamt()));
        lgbdetgVo.getLgo().setXrfamt(xrfAmt);
        totAmt.value = Decimals.add(totAmt.value, lgbdetgVo.getLge().getXrfamt());
    }

    public LiaallSet getLiaallSet() {
        return transactionHelpService.getLiaallSet();
    }

    /**
     * 根据  argFucKey 和 argDtaKey 组合的键、argValue为值，往LiallSet中放入数据
     **/
    public void lgbdetParSet(String argValue, String argFucKey, String argDtaKey) {
        LiaallSet liaallSet = getLiaallSet();
        liaallSet.putLgbdetStr(argFucKey + TAB + argDtaKey, argValue);
    }

    /**
     * 根据  argFucKey 和 argDtaKey 组合的键，从liallSet中获取对应的KEY ,
     * 如果value 不为空 , 返回value
     * 为空   ,返回""
     **/
    public String lgbdetParGet(String argFucKey, String argDtaKey) {
        return getLiaallSet().getLgbdetStr(argFucKey + TAB + argDtaKey);
    }

    /**
     *   source:srvlgb.0000.script
     */
    public void doRelease(String ordInr) {
        List<Lge> lgeList = new ArrayList<>();
        List<LgbismVo> lgbismList = new ArrayList<>();
        readLgeRecord(ordInr, lgeList, lgbismList);
        if (lgeList.size() == 0 || lgbismList.size() == 0) {
            return;
        }
        releaseAmount(lgeList, lgbismList);
        releaseRecord(lgeList, lgbismList);
    }

    /**
     *   source:srvlgb.0006.script
     */
    public void doRepair(String ordInr) {
        List<Lge> lgeList = new ArrayList<>();
        List<LgbismVo> lgbismList = new ArrayList<>();
        readLgeRecord(ordInr, lgeList, lgbismList);
        if (lgeList.size() == 0 || lgbismList.size() == 0) {
            return;
        }
        List<Lgo> lgoList = new ArrayList<>();
        repairAmount(lgeList, lgoList, lgbismList);
        repairRecord(lgeList, lgoList, lgbismList);
    }

    /**
     *   source:srvlgb.0001.script
     */
    public void readLgeRecord(String ordinr, List<Lge> lgeList, List<LgbismVo> lgbismList) {
        String sql = "SELECT LGL.LGBINR lgbinr, LGE.INR lgeinr FROM LGE, LGL WHERE LGE.LGOINR = LGL.LGOINR AND LGE.OBJTYP = 'ORD' AND LGE.OBJINR = " + ordinr + " ORDER BY LGL.LGBINR";
        Map<String, Object> dyncMap = new HashMap<>();
        dyncMap.put("sql", sql);
        List<Map<String, Object>> list = publicMapper.dyncQueryMapList(dyncMap);
        if (list == null || list.size() == 0) {
            return;
        }
        for (int idx=0; idx<list.size(); idx++) {
            Map<String, Object> map = list.get(idx);
            String lgbinr = (String)map.get("lgbinr");
            String lgeinr = (String)map.get("lgeinr");
            Lge lge = lgeMapper.getLgeByInr(lgeinr);
            lgeList.add(lge);
            int find = -1;
            for (int i=0; i<lgbismList.size(); i++) {
                if(MdaUtils.compareTo(lgbismList.get(i).getLgb().getInr(), lgbinr) == 0) {
                    find = i;
                    break;
                }
            }
            if (find == -1) {
                //没有找到新增一条lbgism
                LgbismVo lgbismVo = new LgbismVo();
                Lgb lgb = lgbMapper.selectByInr(lgbinr);
                lgbismVo.setLgb(lgb);
                Lga lga = lgaMapper.selectByLgbInr(lgbinr);
                if (lga == null) {
                    lga = new Lga();
                }
                lgbismVo.setLga(lga);
                Streams.streamInsert(lgbismVo.getIdxstm(), 0, MdaUtils.toString(idx));
                lgbismList.add(lgbismVo);
            } else {
                Streams.streamInsert(lgbismList.get(find).getIdxstm(), 0, MdaUtils.toString(idx));
            }
        }
    }

    /**
     *   source:srvlgb.0002.script
     */
    public void releaseAmount(List<Lge> lgeList, List<LgbismVo> lgbismList) {
        for(int i=0; i<lgbismList.size(); i++) {
            for(int j=1; j<=Streams.streamCount(lgbismList.get(i).getIdxstm()); j++) {
                int idx = Integer.parseInt(Strings.getLine(lgbismList.get(i).getIdxstm(), j));
                if(MdaUtils.isEmpty(lgeList.get(idx).getLgeflg())) {
                    lgbismList.get(i).setTotamt(Decimals.add(lgbismList.get(i).getTotamt(), lgeList.get(idx).getXrfamt()));
                } else {
                    lgbismList.get(i).setNacamt(Decimals.add(lgbismList.get(i).getNacamt(), lgeList.get(idx).getXrfamt()));
                }
            }
            String text = "";
            String typ = lgbismList.get(i).getLgb().getTyp();
            Optional<CodetableItem> item = typList.stream().filter(f -> typ.equals(f.getValue())).findFirst();
            if (item.isPresent()) {
                text = item.get().getLabel();
            }
            if(MdaUtils.compareTo(lgbismList.get(i).getNacamt(),0) > 0) {
                if(MdaUtils.compareTo(Decimals.add(lgbismList.get(i).getLga().getNacamt(), lgbismList.get(i).getLga().getUseamt()), lgbismList.get(i).getLgb().getAmt()) > 0) {
                    throw new CommonServiceException(text + "额度不足。");
                }
                if(Dates.diff(lgbismList.get(i).getLgb().getExpdat(), Dates.today()) < 0) {
                    throw new CommonServiceException(text + "额度已过期。");
                }
            }
            lgbismList.get(i).getLga().setNacamt(Decimals.sub(lgbismList.get(i).getLga().getNacamt(), lgbismList.get(i).getNacamt()));
            lgbismList.get(i).getLga().setUseamt(Decimals.add(Decimals.add(lgbismList.get(i).getLga().getUseamt(), lgbismList.get(i).getTotamt()), lgbismList.get(i).getNacamt()));
        }
    }

    /**
     *   source:srvlgb.0004.script
     */
    public void releaseRecord(List<Lge> lgeList, List<LgbismVo> lgbismList) {
        for(int i=0; i<lgeList.size(); i++) {
            lgeList.get(i).setLgeflg( "A");
            sysmodService.sdbUpdateWithLog(lgeList.get(i));
        }
        for(int i=0; i<lgbismList.size(); i++) {
            lgaMapper.updateByPrimaryKey(lgbismList.get(i).getLga());
        }
    }

    /**
     *   source:srvlgb.0003.script
     */
    public void repairAmount(List<Lge> lgeList, List<Lgo> lgoList, List<LgbismVo> lgbismList) {
        for(int i=0; i<lgbismList.size(); i++) {
            for (int j = 1; j <= Streams.streamCount(lgbismList.get(i).getIdxstm()); j++) {
                int idx = Integer.parseInt(Strings.getLine(lgbismList.get(i).getIdxstm(), j));
                if(!MdaUtils.isEmpty(lgeList.get(idx).getLgeflg())) {
                    lgbismList.get(i).setNacamt(Decimals.add(lgbismList.get(i).getNacamt(), lgeList.get(idx).getXrfamt()));
                }
                Lgo lgo = lgoMapper.getLgoByInr(lgeList.get(idx).getLgoinr());
                lgo.setAmt(Decimals.sub(lgo.getAmt(), lgeList.get(idx).getAmt()));
                lgo.setXrfamt(Decimals.sub(lgo.getXrfamt(), lgeList.get(idx).getXrfamt()));
                lgoList.add(lgo);
            }
            lgbismList.get(i).getLga().setNacamt(Decimals.sub(lgbismList.get(i).getLga().getNacamt(), lgbismList.get(i).getNacamt()));
        }
    }

    /**
     *   source:srvlgb.0005.script
     */
    public void repairRecord(List<Lge> lgeList, List<Lgo> lgoList, List<LgbismVo> lgbismList) {
        for(int i=0; i<lgeList.size(); i++) {
            sysmodService.sdbDeleteWithLog(lgeList.get(i));
        }
        for(int i=0; i<lgoList.size(); i++) {
            if(!MdaUtils.isEmpty(lgoList.get(i).getInr())) {
                sysmodService.sdbUpdateWithLog(lgoList.get(i));
            }
        }
        for(int i=0; i<lgbismList.size(); i++) {
            lgaMapper.updateByPrimaryKey(lgbismList.get(i).getLga());
        }
    }
}
