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

import com.brilliance.mda.runtime.mda.IStream;
import com.brilliance.mda.runtime.mda.impl.Argument;
import com.brilliance.mda.runtime.mda.impl.StreamImpl;
import com.brilliance.mda.runtime.mda.util.*;
import com.brilliance.isc.bo.*;
import com.brilliance.isc.common.api.bch.service.BchService;
import com.brilliance.isc.common.cache.pty.PtyCacheService;
import com.brilliance.isc.common.cbsmod.service.CbsmodService;
import com.brilliance.isc.common.cbsmod.service.XrtmodService;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.component.PtsptaToolComponent;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.converter.DtoMapper;
import com.brilliance.isc.common.counter.service.CounterService;
import com.brilliance.isc.common.exception.CommonServiceException;
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.setfeg.fee.FeeSet;
import com.brilliance.isc.common.setfeg.service.SetfegService;
import com.brilliance.isc.common.setfeg.vo.SetfelVo;
import com.brilliance.isc.common.setgll.service.SetgllService;
import com.brilliance.isc.common.setgll.vo.SetgllVo;
import com.brilliance.isc.common.transaction.help.TransactionHelpService;
import com.brilliance.isc.common.trnmod.service.TrnmodService;
import com.brilliance.isc.common.util.SettleExceptionUtils;
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.GleVo;
import com.brilliance.isc.common.vo.PtsptaVo;
import com.brilliance.isc.mda.dao.ActMapper;
import com.brilliance.isc.mda.dao.GleMapper;
import com.brilliance.isc.mda.dao.TaxMapper;
import com.brilliance.isc.mda.dao.TrmMapper;
import com.brilliance.isc.vo.component.trtcre.TrtcreVo;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

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

@Service("glemodService")
public class GlemodServiceImpl implements GlemodService {

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

    @Autowired
    private PtyCacheService ptyCacheService;

    @Autowired
    private BchService bchService;

    @Autowired
    private ActMapper actMapper;

    @Autowired
    private TaxMapper taxMapper;

    @Autowired
    private GleMapper gleMapper;

    @Autowired
    private Environment environment;

    @Autowired
    private TransactionHelpService transactionHelpService;

    //@Autowired
    //private Trnmod trnmod;

    @Autowired
    private CodetableService codetableService;

    @Autowired
    private CbsmodService cbsmod;

    @Autowired
    private XrtmodService xrtmod;

    @Autowired
    private CounterService counterService;

    @Autowired
    private LiaallService liaallService;

    @Autowired
    private SetgllService setgllService;

    @Autowired
    private PtsptaToolComponent ptsptaToolComponent;

    @Autowired
    private TrmMapper trmMapper;

    @Autowired
    private TrnmodService trnmodService;

    @Autowired
    private SetfegService setfegService;

    /**
     * source:glemod.0000.script
     * @Rule(target=".mtabut.sav",order=1200)
     *
     * ruleMtabutSavN1200
     */
    public void saveGle(GlemodVo glemodVo) {
        fillGLEStream(glemodVo);
        this.gleCommit(glemodVo);
    }
    /**
     * source:glemod.0009.script
     * 试算会计分录。
     */
    @Override
    public GlemodVo ruleGlepanN1000(GlemodVo glemod) throws CommonServiceException {
//        Modules.invokeExpress(this, "\\SETMOD.AssertSetmod", -1);
//        int ignore = ctx.getErrorCode();
//        Modules.invokeExpress(this, "assertLIAALL", -1);
//        ignore = ctx.getErrorCode();
        fillGLEStream(glemod);
        return glemod;
    }

    public String getHeqinr() {
        Pty ownpty = ptyCacheService.getOwnPty();
        if (ownpty != null) {
            return ownpty.getInr();
        }
        return "";
    }

    /**
     * source:glemod.0003.script
     */
    public void gleStoreEntry(GlemodVo glemod, GleVo entry) {
        // Modified by ZJ on Feb 2008
        // 会计模组移植
        // 5.05与5.01区别不大
        String frame = SettleContext.getTransName();
        if (entry.getAmt().compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        if (MdaUtils.isEmpty(entry.getDbtcdt())) {
            SettleExceptionUtils.sysDump("D/C-Flag not set in Booking");
        }
        entry.setTrninr(transactionHelpService.getTrninr());
        /*if (StringUtils.isEmpty(entry.getTrninr())) {
            SettleExceptionUtils.sysDump("Cannot get \\TRN\\INR");
        }*/
        // 5.01特有
        //----by zh <<<<新一代业务处理
        int order = 0;
        if (MdaUtils.compareTo(entry.getNewactcod(), "5006") == 0) {
            //--如果是结售汇，存入上次分录的顺序号＋‘/’+这次的分录顺序号1或2
            // 否则存入这次的分录顺序号
            //　ACTTRNCOD为3时在外层处理(gleexchsav)
        } else {
            order = transactionHelpService.getGlenmb();
            entry.setGleord(String.valueOf(order + 1));
        }
        //----by zh >>>>新一代业务处理
        entry.setAmt(xrtmod.amtRnd(entry.getAmt(), entry.getCur()));
        // 5.01特有 end
        glemod.setGlenmb(glemod.getGlenmb() + 1); //gle计算加1
        if (MdaUtils.isEmpty(entry.getNewactcod())) {
            if (MdaUtils.compareTo(frame, "BPTFFT") == 0) {
                entry.setNewactcod("4338");
            } else {
                entry.setNewactcod("7759");
            }
        }
        /**
         select case \\TRNMOD\\TRN\\OBJTYP
         case "DID"
         entry\\OBJTYP = "LID"
         case "DED"
         entry\\OBJTYP = "LED"
         case "BDD"
         entry\\OBJTYP = "BRD"
         case "BFD"
         entry\\OBJTYP = "BED"
         case else
         entry\\OBJTYP = \\TRNMOD\\TRN\\OBJTYP
         end select
         **/
        entry.setObjtyp(glemod.getRec().getObjtyp());
        //entry\\OBJTYP = \\TRNMOD\\TRN\\OBJTYP
        entry.setObjinr(glemod.getRec().getObjinr());
        // 保存记账机构
        Bch accbch = SettleContext.getUserSession().getBch();
        if (accbch != null) {
            entry.setBranchinr(accbch.getInr());
        }
        if (MdaUtils.isEmpty(entry.getBucdat())) {
            entry.setBucdat(Dates.today());
        }
        if (MdaUtils.isEmpty(entry.getValdat())) {
            entry.setValdat(entry.getBucdat());
        }
        entry.setExpses("");
        entry.setExpflg("S");
        //Gle还要继续使用，那么Gle需要拷贝一份，避免使用同一个实例
        GleVo temp = new GleVo();
        BeanUtils.copyProperties(entry,temp);
        glemod.getGles().add(temp);

        /*String line = entry.getPrn() + TAB + entry.getTrninr() + TAB + entry.getDbtcdt() + TAB + entry.getCur() + TAB + entry.getAmt().toPlainString() + TAB + Utils.fmtDate(entry.getValdat()) + TAB + entry.getAct() + TAB + entry.getWhmtyp() + TAB + entry.getRat().toPlainString() + TAB + entry.getTrmtyp();
        Streams.streamInsert(glemod.getGleshwstm(),0,line);*/
    }

    /**
     * source:glemod.0005.script
     */

    public String getGLCur() {
        return xrtmod.sysiso();
    }

    /**
     * source:glemod.0007.script
     */
    @Override
    public void fillGLEStream(GlemodVo glemod) {
        //! Create actual GLE Stream from SETMOD and LIAONE data
        glemod.setGlesrm(new StreamImpl());
        glemod.setGlenmb(0);
        glemod.setGleshwstm(new StreamImpl());
        glemod.setMaxamtd(new BigDecimal(0));
        glemod.setMaxactd(NULLSTR);
        glemod.setMaxamtc(new BigDecimal(0));
        glemod.setMaxactc(NULLSTR);
        glemod.setJshactd(NULLSTR);
        glemod.setJshactc(NULLSTR);
        //外币贷款专户赋值
        TrtcreVo trtcreVo = glemod.getRec().getTrtcreVo();
        if (trtcreVo != null && "X".equals(trtcreVo.getCrefinflg())) {
            glemod.setFfaflg(trtcreVo.getTrdgrp().getRec().getFfaflg());
            glemod.setFfaacc(trtcreVo.getTrtp().getWbdp().getAct());
        } else if(MdaUtils.compareTo(SettleContext.getTransName(), "TRTOPN") == 0) {
            glemod.setFfaflg(Utils.getFieldValue(glemod.getRec(), "ffaflg", ""));
            glemod.setFfaacc(Utils.getFieldValue(glemod.getRec(), "ffaacc", ""));
        }
        glemod.getGles().clear();
        gleSavSetmod(glemod);
        liaallService.createGLEFromLIA(glemod);
        /*MdaUtils.clear(this.getGlesrm());
        this.setGlenmb(0);
        MdaUtils.clear(this.getGleshwstm());
        this.setMaxamtd(new BigDecimal(0));
        this.setMaxactd(NULLSTR);
        this.setMaxamtc(new BigDecimal(0));
        this.setMaxactc(NULLSTR);
        this.setJshactd(NULLSTR);
        this.setJshactc(NULLSTR);
        gleSavSetmod();
        // post function, because liaall is not always available, when setmod is available
        Modules.invokeExpress(null, "\\LIAALL.CreateGLEFromLIA", -1);
        //int ignore = ctx.getErrorCode();
        // post function, because CBSCHG is not always available, when setmod is available
        //Modules.invokeExpress(this, "\\CBSCHG.CreateGLEFromCbschg", -1);
//        ignore = ctx.getErrorCode();
//        if (MdaUtils.isEmpty(this.getGleshwstm())) {
//            Systems.resetVisible(this, "glepan");
//        } else {
//            Streams.streamSort(this.getGleshwstm());
//            Systems.setVisible(this, "glepan");
//        }*/

    }

    /**
     * source:glemod.0010.script
     */
    public void gleSavSetmod(GlemodVo glemod) {
        int prnNum = 5000;
        String oppacc = "";
        String oppnam = "";
        String oppbnk = "";
        //----LWQ0509不按照分录对应及借贷关系取，交易中统一取值----
        Argument<String> oppaccBox = new Argument<String>("", oppacc);
        Argument<String> oppnamBox = new Argument<String>("", oppnam);
        Argument<String> oppbnkBox = new Argument<String>("", oppbnk);
        trnmodService.east7759(glemod.getRec(), glemod.getPtsList(), glemod.getSetglg().getSetgll(), oppaccBox, oppnamBox, oppbnkBox);

        oppacc = oppaccBox.value;
        oppnam = oppnamBox.value;
        oppbnk = oppbnkBox.value;

        String oppactj = "";
        String oppactd = "";
        String jact = "";
        String dact = "";
        //---所有分录按借贷关系出，除了收付款取国外对方账号，多条的时候取金额最大的190612---
        Argument<String> oppactjBox = new Argument<String>("", oppactj);
        Argument<String> oppactdBox = new Argument<String>("", oppactd);
        Argument<String> jactBox = new Argument<String>("", jact);
        Argument<String> dactBox = new Argument<String>("", dact);
        east7759act(glemod, oppactjBox, oppactdBox, jactBox, dactBox);

        oppactj = oppactjBox.value;
        oppactd = oppactdBox.value;
        jact = jactBox.value;
        dact = dactBox.value;

        String frame = SettleContext.getTransName();
        //Charges to be booked
        List<SetfelVo> setfels = glemod.getSetfeg().getSetfel();
        int gridcnt = setfels.size();
        String feeAcc = NULLSTR;
        String cur_id = NULLSTR;
        String taxAcc = NULLSTR;
        BigDecimal gleamt = null;
        BigDecimal sysamt = null;
        BigDecimal glerat = BigDecimal.ZERO;
        String trmtyp = NULLSTR;
        BigDecimal taxrate = BigDecimal.ZERO;
        String sql = NULLSTR;
        String taxcod = NULLSTR;
        BigDecimal taxrat = BigDecimal.ZERO;
        BigDecimal fepamt = null;
        String ref = NULLSTR;
        String ptyInr = NULLSTR;
        String extKey = NULLSTR;
        String ptspta = NULLSTR;
        Map<String, Object> dyncMap = new HashMap<>();
        for (int j = 0; j < gridcnt; j++) {
            SetfelVo setfelVo = setfels.get(j);
            if (MdaUtils.compareTo(setfelVo.getDsp(), "X") == 0) {
                GleVo gle = new GleVo();
                // debit or credit ?
                if (MdaUtils.compareTo(setfelVo.getAmt(), 0) < 0) {
                    gle.setDbtcdt("D");
                } else {
                    gle.setDbtcdt("C");
                }
                gle.setAmt(setfelVo.getAmt());
                gle.setSysamt(setfelVo.getXrfamt());
                gle.setCur(setfelVo.getCur());
                gle.setSyscur(xrtmod.sysiso());
                //    GLE\\TRMTYP = Mid( setfeg\\setfel\\ ( $j )\\feeacc, 3, 5 )
                // 从5.01移植改造
                feeAcc = "";
                cur_id = Strings.mid(codetableService.getTblLabel(setfelVo.getCur(), "CURKEY"), 1, 2);
                if (!MdaUtils.isEmpty(Strings.trim(cur_id))) {
                    if (MdaUtils.compareTo(Strings.mid(setfelVo.getFeeacc(), 1, 2), "??") == 0) {
                        feeAcc = cur_id + Strings.mid(setfelVo.getFeeacc(), 3, 11);
                    }
                }
                taxAcc = "";
                if (!MdaUtils.isEmpty(setfelVo.getTaxacc())) {
                    cur_id = Strings.mid(codetableService.getTblLabel(setfelVo.getCur(), "CURKEY"), 1, 2);
                    if (!MdaUtils.isEmpty(Strings.trim(cur_id))) {
                        if (MdaUtils.compareTo(Strings.mid(setfelVo.getTaxacc(), 1, 2), "??") == 0) {
                            taxAcc = cur_id + Strings.mid(setfelVo.getTaxacc(), 3, 11);
                        }
                    }
                }
                //------------------------------------------->>
                if (!MdaUtils.isEmpty(feeAcc)) {
                    feeAcc = getAccbch() + feeAcc;
                }
                //
                //------------------------------------------->>
                if (!MdaUtils.isEmpty(taxAcc)) {
                    taxAcc = getAccbch() + taxAcc;
                }
                gleamt = new BigDecimal("0");
                sysamt = new BigDecimal("0");
                if (!MdaUtils.isEmpty(taxAcc)) {
                    gle.setAct(taxAcc);
                    buildTrmtyp(gle);
                    Trm feeTrm = actGetTermid(feeAcc);
                    if (feeTrm != null) {
                        trmtyp = feeTrm.getTrmcod();
                    }
                    sql = "SELECT TAXRAT FROM TAX WHERE TAXCOD='T000000001' ";
                    dyncMap.put("sql", sql);
                    List<Tax> taxList = taxMapper.dyncRead(dyncMap);
                    if (taxList != null && taxList.size() > 0) {
                        taxrate = taxList.get(0).getTaxrat();
                    }
                    sql = "SELECT TAXCOD,TAXRAT FROM TAX WHERE BUSCOD = '" + trmtyp + "' and custyp is null";
                    dyncMap.put("sql", sql);
                    taxList = taxMapper.dyncRead(dyncMap);
                    if (taxList != null && taxList.size() > 0) {
                        taxcod = taxList.get(0).getTaxcod();
                        taxrat = taxList.get(0).getTaxrat();
                    }
                    if (!StringUtils.isEmpty(taxcod)) {
                        taxrate = taxrat;
                    }
                    if (taxrate.compareTo(BigDecimal.ZERO) > 0) {
                        gle.setAmt(getTaxAmt(setfelVo.getAmt(), taxrate));
                        gle.setSysamt(getTaxAmt(setfelVo.getXrfamt(), taxrate));
                        glerat = taxrate;
                        gleamt = gle.getAmt();
                        sysamt = gle.getSysamt();
                        fepamt = Decimals.sub(setfelVo.getAmt(), gle.getAmt());
                        gle.setValdat(Dates.today());
                        if (!MdaUtils.isEmpty(gle.getTrmtyp())) {
                            prnNum = prnNum + 1;
                        }
                        gle.setPrn(MdaUtils.toString(prnNum));
                        /*if (Strings.pos(frame, "MCT") > 0) {
                            ref = Datas.getContent(this, "\\" + Platform.recGetObj(ctx.absGet(Mtabut.class).getRec()) + "GRP\\REC\\SUBREF");
                        } else {
                            ref = Datas.getContent(this, "\\" + Platform.recGetObj(ctx.absGet(Mtabut.class).getRec()) + "GRP\\REC\\OWNREF");
                        }*/
                        if (Strings.pos(frame, "MCT") > 0) {
                            ref = glemod.getRec().getSubref();
                        } else {
                            ref = glemod.getRec().getOwnref();
                        }
                        gle.setTxt1("Charges for " + ref);
                        gle.setActtrncod(Strings.mid(codetableService.getTblLabel(gle.getTrmtyp(), "TRMTYP"), 2, 1));
                        gle.setTxt2(ref + " " + setfelVo.getFeetxtinf() + "销项税");
                        // 存费用种类FeeCod
                        gle.setTaxinf("TAXCP" + "::" + trmtyp + "::" + glerat.divide(new BigDecimal("100")).stripTrailingZeros().toPlainString() + "::" + Numerics.round(fepamt, 2).toPlainString());
                        gle.setDebitact(oppactj);
                        ptyInr = setfelVo.getRolptyinr();
                        if (!MdaUtils.isEmpty(ptyInr)) {
                            Pty pty = ptyCacheService.getPtyById(ptyInr);
                            if (pty != null) {
                                gle.setCliextkey(pty.getExtkey());
                            }
                        }
                        if (Strings.len(gle.getCliextkey()) != 10) {
                            gle.setCliextkey(getCliextkey(glemod));
                        }
                        //---EAST7759---
                        if( MdaUtils.compareTo(gle.getDbtcdt(),"D") == 0 ) {
                            gle.setEastoppacc(oppactd);
                            gle.setEastoppnam("");
                            gle.setEastoppbnk("");
                        } else {
                            //---所有分录按借贷关系出，除了收付款取国外对方账号，多条的时候取金额最大的190612---
                            gle.setEastoppacc(oppactj);
                            gle.setEastoppnam("");
                            gle.setEastoppbnk("");
                        }
                        //保存增值税相关的分录
                        gleStoreEntry(glemod, gle);
                    }
                }
                //------------------------------------------->>
                gle.setAct(feeAcc);    //setfeg\\setfel\\ ( $j )\\feeacc
                //    GLE\\ACT = GetAvailAcc( setfeg\\setfel\\ ( $j )\\feeacc, GLE\\CUR, "", self, GLE\\AMT )
                //!税则表使用规则，以当前业务代码去匹配税则表，如果税则表中可以匹配到该业务代码的数据且客户属性为空时使用该记录的税率，如果业务代码可以匹配到对应数据但是客户属性不为空时，使用默认T000000001的税率
                buildTrmtyp(gle);
                if (!MdaUtils.isEmpty(taxAcc)) {
                    gle.setAmt(Decimals.sub(setfelVo.getAmt(), gleamt));
                    gle.setSysamt(Decimals.sub(setfelVo.getXrfamt(), sysamt));
                } else {
                    gle.setAmt(setfelVo.getAmt());
                    gle.setSysamt(setfelVo.getXrfamt());
                }
                /*if (glerat.compareTo(BigDecimal.ZERO) > 0) {
                    setfelVo.getFecp1().setTaxrat(glerat);
                }*/
                gle.setValdat(Dates.today());
                if (!StringUtils.isEmpty(gle.getTrmtyp())) {
                    prnNum = prnNum + 1;
                }
                gle.setPrn(MdaUtils.toString(prnNum));
                if (Strings.pos(frame, "MCT") > 0) {
                    //ref = Datas.getContent(this, "\\" + Platform.recGetObj(ctx.absGet(Mtabut.class).getRec()) + "GRP\\REC\\SUBREF");
                    ref = glemod.getRec().getSubref();
                } else {
                    //ref = Datas.getContent(this, "\\" + Platform.recGetObj(ctx.absGet(Mtabut.class).getRec()) + "GRP\\REC\\OWNREF");
                    ref = glemod.getRec().getOwnref();
                }
                gle.setTxt1("Charges for " + ref);
                gle.setActtrncod(Strings.mid(codetableService.getTblLabel(gle.getTrmtyp(), "TRMTYP"), 2, 1));
                gle.setTxt2(ref + " " + setfelVo.getFeetxtinf());
                // 存费用种类FeeCod
                /**
                 if not IsEmpty( $TaxAcc ) then
                 GLE\\TAXINF = "Y::" + Str( $gleamt ) + "::" + Str( $GLERAT )
                 else
                 GLE\\TAXINF = "N"
                 endif\\
                 **/
                gle.setTaxinf("N");
                gle.setDebitact(oppactj);
                gle.setTxt3(setfelVo.getFeecod());
                ptyInr = setfelVo.getRolptyinr();
                if (!MdaUtils.isEmpty(ptyInr)) {
                    Pty pty = ptyCacheService.getPtyById(ptyInr);
                    if (pty != null) {
                        gle.setCliextkey(pty.getExtkey());
                    }
                }
                if (Strings.len(gle.getCliextkey()) != 10) {
                    gle.setCliextkey(getCliextkey(glemod));
                }
                //---EAST7759---
                if( MdaUtils.compareTo(gle.getDbtcdt(),"D") == 0 ) {
                    gle.setEastoppacc( oppactd);
                    gle.setEastoppnam( "");
                    gle.setEastoppbnk( "");
                } else {
                    //---所有分录按借贷关系出，除了收付款取国外对方账号，多条的时候取金额最大的190612---
                    gle.setEastoppacc(oppactj);
                    gle.setEastoppnam("");
                    gle.setEastoppbnk("");
                }
                gleStoreEntry(glemod, gle);
            }
        }
        //---EAST7759---
        //\\TRNMOD.east7759 ( $OPPACC, $OPPNAM, $OPPBNK )
        prnNum = 2000;
        //generate one booking entry per GLL-Row
        List<SetgllVo> setglls = glemod.getSetglg().getSetgll();
        gridcnt = setglls.size();
        String moudule = NULLSTR;
        int err = 0;
        String line = NULLSTR;
        String xzh = NULLSTR;
        String accCur = NULLSTR;
        String cur = NULLSTR;
        String jshcur = NULLSTR;
        String dCFlag = NULLSTR;
        BigDecimal amt = null;
        BigDecimal accAmt = null;
        String refGle = NULLSTR;
        if (gridcnt > 0) {
            for (int i = 0; i < gridcnt; i++) {
                SetgllVo setgllVo = setglls.get(i);
                GleVo gle = new GleVo();
                //    if not IsEmpty( SETGLG\\SETGLL( $i )\\acccpramt ) then
                if (!MdaUtils.isEmpty(setgllVo.getAct())) {
                    // GLL上实际的会计账
                    gle.setCur(setgllVo.getAcccur());
                    gle.setSyscur(xrtmod.sysiso());
                    /**      GLE\\AMT = Abs( SETGLG\\SETGLL( $i )\\acccpramt )
                     Clear( GLE\\SYSAMT )
                     for $j = 1 to $Gridcnt
                     if SETGLG\\SETGLL( $j )\\CPRMAC == SETGLG\\SETGLL( $i )\\CPRMAC then
                     if SETGLG\\SETGLL( $j )\\debcdtflg == SETGLG\\SETGLL( $i )\\debcdtflg then
                     GLE\\SYSAMT = Abs( GLE\\SYSAMT + SETGLG\\SETGLL( $j )\\xrfamt )
                     else
                     GLE\\SYSAMT = Abs( GLE\\SYSAMT - SETGLG\\SETGLL( $j )\\xrfamt )
                     endif
                     endif
                     next
                     **/
                    gle.setAmt(Numerics.abs(setgllVo.getAccamt()));
                    gle.setSysamt(Numerics.abs(setgllVo.getXrfamt()));
                    gle.setDbtcdt(setgllVo.getDebcdtflg());
                    gle.setAct(Strings.mid(setgllVo.getAct(), 1, 21));   // 光大账号位数为21位
                    gle.setValdat(setgllVo.getValdat());
                    gle.setTrmtyp(setgllVo.getActtrmtyp());
                    //---业务选择ARD,ACTTRMTYP选择2149,账号输入客户帐，此笔账务回单不会给核心，所以修改---
                    if (!MdaUtils.isEmpty(setgllVo.getActtrmtyp()) && !MdaUtils.isEmpty(setgllVo.getAcccode())) {
                        if (MdaUtils.compareTo(setgllVo.getActtrmtyp(), setgllVo.getAcccode()) != 0) {
                            gle.setTrmtyp(setgllVo.getAcccode());
                        }
                    }
                    Trm trm = null;
                    if ("1926".equals(gle.getTrmtyp()) || "2120".equals(gle.getTrmtyp()) || "2149".equals(gle.getTrmtyp())) {
                        String dbAct = "AAAABB" + setgllVo.getAct().substring(6);
                        trm = trmMapper.getTrmByAct(dbAct, null);
                    }
                    if (trm == null) {
                        trm = new Trm();
                        trm.setTrmcod(gle.getTrmtyp());
                        trm = trmMapper.selectByTrmcod(trm);
                    }
                    if (trm != null) {
                        gle.setTrmtypName(trm.getNam());
                    }
                    if (MdaUtils.compareTo(gle.getTrmtyp(), "2120") == 0) {
                        gle.setPrn("2000");
                    } else {
                        prnNum = prnNum + 10;
                        gle.setPrn(MdaUtils.toString(prnNum));
                    }
                    gleDefEntryFieldsCeb(glemod, gle, i);
                    //---EAST7759---
                    line = Strings.getLine(setgllVo.getAmtidsstm(), 1);
                    if (MdaUtils.compareTo(Strings.mid(line, 1, 7), "*SETFEG") == 0) {
                        gle.setEastoppacc(oppactd);
                        gle.setEastoppnam("");
                        gle.setEastoppbnk("");
                    } else {
                        if (isSHOUFUKUANset(glemod)) {
                            gle.setEastoppacc(oppacc);
                            gle.setEastoppnam(oppnam);
                            gle.setEastoppbnk(oppbnk);
                        } else {
                            if (MdaUtils.compareTo(gle.getDbtcdt(), "C") == 0) {
                                gle.setEastoppacc(jact);
                                if (MdaUtils.isEmpty(gle.getEastoppacc())) {
                                    gle.setEastoppacc(oppactj);
                                }
                            }
                            if (MdaUtils.compareTo(gle.getDbtcdt(), "D") == 0) {
                                gle.setEastoppacc(dact);
                                if (MdaUtils.isEmpty(gle.getEastoppacc())) {
                                    gle.setEastoppacc(oppactd);
                                }
                            }
                            gle.setEastoppnam("");
                            gle.setEastoppbnk("");
                        }
                    }
                    //资金池需求：所有交易都可输入虚账户信息
                    xzh = setgllVo.getXzhacc() + setgllVo.getXzhnam();
                    if (!MdaUtils.isEmpty(xzh)) {
                        gle.setEastinf(setgllVo.getXzhacc() + ";+;" + setgllVo.getXzhnam() + ";+;");
                    }
                    accCur = setgllVo.getAcccur();
                    cur = setgllVo.getCur();
                    if (MdaUtils.compareTo(cur, accCur) != 0) { // 币别不同，需要结售汇
                        gle.setJshnum(i);
                    }
                    gleStoreEntry(glemod, gle);
                }
                dCFlag = setgllVo.getDebcdtflg();
                if (MdaUtils.compareTo(gle.getTrmtyp(), "2435") == 0) {
                    //!出外币贷款专户会计分录,自动补足
                    if (!MdaUtils.isEmpty(glemod.getFfaflg())) {
                        //!1.贷记外币贷款专户
                        amt = setgllVo.getAmt();
                        sysamt = setgllVo.getXrfamt();
                        accAmt = setgllVo.getAccamt();
                        gle.setSyscur(xrtmod.sysiso());
                        gle.setAmt(Numerics.abs(amt));
                        gle.setCur(cur);
                        gle.setSysamt(Numerics.abs(sysamt));
                        gle.setDbtcdt("D");
                        gle.setAct(glemod.getFfaacc());
                        gle.setValdat(setgllVo.getValdat());
                        prnNum = prnNum + 10;
                        gle.setPrn(MdaUtils.toString(prnNum));
                        gle.setRat(new BigDecimal("0"));
                        gle.setTrmtyp("2088");
                        gleDefEntryFieldsCeb(glemod, gle, i);
                        gle.setEastoppacc(oppacc);
                        gle.setEastoppnam(oppnam);
                        gle.setEastoppbnk(oppbnk);
                        //!外币贷款专户要出现在给客户的核心的回单上，摘要暂定为业务编号
                        //refGle = Datas.getContent(this, "\\" + Platform.recGetObj(ctx.absGet(Mtabut.class).getRec()) + "GRP\\REC\\OWNREF");
                        refGle = glemod.getRec().getOwnref();
                        gle.setTxt1(refGle);
                        gle.setTxt2(gle.getTxt1());
                        gleStoreEntry(glemod, gle);
                        //!2.借记外币贷款专户
                        amt = setgllVo.getAmt();
                        sysamt = setgllVo.getXrfamt();
                        accAmt = setgllVo.getAccamt();
                        gle.setSyscur(xrtmod.sysiso());
                        gle.setAmt(Numerics.abs(amt));
                        gle.setCur(cur);
                        gle.setSysamt(Numerics.abs(sysamt));
                        gle.setDbtcdt("C");
                        gle.setAct(glemod.getFfaacc());
                        gle.setValdat(setgllVo.getValdat());
                        prnNum = prnNum + 10;
                        gle.setPrn(MdaUtils.toString(prnNum));
                        gle.setRat(new BigDecimal("0"));
                        gle.setTrmtyp("2088");
                        gleDefEntryFieldsCeb(glemod, gle, i);
                        gle.setEastoppacc(oppacc);
                        gle.setEastoppnam(oppnam);
                        gle.setEastoppbnk(oppbnk);
                        //!外币贷款专户要出现在给客户的核心的回单上，摘要暂定为业务编号
                        //refGle = Datas.getContent(this, "\\" + Platform.recGetObj(ctx.absGet(Mtabut.class).getRec()) + "GRP\\REC\\OWNREF");
                        refGle = glemod.getRec().getOwnref();
                        gle.setTxt1(refGle);
                        gle.setTxt2(gle.getTxt1());
                        gleStoreEntry(glemod, gle);
                    }
                }
                // 结售汇的账号
                accCur = setgllVo.getAcccur();
                cur = setgllVo.getCur();
                jshcur = "";
                if (MdaUtils.compareTo(cur, accCur) != 0) {   // 币别不同，需要结售汇
                    amt = setgllVo.getAmt();
                    sysamt = setgllVo.getXrfamt();
                    accAmt = setgllVo.getAccamt();
                    gle.setSyscur(xrtmod.sysiso());
                    if (MdaUtils.compareTo(dCFlag, "D") == 0) {
                        gle.setAmt(Numerics.abs(accAmt));
                        gle.setCur(accCur);
                        jshcur = cur;
                    } else {
                        gle.setAmt(Numerics.abs(amt));
                        gle.setCur(cur);
                        jshcur = accCur;
                    }
                    gle.setSysamt(Numerics.abs(sysamt));
                    gle.setDbtcdt("C");
                    gle.setAct(getAvailAcc("FX-SPR", gle.getCur(), "", gle.getAmt()));
                    gle.setValdat(setgllVo.getValdat());
                    prnNum = prnNum + 1;
                    gle.setPrn(MdaUtils.toString(prnNum));   // 结售汇
                    gle.setRat(setgllVo.getRat());
                    buildTrmtyp(gle);
                    gleDefEntryFieldsCeb(glemod, gle, i);
                    //---EAST7759---
                    /**
                     GLE\\EASTOPPACC = $OPPACC
                     GLE\\EASTOPPNAM = $OPPNAM
                     GLE\\EASTOPPBNK = $OPPBNK
                     **/
                    gle.setEastoppacc(getAvailAcc("FX-SPR", jshcur, "", gle.getAmt()));
                    gle.setEastoppnam("");
                    gle.setEastoppbnk("");
                    gle.setJshnum(i);
                    gleStoreEntry(glemod, gle);
                    // 第二条账
                    gle.setSyscur(xrtmod.sysiso());
                    if (MdaUtils.compareTo(dCFlag, "C") == 0) {
                        gle.setAmt(Numerics.abs(accAmt));
                        gle.setCur(accCur);
                        jshcur = cur;
                    } else {
                        gle.setAmt(Numerics.abs(amt));
                        gle.setCur(cur);
                        jshcur = accCur;
                    }
                    gle.setSysamt(Numerics.abs(sysamt));
                    gle.setDbtcdt("D");
                    gle.setAct(getAvailAcc("FX-SPR", gle.getCur(), "", gle.getAmt()));
                    gle.setValdat(setgllVo.getValdat());
                    prnNum = prnNum + 1;
                    gle.setPrn(MdaUtils.toString(prnNum));   // 结售汇
                    gle.setRat(setgllVo.getRat());
                    buildTrmtyp(gle);
                    gleDefEntryFieldsCeb(glemod, gle, i);
                    //---EAST7759---
                    /**
                     GLE\\EASTOPPACC = $OPPACC
                     GLE\\EASTOPPNAM = $OPPNAM
                     GLE\\EASTOPPBNK = $OPPBNK
                     **/
                    gle.setEastoppacc(getAvailAcc("FX-SPR", jshcur, "", gle.getAmt()));
                    gle.setEastoppnam("");
                    gle.setEastoppbnk("");
                    gle.setJshnum(i);
                    gleStoreEntry(glemod, gle);
                    // 第三条账
                    gle.setSyscur(xrtmod.sysiso());
                    if (MdaUtils.compareTo(dCFlag, "D") == 0) {
                        gle.setAmt(Numerics.abs(accAmt));
                        gle.setCur(accCur);
                        jshcur = cur;
                    } else {
                        gle.setAmt(Numerics.abs(amt));
                        gle.setCur(cur);
                        jshcur = accCur;
                    }
                    gle.setSysamt(Numerics.abs(sysamt));
                    gle.setDbtcdt("D");
                    gle.setAct(getAvailAcc( "FX-SPR", gle.getCur(), "", gle.getAmt()));
                    gle.setValdat(setgllVo.getValdat());
                    gle.setPrn("6001");   // 结售汇
                    gle.setRat(setgllVo.getRat());
                    buildTrmtyp(gle);
                    gle.setNewactcod("5006");
                    gle.setGleord("0");
                    gleDefEntryFieldsCeb(glemod, gle, i);
                    //---EAST7759---
                    /**
                     GLE\\EASTOPPACC = $OPPACC
                     GLE\\EASTOPPNAM = $OPPNAM
                     GLE\\EASTOPPBNK = $OPPBNK
                     **/
                    gle.setEastoppacc(getAvailAcc( "FX-SPR", jshcur, "", gle.getAmt()));
                    gle.setEastoppnam("");
                    gle.setEastoppbnk("");
                    gle.setJshnum(i);
                    gleStoreEntry(glemod, gle);
                    // 第四条账
                    gle.setSyscur(xrtmod.sysiso());
                    if (MdaUtils.compareTo(dCFlag, "C") == 0) {
                        gle.setAmt(Numerics.abs(accAmt));
                        gle.setCur(accCur);
                        jshcur = cur;
                    } else {
                        gle.setAmt(Numerics.abs(amt));
                        gle.setCur(cur);
                        jshcur = accCur;
                    }
                    gle.setSysamt(Numerics.abs(sysamt));
                    gle.setDbtcdt("C");
                    gle.setAct(getAvailAcc( "FX-SPR", gle.getCur(), "", gle.getAmt()));
                    gle.setValdat(setgllVo.getValdat());
                    gle.setPrn("6002");   // 结售汇
                    gle.setRat(setgllVo.getRat());
                    buildTrmtyp(gle);
                    gle.setNewactcod("5006");
                    gle.setGleord("1");
                    gleDefEntryFieldsCeb(glemod, gle, i);
                    //---EAST7759---
                    /**
                     GLE\\EASTOPPACC = $OPPACC
                     GLE\\EASTOPPNAM = $OPPNAM
                     GLE\\EASTOPPBNK = $OPPBNK
                     **/
                    gle.setEastoppacc(getAvailAcc( "FX-SPR", jshcur, "", gle.getAmt()));
                    gle.setEastoppnam("");
                    gle.setEastoppbnk("");
                    gle.setJshnum(i);
                    gleStoreEntry(glemod, gle);
                }
            }
        }

    }

    /**
     * source:glemod.0012.script
     */
    @Override
    public GlemodVo liaglesavCeb(GlemodVo glemod, String cur, BigDecimal amt, String engact, String engcat, String ref, String typ, Date value, String cbt, String txt2, String trmTyp1, String trmTyp2) {
        GleVo gle = new GleVo();
        String dt = NULLSTR;
        String cr = NULLSTR;
        if (MdaUtils.compareTo(amt, 0) > 0) {
            dt = "D";
            cr = "C";
        } else {
            dt = "C";
            cr = "D";
        }
        String pfx = "1";
        // Modified by ZJ on Feb 2008
        // 会计移植
        gle.setCur(cur);
        gle.setValdat(value);
        gle.setTxt1(glemod.getRec().getOwnref());
        /**
         //---将摘要中的回车替换成"#"
         GLE\\TXT2 = ReplaceCRtoChar( GetBriefRefCeb2 + " " + txt2, "#" )
         **/
        //---将摘要中的回车替换成" ",移除回车
        // gle.setTxt2(Utils.replaceCRtoChar(Platform.getBriefRefCeb2() + " " + txt2, " "));
        gle.setTxt2(glemod.getRec().getOwnref()+ " " + txt2);
        gle.setCliextkey(txt2);
        gle.setAmt(Numerics.abs(amt));
        //-----------新一代---------------
        gle.setNewactcod("7759");
        gle.setDbtdft("");
        //-----------------------------------
        String term_id1 = "";
        String term_id1_name = "";
        //Trm trm1 = actGetTermid(engact, trmTyp1);
        Trm trm1 = actGetTermid(engact);
        if (trm1 != null) {
            term_id1 = trm1.getTrmcod();
            term_id1_name = trm1.getNam();
        }
        String term_id2 = "";
        String term_id2_name = "";
        //Trm trm2 = actGetTermid(engcat, trmTyp2);
        Trm trm2 = actGetTermid(engcat);
        if (trm2 != null) {
            term_id2 = trm2.getTrmcod();
            term_id2_name = trm2.getNam();
        }
        // 5.05传票打印类型不再需要
        //GLE\\ACTTRNCOD = Mid( $prttyp1, 2, 1 )
        //select case cbt
        //  case "LIA", "DFP", "SAU", "AVL", "INT"              # 或有资产负债，只要有账号就出账
        // 信用证减额修改特殊处理：在修改即远期的情况下不出账
        /**
         $MaxAmt1 = GetContentNumeric( "\\\\LITAMEP\\\\ENGAMT" )
         $Ignore = ErrorCode
         $MaxAmt2 = GetContentNumeric( "\\\\LIDGRP\\\\CBS\\\\MAX2\\\\AMT" )
         $Ignore = ErrorCode
         $OldAmt = GetContentNumeric( "\\\\OLDLIDGRP\\\\CBS\\\\MAX2\\\\AMT" )
         $Ignore = ErrorCode
         if GetFramename == "LITAME" and $MaxAmt1 + $MaxAmt2 - $OldAmt < 0 then
         else**/
        String bkset = "1";
        //---EAST7759---
        //----LWQ0509不按照分录对应及借贷关系取，交易中统一取值----
       /* String oppacc;
        Argument<String> oppaccBox = new Argument<String>();
        String oppnam;
        Argument<String> oppnamBox = new Argument<String>();
        String oppbnk;
        Argument<String> oppbnkBox = new Argument<String>();
        ctx.absGet(Trnmod.class).east7759(oppaccBox, oppnamBox, oppbnkBox);

        oppacc = oppaccBox.value;
        oppnam = oppnamBox.value;
        oppbnk = oppbnkBox.value;*/

        if (MdaUtils.compareTo(amt, 0) != 0 && !MdaUtils.isEmpty(engact)) {
            gle.setDbtcdt(dt);
            gle.setTxt3(typ + " Booking");
            gle.setAct(engact);
            gle.setPeeact(engcat);           // for accounting code
            //-----------------------------------------<<
            gle.setTrmtyp(term_id1);
            gle.setTrmtypName(term_id1_name);
            /**
             if GLE\\TRMTYP == "2346" or GLE\\TRMTYP == "2685" or GLE\\TRMTYP == "2747" then
             **/
            if (MdaUtils.compareTo(gle.getTrmtyp(), "2346") == 0 || MdaUtils.compareTo(gle.getTrmtyp(), "2685") == 0) {
                gle.setNewactcod("9007");
            }
            //----------------------------------------->>
            if(term_id1!=null && !"".equals(term_id1)){
                if (MdaUtils.compareTo(dt, "D") == 0) {
                    gle.setPrn(MdaUtils.toString(Strings.parseInt(Strings.mid(term_id1, 2, 3)) * 2, -4));
                } else {
                    gle.setPrn(MdaUtils.toString(Strings.parseInt(Strings.mid(term_id2, 2, 3)) * 2 + 1, -4));
                }
            }
            //---east7759---
            gle.setEastoppacc("");
            //---所有分录按借贷关系出，除了收付款取国外对方账号，多条的时候取金额最大的190612---
            gle.setEastoppacc(engcat);
            gle.setEastoppnam("");
            gle.setEastoppnam("");
            gle.setEastoppbnk("");
            gle.setEastoppbnk("");
            gleStoreEntry(glemod, gle);
        }
        if (!MdaUtils.isEmpty(engcat) && MdaUtils.compareTo(amt, 0) != 0) {
            gle.setDbtcdt(cr);
            gle.setTxt3(typ + " Counter Booking");
            gle.setAct(engcat);
            gle.setPeeact("");          // for accounting code
            //-----------------------------------------<<
            gle.setTrmtyp(term_id2);
            gle.setTrmtypName(term_id2_name);
            /**
             if GLE\\TRMTYP == "2346" or GLE\\TRMTYP == "2685" or GLE\\TRMTYP == "2747" then
             **/
            if (MdaUtils.compareTo(gle.getTrmtyp(), "2346") == 0 || MdaUtils.compareTo(gle.getTrmtyp(), "2685") == 0) {
                gle.setNewactcod("9007");
            }
            //----------------------------------------->>
            if(term_id1!=null && !"".equals(term_id1)){
                if (MdaUtils.compareTo(cr, "C") == 0) {
                    gle.setPrn(MdaUtils.toString(Strings.parseInt(Strings.mid(term_id1, 2, 3)) * 2 + 1, -4));
                } else {
                    gle.setPrn(MdaUtils.toString(Strings.parseInt(Strings.mid(term_id2, 2, 3)) * 2, -4));
                }
            }
            //---east7759---
            gle.setEastoppacc("");
            //---所有分录按借贷关系出，除了收付款取国外对方账号，多条的时候取金额最大的19061
            gle.setEastoppacc(engact);
            gle.setEastoppnam("");
            gle.setEastoppnam("");
            gle.setEastoppbnk("");
            gle.setEastoppbnk("");
            gleStoreEntry(glemod, gle);
        }
        //end select
        return glemod;
    }

    /**
     * source:glemod.0014.script
     */
    public void gleDefEntryFieldsCeb(GlemodVo glemod, GleVo gle, int idx) {
        // 本函数用于生成结算GLE初始值
        // 从5.01移植
        //----------------------------------------------------
        gle.setActtrncod(Strings.mid(codetableService.getTblLabel(gle.getTrmtyp(), "TRMTYP"), 2, 1));
        if (Strings.pos(SettleContext.getTransName(), "MCT") > 0) {
            String subref = glemod.getRec().getSubref();
            if (StringUtils.isEmpty(subref)) {
                subref = "NONREF";
            }
            gle.setTxt1(subref);
        } else {
            String ownref = glemod.getRec().getOwnref();
            if (StringUtils.isEmpty(ownref)) {
                ownref = "NONREF";
            }
            gle.setTxt1(ownref);
        }
        SetgllVo setgllVo = glemod.getSetglg().getSetgll().get(idx);
        gle.setTxt2(setgllVo.getTxt2());
        if (MdaUtils.compareTo(gle.getRat(), 0) != 0) { // 牌价不为0，即外汇买卖
            // 结售汇的交易号应该现算
            //  GLE\\DBTDFT = DbtCdt
            /**
             if \\SETMOD\\SETGLG\\SETGLL( idx )\\CUR <> \\SETMOD\\SETGLG\\SETGLL( idx )\\ACCCUR then
             GLE\\TXT2 = GLE\\TXT2 + 'LG000037' + Str( \\SETMOD\\SETGLG\\SETGLL( idx )\\RAT )
             endif
             **/
            if (MdaUtils.isEmpty(setgllVo.getTrdout())) {
                gle.setTrdtyp(setgllVo.getTrdint());
            } else {
                gle.setTrdtyp(setgllVo.getTrdout());
            }
            //---结售汇改造  ----------------------------
            if (!MdaUtils.isEmpty(setgllVo.getTrnman())) {
                gle.setTrnman(setgllVo.getTrnman());
            }
            //-------------------xxf---------------------
            //---------------一日多价改造  ----------------
            gle.setMidrat(setgllVo.getMidrat());
            gle.setXrttim(setgllVo.getXrttim());
            //-------------------xxf---------------------
            //新一代处理<<<<<<<<<<<<<<<<<<<<<<<<<
            //------------by zh <<<外汇买卖类型结汇
            /**
             if not IsEmpty( \\SETMOD\\SETGLG\\SETGLL( idx )\\trdint ) then
             GLE\\WHMTYP = "3"
             else
             if not IsEmpty( \\SETMOD\\SETGLG\\SETGLL( idx )\\trdout ) then
             GLE\\WHMTYP = "5"
             else
             GLE\\WHMTYP = ""
             endif
             endif
             **/
            if (!MdaUtils.isEmpty(setgllVo.getTrdint())) {
                if (MdaUtils.compareTo(gle.getTrnman(), "01") == 0) {
                    gle.setWhmtyp("2");
                } else {
                    gle.setWhmtyp("3");
                }
            } else {
                if (!MdaUtils.isEmpty(setgllVo.getTrdout())) {
                    if (MdaUtils.compareTo(gle.getTrnman(), "01") == 0) {
                        gle.setWhmtyp("4");
                    } else {
                        gle.setWhmtyp("5");
                    }
                } else {
                    gle.setWhmtyp("");
                }
            }
        }
        //--GLE中增加保存客户号的信息--------
        if (!MdaUtils.isEmpty(setgllVo.getSetgrp().getAct().getPtyextkey())) {
            gle.setCliextkey(setgllVo.getSetgrp().getAct().getPtyextkey());
        } else {
            if (Strings.pos(setgllVo.getSetgrp().getRol().getPtytyp(), "C") > 0) {
                gle.setCliextkey(setgllVo.getSetgrp().getRol().getPtyextkey());
                //-----GLE中除了可以使用手工录入的客户编号-------
            }
        }
        //if IsEmpty( GLE\\CLIEXTKEY ) then
        if (MdaUtils.isEmpty(gle.getCliextkey()) || MdaUtils.compareTo(SettleContext.getUserSession().getAtp().getBus(), "CP") == 0) {
            gle.setCliextkey(getCliextkey(glemod));
        }
        //--ZMQZMQ---
        String zmqact = NULLSTR;
        int err = 0;
        if (MdaUtils.compareTo(Strings.mid(gle.getAct(), 1, 2), "FT") == 0 || MdaUtils.compareTo(Strings.mid(gle.getAct(), 1, 2), "EF") == 0 || MdaUtils.compareTo(Strings.mid(gle.getAct(), 1, 3), "ZMQ") == 0) {
            List<Act> actList = actMapper.getActListByExtkey(gle.getAct());
            if (actList != null && actList.size() > 0) {
                zmqact = actList.get(0).getZmqacc();
            }
            gle.setTxt2(gle.getTxt2() + " " + zmqact);
            gle.setTrntyp(setgllVo.getTrntyp());
            gle.setOppacc(setgllVo.getOppacc());
            gle.setOppnam(setgllVo.getOppnam());
            gle.setOppbnk(setgllVo.getOppbnk());
            gle.setDiscod(setgllVo.getDiscod());
            gle.setCtycod(setgllVo.getCtycod());
        }
        //---east7759---
        gle.setEastoppacc(setgllVo.getEastoppacc());
        gle.setEastoppnam(setgllVo.getEastoppnam());
        gle.setEastoppbnk(setgllVo.getEastoppbnk());
        gle.setEastinf(setgllVo.getEastinf());
        /**
         //---将摘要中的回车替换成"#"
         GLE\\TXT2 = ReplaceCRtoChar( GLE\\TXT2, "#" )
         **/
        //---将摘要中的回车替换成"" 移除回车
        gle.setTxt2(Utils.replaceCRtoChar(gle.getTxt2(), ""));
        if (MdaUtils.isEmpty(gle.getValdat())) {
            gle.setValdat(Dates.today());
        }
        // 从5.01移植 end
        /**
         //----------------------------------------------------
         GLE\\ACTTRNCOD = Mid( term_id, 8, 1 )
         GLE\\TRMTYP = Mid( term_id, 1, 5 )
         //----------------------------------------------------
         \\SYSMOD.Getxxdfields ( "BCH", "INR", \\SETMOD\\SETGLG\\SETGLL( idx )\\BRANCH, "Y", GLE\\BRANCHINR )
         GLE\\TXT1 = GetReferenceOfRol( "OWN" )
         GLE\\TXT2 = \\SETMOD\\SETGLG\\SETGLL( idx )\\txt2
         if who == "SUMTAB" then // 外汇买卖
         // 结售汇的交易号应该现算
         GLE\\DBTDFT = DbtCdt
         if \\SETMOD\\SETGLG\\SETGLL( idx )\\CUR <> \\SETMOD\\SETGLG\\SETGLL( idx )\\ACCCUR then
         GLE\\TXT2 = GLE\\TXT2 + 'LG000046' + Str( \\SETMOD\\SETGLG\\SETGLL( idx )\\RAT )
         endif
         if IsEmpty( \\SETMOD\\SETGLG\\SETGLL( idx )\\trdout ) then
         GLE\\TRDTYP = \\SETMOD\\SETGLG\\SETGLL( idx )\\trdint
         else
         GLE\\TRDTYP = \\SETMOD\\SETGLG\\SETGLL( idx )\\trdout
         endif
         //---结售汇改造  ----------------------------
         if not IsEmpty( \\SETMOD\\SETGLG\\SETGLL( idx )\\trnman ) then
         GLE\\TRNMAN = \\SETMOD\\SETGLG\\SETGLL( idx )\\trnman
         endif
         //-------------------xxf---------------------
         //---------------一日多价改造  ----------------
         GLE\\MIDRAT = \\SETMOD\\SETGLG\\SETGLL( idx )\\mcbrmbrat
         GLE\\XRTTIM = \\SETMOD\\SETGLG\\SETGLL( idx )\\xrttim
         //-------------------xxf---------------------
         //新一代处理<<<<<<<<<<<<<<<<<<<<<<<<<
         //------------by zh <<<外汇买卖类型结汇
         if not IsEmpty( \\SETMOD\\SETGLG\\SETGLL( idx )\\trdint ) then
         GLE\\WHMTYP = "3"
         else
         if not IsEmpty( \\SETMOD\\SETGLG\\SETGLL( idx )\\trdout ) then
         GLE\\WHMTYP = "5"
         else
         GLE\\WHMTYP = ""
         endif
         endif
         //------------by zh <<<外汇买卖类型售汇
         //新一代处理>>>>>>>>>>>>>>>>>>>>>>>>>>
         endif
         //---将摘要中的回车替换成"#"
         GLE\\TXT2 = ReplaceCRtoChar( GLE\\TXT2 + 'LG000047' + \\SETMOD\\SETGLG\\SETGLL( idx )\\txt2, "#" )
         GLE\\ACT = act
         GLE\\DBTCDT = DbtCdt
         GLE\\CUR = cur
         GLE\\AMT = Abs( amt )
         GLE\\VALDAT = Toda**/

    }

    /**
     * source:glemod.0015.script
     */
    @Override
    public String getAvailAcc(String trnTyp, String cur, String ptyInr, BigDecimal amt) {
        log.debug("获取账号信息Trntyp:{},Cur:{},PtyInr:{},Amt:{}", trnTyp, cur, ptyInr, amt);
        String accout = "";
        if (!StringUtils.isEmpty(trnTyp)) {
            StopWatch stopWatch = new StopWatch("获取账号性能分析");
            stopWatch.start("获取账号");
            accout = getActBlk(trnTyp, cur, ptyInr, amt);
            stopWatch.stop();
            log.info(stopWatch.prettyPrint());
        }
        return accout;
        /*//取得上下文
        IContext ctx = MdaEnv.getContext();
        ctx.setErrorCode(NO_ERROR);
        String actVal = "";
        if (!MdaUtils.isEmpty(trnTyp)) {
            actVal = getActBlk(trnTyp, cur, ptyInr, callmod, amt);
            //  if IsEmpty( $ActVal ) then
            //    $ActVal = ACTGetComBlk( TrnTyp, TrnTyp, Cur, Callmod )
            //  endif
        }
        return actVal;*/

    }

    private List<Act> getActs(String trnTyp, String cur, String ptyInr, BigDecimal amt) {

        String whereSql = actgetsql(ptyInr, trnTyp, cur);
        if (StringUtils.isEmpty(whereSql)) {
            return Lists.newArrayList();
        }
        StringBuffer sqlBuf = new StringBuffer(whereSql);
        sqlBuf.append(amt.compareTo(new BigDecimal("0")) < 0 ? " AND DIRFLG <> 'D'" : " AND DIRFLG <> 'C'")
                .append(" AND DELFLG = ' ' ");

        String sql = "select EXTKEY from ACT "
                + Utils.sdbEtyGenSql("ACT", sqlBuf.toString())
                + " ORDER BY PRI DESC, INR DESC";
        Map<String, Object> dyncMap = new ImmutableMap.Builder<String, Object>().put("sql", sql).build();
        List<Act> actList = actMapper.dyncRead(dyncMap);

        return CollectionUtils.isEmpty(actList) ? Lists.newArrayList() : actList;
    }

    private List<Bch> getBchs2Inr(String sBranch) {

        if (StringUtils.isEmpty(sBranch)) {
            return Lists.newArrayList();
        }
        Bch bch = bchService.getByBranch(sBranch);
        List<Bch> bchList = new ArrayList<>();
        if(bch != null){
            bchList.add(bch);
        }
        return bchList;

    }


    private List<Bch> getBchs2Bchlst(String sBranch) {


        return null;

    }


    /**
     * source:glemod.0016.script
     */
    public String getActBlk(String trnTyp, String cur, String ptyInr, BigDecimal amt) {
        String actVal = "";
        // PAC特殊处理，账号同SPC
        if (MdaUtils.compareTo(trnTyp, "PAC") == 0) {
            trnTyp = "SPC";
        }
        String sql = actgetsql(ptyInr, trnTyp, cur);
        actVal = actGetBlkCeb(sql, amt);
        IStream actStm = new StreamImpl();
        Streams.streamClear(actStm);
        IStream realStm = new StreamImpl();
        Streams.streamClear(realStm);
        String line = NULLSTR;
        String inr = NULLSTR;
        String branch = NULLSTR;
        IStream inrstr = new StreamImpl();
        String bchInr = NULLSTR;
        String bchkinr = NULLSTR;
        int count = 0;
        int posinr = 0;
        Map<String, Object> dyncMap = new HashMap<>();
        if (!MdaUtils.isEmpty(actVal)) {
            Streams.streamSet(actStm, actVal);
            for (int i = 1; i <= Streams.streamCount(actStm); i++) {
                line = Strings.trim(Strings.getLine(actStm, i));
                if (MdaUtils.compareTo(line, "") != 0) {
                    if (MdaUtils.compareTo(Strings.mid(line, 1, 4), "AAAA") == 0) {
                        if (MdaUtils.compareTo(Strings.mid(line, 5, 4), "AAAA") != 0) {
                            line = getAccbch() + Strings.mid(line, 5);
                        } else {
                            line = getAccbch() + Strings.mid(line, 9);
                        }
                    }
                    if (MdaUtils.compareTo(Strings.mid(line, 5, 2), "BB") == 0) {
                        line = Strings.mid(line, 1, 4) + Strings.mid(codetableService.getTblLabel(cur, "CURKEY"), 1, 2) + Strings.mid(line, 7);
                    }
                    if (MdaUtils.compareTo(Strings.mid(line, 9, 2), "BB") == 0) {
                        line = Strings.mid(line, 1, 8) + Strings.mid(codetableService.getTblLabel(cur, "CURKEY"), 1, 2) + Strings.mid(line, 11);
                    }
                    boolean branchUpdated = false;
                    switch (Strings.len(line)) {
                        case 20:
                            branch = Strings.mid(line, 4, 4);
                            branchUpdated = true;
                            break;
                        case 17:
                            //--ZMQZMQ---
                            if (MdaUtils.compareTo(Strings.mid(line, 1, 2), "FT") == 0 || MdaUtils.compareTo(Strings.mid(line, 1, 2), "EF") == 0) {
                                branch = Strings.mid(line, 8, 4);
                            } else {
                                branch = Strings.mid(line, 1, 4);
                            }
                            branchUpdated = true;
                            break;
                        case 21:
                            // $Branch = Mid( $line, 1, 8 )
                            //$Sql = "SELECT INR FROM BCH WHERE BRANCH = 'RG000050
                            //萧山模式的账户老机构和新机构都要查出来
                            branch = Strings.mid(line, 3, 4);
                            branchUpdated = true;
                            break;
                    }
                    if (branchUpdated) {
                        Streams.streamClear(inrstr);
                        Bch accbch = bchService.getByBranch(branch);
                        if (accbch != null) {
                            Streams.streamInsert(inrstr, 0, accbch.getInr());
                        }
                    }
                    // if not IsEmpty( $Inr ) then
                    if (!MdaUtils.isEmpty(inrstr)) {
                        Bch accbch = SettleContext.getUserSession().getBch();
                        if (null == accbch) {
                            accbch = SettleContext.getUserSession().getWrkbch();
                        }
                        if (accbch != null) {
                            List<Bch> bchList = null;
                            if ("X".equalsIgnoreCase(accbch.getZmqflg())) {
                                bchList = getZmqBchList(accbch.getBranch());
                            } else {
                                bchList = bchService.listAllChildSubBchByAccBch(accbch.getBranch());
                            }
                            if(bchList == null){
                                bchList = new ArrayList<>();
                            }
                            //支行经办，非客户账需要增加记账机构
                            Bch orgBch = SettleContext.getUserSession().getOrgBch();
                            if (orgBch != null && "2".equalsIgnoreCase(orgBch.getLev()) && "7".equalsIgnoreCase(orgBch.getBchtyp()) && !trnTyp.startsWith("LO")) {
                                String accBranch = accbch.getBranch();
                                if (!bchList.stream().allMatch(bch -> bch.getBranch().equals(accBranch))) {
                                    bchList.add(accbch);
                                }
                            }
                            //bchList.add(accbch);
                            //杭州萧山模式 bch会有2条7740的记录
                            count = Streams.streamCount(inrstr);
                            for (int idx = 1; idx <= count; idx++) {
                                inr = Strings.getLine(inrstr, idx);
                                for (Bch bch : bchList) {
                                    if (bch.getInr().equals(inr)) {
                                        Streams.streamInsert(realStm, 0, line);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        //= StreamGet( $ActStm )
        return MdaUtils.toString(realStm);
        /**
         if IsEmpty( $ActVal ) and not IsEmpty( $TrnTyp ) then
         $Sql = "WHERE CUR = '" + Cur + "' AND HOLPTYINR = '88888888' AND TRMTYP = '" + $TrnTyp + "' AND TYP = '" + getdsp( $Dsp ) + "'"
         $ActVal = \\TRNMOD.ACTGetBlk ( $Sql, PtyInr, Amt )
         if not IsEmpty( $ActVal ) then
         $ActVal = GetBranch( getProcessBCHKEY ) + $ActVal
         endif
         endif
         = $ActVa**/

    }

    /**
     * source:glemod.0017.script
     */
    public String actgetsql(String ptyinr, String dsp, String cur) {
        String res = "WHERE EXTKEY <> ''";
        if (StringUtils.isNotEmpty(cur)) {
            res += " AND (CUR = '" + cur + "' or CUR = ' ')";
        }
        //String res = "WHERE (CUR = '" + cur + "' or CUR = ' ')";
        // DSP有两种情况，一个是确定的单个账号，比如AS-LIS，另一个是账号列表，比如LOD
        String dsptmp = "";
        String frame = SettleContext.getTransName();
        if (MdaUtils.compareTo(dsp, "TPD") == 0 && MdaUtils.compareTo(frame, "MCTFEE") == 0) {
            res = res + " AND TRMTYP LIKE '" + Utils.getdsp(dsp) + "%' AND TRMTYP<>'TP-T16'";
        } else {
            if (MdaUtils.compareTo(dsp, "TPC") == 0 && MdaUtils.compareTo(frame, "MCTFEE") == 0) {
                res = res + " AND TRMTYP LIKE '" + Utils.getdsp(dsp) + "%' AND TRMTYP<>'TP-T15'";
            } else {
                if (MdaUtils.compareTo(Strings.mid(dsp, 1, 2), "SP") == 0) {
                    if (MdaUtils.compareTo(Utils.getLCType(frame), "D") == 0) {
                        dsp = "SP-DFT";
                    } else {
                        FeeSet feeSet = setfegService.getFeeSet();
                        if (feeSet != null && "D".equals(feeSet.getDflg())) {
                            dsp = "SP-DFT";
                        } else {
                            dsp = "SP-FFT";
                        }
                    }
                }
                if (Strings.pos(dsp, "-") > 0) {
                    res = res + " AND TRMTYP = '" + dsp + "'";
                } else {
                    /**
                     $res = $res + " AND TRMTYP LIKE '" + getdsp( DSP ) + "%'"
                     **/
                    /**
                     $res = $res + " AND TRMTYP LIKE '" + getdsp( DSP ) + "%' and TRMTYP<>'TP-T16' and TRMTYP<>'TP-T15' "
                     **/
                    dsptmp = "";
                    switch (dsp) {
                        case "LFD":
                        case "LFC":
                            String actpro = setfegService.getFeeSet().getActpro();
                            if (StringUtils.isEmpty(actpro)) {
                                throw new CommonServiceException("请确定外管局账户性质");
                            }
                            //!外币贷款专户也是LO类型的2088科目的企业活期户，只是其外管局报送属性是2303:外币贷款专户
                            res = res + " AND TRMTYP LIKE 'LO%' AND ACTPRO = '" + actpro + "' AND TRMTYP<>'TP-T16' AND TRMTYP<>'TP-T15' ";
                            break;
                        default:
                            res = res + " AND TRMTYP LIKE '" + Utils.getdsp(dsp) + "%' and TRMTYP<>'TP-T16' AND TRMTYP<>'TP-T15' ";
                    }
                }
            }
        }
        if (!MdaUtils.isEmpty(ptyinr)) {
            if (MdaUtils.compareTo(getzmqflg(), "X") == 0) {
                if (MdaUtils.compareTo(frame, "MCTFEE") != 0 && (MdaUtils.compareTo(Strings.mid(dsp, 1, 2), "LO") == 0 || MdaUtils.compareTo(Strings.mid(dsp, 1, 2), "LF") == 0 || MdaUtils.compareTo(Strings.mid(dsp, 1, 2), "CC") == 0)) {
                    res = res + " AND ( (HOLPTYINR = '" + ptyinr + "' AND ACCTYP='C' AND (EXTKEY LIKE 'FT%' OR EXTKEY LIKE 'ZMQ%' OR EXTKEY LIKE 'EF%') ) OR (ACCTYP='O' AND HOLPTYINR = '" + this.getHeqinr() + "' )  ) ";
                } else {
                    res = res + " AND ( (HOLPTYINR = '" + ptyinr + "' AND ACCTYP='C') OR (ACCTYP='O' AND HOLPTYINR = '" + this.getHeqinr() + "' ) ) ";
                }
            } else {
                switch (dsp) {
                    case "LFD":
                    case "LFC":
                        //!外币贷款专户也是LO类型的2088科目的企业活期户，只是其外管局报送属性是2303:外币贷款专户
                        res = res + " AND  (HOLPTYINR = '" + ptyinr + "' AND ACCTYP='C' AND (EXTKEY NOT LIKE 'FT%' AND EXTKEY NOT LIKE 'ZMQ%' AND EXTKEY NOT LIKE 'EF%') ) ";
                        break;
                    default:
                        res = res + " AND ( (HOLPTYINR = '" + ptyinr + "' AND ACCTYP='C' AND (EXTKEY NOT LIKE 'FT%' AND EXTKEY NOT LIKE 'ZMQ%' AND EXTKEY NOT LIKE 'EF%') ) OR (ACCTYP='O' AND HOLPTYINR = '" + this.getHeqinr() + "' )  ) ";
                }
                /**
                 $res = $res + " AND ( (HOLPTYINR = '" + PTYINR + "' AND ACCTYP='C' AND (EXTKEY NOT LIKE 'FT%' AND EXTKEY NOT LIKE 'ZMQ%') ) OR (ACCTYP='O' AND HOLPTYINR = '" + HEQINR + "' )  ) "
                 **/
            }
            /**
             if getzmqflg == "X" and GetFramename <> "MCTFEE" and ( Mid( DSP, 1, 2 ) == "LO" or Mid( DSP, 1, 2 ) == "CC" ) then
             $res = $res + " AND ( (HOLPTYINR = '" + PTYINR + "' AND ACCTYP='C' AND (EXTKEY LIKE 'FT%' OR EXTKEY LIKE 'ZMQ%') ) OR (ACCTYP='O' AND HOLPTYINR = '" + HEQINR + "' )  ) "
             else
             //--90325需求非自贸区分行不能选择ZMQ或者FT账号-----
             //--去掉此段代码mctfee交易中不管自贸区还是非自贸区分行都可带入和客户相关的所有账号--
             if getzmqflg == "" and GetFramename == "MCTFEE" and ( Mid( DSP, 1, 2 ) == "LO" or Mid( DSP, 1, 2 ) == "CC" ) then
             $res = $res + " AND ( (HOLPTYINR = '" + PTYINR + "' AND ACCTYP='C' AND (EXTKEY NOT LIKE 'FT%' AND EXTKEY NOT LIKE 'ZMQ%') ) OR (ACCTYP='O' AND HOLPTYINR = '" + HEQINR + "' )  ) "
             else
             $res = $res + " AND ( (HOLPTYINR = '" + PTYINR + "' AND ACCTYP='C') OR (ACCTYP='O' AND HOLPTYINR = '" + HEQINR + "' ) ) "
             endif
             endif
             **/
        } else {
            res = res + " AND ( ACCTYP='O' AND HOLPTYINR = '" + this.getHeqinr() + "' ) ";
        }
        return res;

    }

    public void buildTrmtyp(GleVo gleVo) {
        Trm trm = actGetTermid(gleVo.getAct());
        if (trm != null) {
            gleVo.setTrmtyp(trm.getTrmcod());
            gleVo.setTrmtypName(trm.getNam());
        }
    }
    /**
     * source:glemod.0019.script
     */
    public Trm actGetTermid(String act) {
        if (!MdaUtils.isEmpty(act)) {
            Trm trm  = trmMapper.getTrmByAct(act, null);
            if (trm == null) {
                String termid = "";
                if (Strings.len(act) == 17) {
                    termid = Strings.mid(act, 7, 4);
                }
                if (Strings.len(act) == 21) {
                    termid = Strings.mid(act, 12, 4);
                }
                trm = new Trm();
                trm.setTrmcod(termid);
                trm = trmMapper.selectByTrmcod(trm);
            }
            return trm;
        }
        return null;
    }

    public Trm actGetTermid(String act, String trmtyp) {
        if (!MdaUtils.isEmpty(act)) {
            Trm trm = trmMapper.seletByTrmtyp(trmtyp);
            if (trm == null) {
                trm  = trmMapper.getTrmByAct(act, trmtyp);
                if (trm == null) {
                    String termid = "";
                    if (Strings.len(act) == 17) {
                        termid = Strings.mid(act, 7, 4);
                    }
                    if (Strings.len(act) == 21) {
                        termid = Strings.mid(act, 12, 4);
                    }
                    trm = new Trm();
                    trm.setTrmcod(termid);
                    trm = trmMapper.selectByTrmcod(trm);
                }
            }
            return trm;
        }
        return null;
    }

    /**
     * source:glemod.0021.script
     */
    public void east7759act(GlemodVo glemod, Argument<String> oppactd, Argument<String> oppactC, Argument<String> jact, Argument<String> dact) {
        //---east7759---
        //---收费贷方取借方费用的账号------
        List<SetgllVo> setglls = glemod.getSetglg().getSetgll();
        String voppactd = "";
        String oPPACtJ = "";
        String vjact = "";
        String vdact = "";
        if (setglls.size() > 0) {
            List<SetgllVo> tmpSetglls = setglls.stream().filter(setgllVo -> MdaUtils.compareTo(Strings.mid(Strings.getLine(setgllVo.getAmtidsstm(), 1), 1, 7), "*SETFEG") == 0).sorted(Comparator.comparing(SetgllVo::getXrfamt).reversed()).collect(Collectors.toList());
            if (tmpSetglls.size() > 0) {
                voppactd = tmpSetglls.get(0).getAct();
            }
        }
        //--借方收费合计取收入科目金额最大账号------
        List<SetfelVo> setfels = glemod.getSetfeg().getSetfel();
        if (setfels.size() > 0) {

            //SetfelVo setfel = setfels.stream().filter(setfelVo -> MdaUtils.compareTo(setfelVo.getDsp(), "X") == 0).sorted(Comparator.comparing(SetfelVo::getXrfamt).reversed()).collect(Collectors.toList()).get(0);
            setfels = setfels.stream().filter(setfelVo -> MdaUtils.compareTo(setfelVo.getDsp(), "X") == 0).sorted(Comparator.comparing(SetfelVo::getXrfamt).reversed()).collect(Collectors.toList());
            String feeAcc = "";
            if (!CollectionUtils.isEmpty(setfels)) {
                SetfelVo setfel = setfels.get(0);
                String cur_id = Strings.mid(codetableService.getTblLabel(setfel.getCur(), "CURKEY"), 1, 2);
                if (!MdaUtils.isEmpty(Strings.trim(cur_id))) {
                    if (MdaUtils.compareTo(Strings.mid(setfel.getFeeacc(), 1, 2), "??") == 0) {
                        feeAcc = cur_id + Strings.mid(setfel.getFeeacc(), 3, 11);
                    }
                }
            }
            if (!MdaUtils.isEmpty(feeAcc)) {
                feeAcc = getAccbch() + feeAcc;
            }
            oPPACtJ = feeAcc;
        }
        //--记账分录借方与贷方最大金额的账号--
        if (setglls.size() > 0) {
            List<SetgllVo> tmpSetglls = setglls.stream().filter(setgllVo -> MdaUtils.compareTo(Strings.mid(Strings.getLine(setgllVo.getAmtidsstm(), 1), 1, 7), "*SETFEG") != 0).filter(setgllVo -> MdaUtils.compareTo(setgllVo.getDebcdtflg(), "D") == 0).sorted(Comparator.comparing(SetgllVo::getXrfamt).reversed()).collect(Collectors.toList());
            if (tmpSetglls.size() > 0) {
                vjact = tmpSetglls.get(0).getAct();
            }
            tmpSetglls = setglls.stream().filter(setgllVo -> MdaUtils.compareTo(Strings.mid(Strings.getLine(setgllVo.getAmtidsstm(), 1), 1, 7), "*SETFEG") != 0).filter(setgllVo -> MdaUtils.compareTo(setgllVo.getDebcdtflg(), "C") == 0).sorted(Comparator.comparing(SetgllVo::getXrfamt).reversed()).collect(Collectors.toList());
            if (tmpSetglls.size() > 0) {
                vdact = tmpSetglls.get(0).getAct();
            }
        }
        jact.value = vjact;
        dact.value = vdact;
        oppactd.value = voppactd;
        oppactC.value = oPPACtJ;
    }

    /**
     * source:glemod.0022.script
     */
    public boolean isSHOUFUKUANset(GlemodVo glemod) {
        //! determine, whether this PTSPTA is filled with an appropriate address
        //! i.e. whether PTSPTA\\ROL is set
        //进口信用证付款、进口代收付款
        //外币、全额同业代付不出202报文、7759对方信息按照只取账号赋值
        //人民币，全额同业代付、代理行模式、不出202报文、7759对方信息按照其他交易赋值；
        //收付汇交易：
        //
        //（1）表外：对方账号互取
        //           对方户名：空
        //           对方行号：空
        //（2）结售汇：对方账号2143科目互取
        //             对方户名：空
        //             对方行号：空
        // (3)其余分录账号均取对方账号、对方户名（黑名单校验名称）、对方行号，按报文类型不同加以区分。
        //
        //其他交易（只取账号）：
        //（1）表外：对方账号互取
        //（2）结售汇：对方账号2143科目互取
        //（3）收费：借方对方账号：取贷方最大金额账号
        //           贷方对方账号：取借方最大金额账号
        //除表外、结售汇、收费以外的分录，根据最大金额判断：借方的对方账号取贷方的最大金额账号，
        //    贷方的对方账号取借方的最大金额账号。
        BizInfoVo rec = glemod.getRec();
        String cmtflg = Utils.getFieldValue(rec, "cmtflg", "");
        String dfflag = Utils.getFieldValue(rec, "dfflag");
        BigDecimal oriamt = Utils.getFieldValue(rec, "oriamt");
        String oricur = Utils.getFieldValue(rec, "oricur");
        BigDecimal amt = glemod.getCbsMap().get("MAX").getAmt();
        String frm = SettleContext.getDirectTransName();
        if (MdaUtils.compareTo(frm, "CPTATO") == 0 || MdaUtils.compareTo(frm, "CPTOPN") == 0 || MdaUtils.compareTo(frm, "CPTATI") == 0 || MdaUtils.compareTo(frm, "CPTECO") == 0 || MdaUtils.compareTo(frm, "CPTADV") == 0 || MdaUtils.compareTo(frm, "CPTECI") == 0 || MdaUtils.compareTo(Strings.mid(frm, 4, 3), "PSE") == 0 || MdaUtils.compareTo(Strings.mid(frm, 4, 3), "SET") == 0 || MdaUtils.compareTo(frm, "DFTMSG") == 0) {
            switch (frm) {
                case "BPTSET":
                case "TRTSET":
                    return false;
                case "GITSET":
                case "GITPSE":
                case "NITSET":
                case "NITPSE":
                    String fingua = Utils.getFieldValue(glemod.getRec(), "fingua");
                    if (MdaUtils.compareTo(fingua, "N") == 0) {
                        return false;
                    } else {
                        return true;
                    }
                    // break;
                case "BRTSET":
                case "BCTSET":
                    if ((MdaUtils.compareTo(dfflag, "X") == 0 && MdaUtils.compareTo(oriamt, amt) == 0 && MdaUtils.compareTo(oricur, "CNY") != 0) || (MdaUtils.compareTo(dfflag, "X") == 0 && MdaUtils.compareTo(oriamt, amt) == 0 && MdaUtils.compareTo(oricur, "CNY") == 0 && MdaUtils.compareTo(cmtflg, "C") == 0)) {
                        return false;
                    } else {
                        if (MdaUtils.compareTo(cmtflg, "O") == 0) {
                            return false;
                        } else {
                            return true;
                        }
                    }
                    // break;
                default:
                    return true;
            }
        } else {
            return false;
        }
    }

    /**
     * source:glemod.0023.script
     */
    @Override
    public String actGetTRMCOD(String act) {
        if (StringUtils.isEmpty(act)) {
            return "";
        }
        return actMapper.getTxmcodByExtkey(act);
    }

    /**
     * source:glemod.0002.script
     */
    public void gleCommit(GlemodVo glemod) {
        // store GLE entries. If that is not necessary in installation, remove # in following line
        if (glemod.getGlenmb() > 0) {
            for (int i = 0; i < glemod.getGlenmb(); i++) {
                GleVo gle = glemod.getGles().get(i);
                if (MdaUtils.compareTo(gle.getTrninr(), transactionHelpService.getTrninr()) != 0) {
                    SettleExceptionUtils.sysDump("Error in save of GLE entries - wrong identnumber: " + gle.getTrninr());
                }
                gle.setInr(counterService.dbCounterFormat("GLE"));
                gleMapper.insert(DtoMapper.INSTANCE.transfer(gle));
                glemod.getGlesrm().insertLine(0, "GLE" + MdaUtils.toString(i + 1, -3));//GLE001
                glemod.getGlesrm().insertLine(0, Utils.toJson(gle));
            }
            //存盘操作
            //Streams.streamSave(glemod.getGlesrm(), Platform.getFullName("DATA", "GLEDATA\\" + glemod.getTrninr() + ".LST"));
            Utils.streamSave(glemod.getGlesrm(), environment.getProperty("envConfig.rootPath") + File.separator + "DATA" + File.separator + "GLEDATA" + File.separator + transactionHelpService.getTrninr() + ".LST");
        }
    }

    /**
     * source:glemod.0020.script
     */
    public static BigDecimal getTaxAmt(BigDecimal setamt, BigDecimal rate) {
        //!计算销项税税款金额
        //
        //公式为：费用总额/(1+税率)*税率
        //数据库存储的税率为整数，因此在计算时需要将税率/100 取得正确税率
        BigDecimal gleamt = new BigDecimal("0");
        gleamt = Decimals.mul(Decimals.div(setamt, (Decimals.add(1, Decimals.div(rate, 100)))), (Decimals.div(rate, 100)));
        return Numerics.round(gleamt, 2);

    }

    public String getzmqflg() {
        if (SettleContext.getUserSession().getBch() != null) {
            return SettleContext.getUserSession().getBch().getZmqflg();
        } else {
            return "";
        }
    }

    public String getAccbch() {
        Bch accbch = SettleContext.getUserSession().getBch();
        if (accbch != null) {
            return accbch.getBranch();
        }
        return "";
    }

    public String actGetBlkCeb(String sqlblk, BigDecimal amt) {
        if (StringUtils.isEmpty(sqlblk)) {
            return "";
        }
        String res = "";
        if (MdaUtils.compareTo(amt, 0) < 0) {
            sqlblk += " AND DIRFLG <> 'D'";
        } else {
            sqlblk += " AND DIRFLG <> 'C'";
        }
        sqlblk += " AND DELFLG <> 'X' ";
        sqlblk = Utils.sdbEtyGenSql("ACT", sqlblk);
        sqlblk += " ORDER BY PRI DESC, INR DESC";
        String sql = "select EXTKEY from ACT " + sqlblk;
        Map<String, Object> dyncMap = new HashMap<>();
        dyncMap.put("sql", sql);
        List<Act> actList = actMapper.dyncRead(dyncMap);
        if (actList != null && actList.size() > 0) {
            for (int i = 0; i < actList.size(); i++) {
                if (i == 0) {
                    res = actList.get(i).getExtkey();
                } else {
                    res += CR + actList.get(i).getExtkey();
                }
            }
        }
        return res;
        /*// default account if possible without user interaction.
        // 修改查数据库记录的账号优先选择顺序
        IStream sqlStm = new StreamImpl();
        Streams.streamSet(sqlStm,sqlblk);
        String res = "";
        String pfx = "";
        int stmCnt = Streams.streamCount(sqlStm);
        String mySql = NULLSTR;
        IStream accLst = new StreamImpl();
        int stmCntAcc = 0;
        String extkey = NULLSTR;
        int ignore = 0;
        for(int  linIdx = 1;linIdx <= stmCnt;linIdx++)
        {
            mySql = Strings.getLine(sqlStm,linIdx);
            if( MdaUtils.isEmpty(mySql) )
            {
                continue ; // #######TODO 改写 LABEL与GOTO  ####   goto nextsql
            }
            if( MdaUtils.compareTo(amt,0)<0 )
            {
                mySql = mySql + " AND DIRFLG <> 'D'";
            }
            else
            {
                mySql = mySql + " AND DIRFLG <> 'C'";
            }
            mySql = mySql + " AND DELFLG = ' ' ";
            mySql = Platform.sdbEtyGenSql(this.getWrkact(),mySql);
            // 就这儿不同
            mySql = mySql + " ORDER BY PRI DESC, INR DESC";
            // check if already in cache
            Streams.streamClear(accLst);
            Caches.cacheRead(accLst,"ACTGETBLK",mySql);
            if( ctx.getErrorCode() != tdCacheNotFound )
            {
                stmCntAcc = Streams.streamCount(accLst);
                if( stmCntAcc > 0 )
                {
                    for(int  idx = 1;idx <= stmCntAcc;idx++)
                    {
                        extkey = Strings.getLine(accLst,idx);
                        if( Strings.searchBlock(res,extkey) == 0 )
                        {
                            res = res + pfx + extkey;
                            pfx = CR;
                        }
                    }
                }
                continue ; // #######TODO 改写 LABEL与GOTO  ####   goto nextsql
            }
            // if not in cache retrieve from DB
            Streams.streamClear(accLst);
            ctx.getDaoSession().dbSelectCursor(this.getWrkact(),mySql);
            while( ctx.getErrorCode() == 0 )
            {
                ctx.getDaoSession().dbFetch(this.getWrkact());
                if( ctx.getErrorCode() == 0 )
                {
                    if( Strings.searchBlock(res,this.getWrkact().getExtkey()) == 0 )
                    {
                        res = res + pfx + this.getWrkact().getExtkey();
                        this.getWrkact().setNam( Dynamic.actGetActHint( this.getWrkact()));
                        Caches.cacheWrite(this.getWrkact().getNam(),"ACTHINT",this.getWrkact().getExtkey());
                        ignore = ctx.getErrorCode();
                        pfx = CR;
                    }
                    Streams.streamInsert(accLst,0,this.getWrkact().getExtkey());
                }
            }
            if( ctx.getErrorCode() != tdOdbcNotFound )
            {
                ctx.reraise();
            }
            ctx.getDaoSession().dbCloseCursor();
            Caches.cacheWrite(accLst,"ACTGETBLK",mySql);
            // #######TODO 改写 LABEL与GOTO   ####    label nextsql
        }
        return  res;*/
    }

    public String getCliextkey(GlemodVo glemod) {
        String bus = SettleContext.getUserSession().getAtp().getBus();
        String role = "";
        switch (bus) {
            case "LI":
            case "BR":
                role = "APL";
                break;
            case "NI":
            case "GI":
                String hndtyp = Utils.getFieldValue(glemod.getRec(), "hndtyp");
                if (StringUtils.isNotEmpty(hndtyp)
                        && hndtyp.startsWith("O")) {
                    role = "APL";
                } else {
                    role = "BEN";
                }
                break;
            case "LE":
            case "BE":
            case "LT":
                role = "BEN";
                break;
            case "DI":
            case "BD":
                role = "APL";
                break;
            case "DE":
            case "BF":
            case "DT":
                role = "BEN";
                break;
            case "BC":
                role = "DRE";
                break;
            case "BO":
                role = "DRR";
                break;
            case "BP":
                if(SettleContext.getTransName().startsWith("BP")) {
                    role = "FIA";
                }
                break;
            case "TR":
                role = "FIP";
                break;
            case "DF":
                if(SettleContext.getTransName().startsWith("DF")) {
                    role = "APL";
                } else if (SettleContext.getTransName().startsWith("BC")) {
                    role = "DRE";
                } else {
                    role = "APL";
                }
                break;
            case "CP":
                String paytyp = Utils.getFieldValue(glemod.getRec(), "paytyp");
                if (StringUtils.isNotEmpty(paytyp)
                        && paytyp.startsWith("O")) {
                    role = "ORC";
                } else {
                    role = "PYE";
                }
                break;
            case "MC":
                role = "ADE";
                break;
            case "CC":
                role = "PRE";
                break;
            case "JS":
            case "WI":
                role = "APL";
                break;
            default:
                // hoping that in future product modules the client will always be CLI
                role = "CLI";
        }

        String cliextkey = "";
        PtsptaVo ptspta = ptsptaToolComponent.getPtsFromListByRol(glemod.getPtsList(), role);
        if (ptspta != null) {
            Pty pty = ptyCacheService.getPtyById(ptspta.getPtyinr());
            if(pty != null){
                cliextkey = pty.getExtkey();
            }
        }
        return cliextkey;
    }

    /**
     * 账号机构隔离
     * @param actList
     * @return
     */
    public List<String> filterAct(List<String> actList){
        Bch accbch = SettleContext.getUserSession().getBch();
        List<Bch> bchList = null;
        if (accbch != null) {
            if ("X".equalsIgnoreCase(accbch.getZmqflg())) {
                bchList = getZmqBchList(accbch.getBranch());
            } else {
                bchList = bchService.listAllChildSubBchByAccBch(accbch.getBranch());
            }
        }
        if (bchList == null) {
            log.info("机构列表为空，不进行账号机构隔离操作");
            return actList;
        }
        List<String> acts = new ArrayList<>();
        List<Bch> finalBchList = bchList;
        actList.forEach(act -> {
            int length = act.length();
            String branch = "";
            if (length == 20) {
                branch = Strings.mid(act, 4, 4);
            } else if (length == 17) {
                if (MdaUtils.compareTo(Strings.mid(act, 1, 2), "FT") == 0 || MdaUtils.compareTo(Strings.mid(act, 1, 2), "EF") == 0) {
                    branch = Strings.mid(act, 8, 4);
                } else {
                    branch = Strings.mid(act, 1, 4);
                }
            } else if (length == 21) {
                branch = Strings.mid(act, 3, 4);
            }
            if (StringUtils.isNotEmpty(branch)) {
                String finalBranch = branch;
                if (finalBchList.stream().anyMatch(item->item.getBranch().equalsIgnoreCase(finalBranch))) {
                    acts.add(act);
                }
            } else {
                log.info("账号{}不符合规范", act);
            }
        });
        return acts;
    }

    @Override
    public HashMap<String, String> getBranchinrAndBchkeyinr(String act) {
        HashMap<String, String> result = new HashMap<>();
        if (StringUtils.isEmpty(act)) {
            log.warn("账号为空不符合规范");
            result.put("branchinr","");
            result.put("bchkeyinr","");
        } else {
            int length = act.length();
            String branch = "";
            if (length == 20) {
                branch = Strings.mid(act, 4, 4);
            } else if (length == 17) {
                if (MdaUtils.compareTo(Strings.mid(act, 1, 2), "FT") == 0 || MdaUtils.compareTo(Strings.mid(act, 1, 2), "EF") == 0) {
                    branch = Strings.mid(act, 8, 4);
                } else {
                    branch = Strings.mid(act, 1, 4);
                }
            } else if (length == 21) {
                branch = Strings.mid(act, 3, 4);
            }
            if (StringUtils.isEmpty(branch)) {
                log.warn("从账号:{}中获取到的机构为空",act);
                result.put("branchinr","");
                result.put("bchkeyinr","");
            } else {
                String actUpper = act.toUpperCase();
                Bch bch = bchService.getByBranch(branch);
                if (bch == null) {
                    log.warn("从账号:{}中获取到的机构:{}为空",act,branch);
                    result.put("branchinr","");
                    result.put("bchkeyinr","");
                    return result;
                }
                result.put("branchinr",bch.getInr());
                if (actUpper.startsWith("FT") || actUpper.startsWith("EF") || actUpper.startsWith("ZMQ")) {
                    if ("X".equalsIgnoreCase(bch.getZmqflg())) {
                        log.info("从账号:{}中获取到的自贸区机构:{}",act,bch.getBranch());
                        result.put("bchkeyinr",bch.getInr());
                    } else {
                        Bch directParentBch = bchService.getDirectParentBch(branch);
                        List<Bch> bches = bchService.listAccBch(directParentBch.getBranch());
                        Bch accBch = bches.stream().filter(item -> "X".equalsIgnoreCase(item.getZmqflg())).findFirst().orElse(new Bch());
                        log.info("根据账号:{}中的机构:{}计算获取到的自贸区机构:{}",act,bch.getBranch(),accBch.getBranch());
                        result.put("bchkeyinr",accBch.getInr());
                    }
                } else {
                    if ("7".equalsIgnoreCase(bch.getBchtyp())) {
                        log.info("根据账号:{}中的机构:{}计算获取到的经办机构:{}",act,bch.getBranch(),bch.getBranch());
                        result.put("bchkeyinr",bch.getInr());
                    } else {
                        Bch directParentBch = bchService.getDirectParentBch(branch);
                        Bch accBch = bchService.getDirectAccBch(directParentBch.getBranch());
                        log.info("根据账号:{}中的机构:{}计算获取到的记账机构:{}",act,bch.getBranch(),accBch.getBranch());
                        result.put("bchkeyinr",bch.getInr());
                    }
                }
            }
        }
        return result;
    }

    /**
     * 自贸区机构号
     * @param zmqBch
     * @return
     */
    private List<Bch> getZmqBchList(String zmqBch) {
        Bch directParentBch = bchService.getDirectParentBch(zmqBch);
        if (directParentBch == null) {
            throw new CommonServiceException("获取不到自贸区"+zmqBch+"记账机构");
        }
        String branch = directParentBch.getBranch();
        return bchService.listAllChildAndItselfBch(branch);
    }
}
