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

import com.alibaba.fastjson2.JSON;
import com.brilliance.mda.runtime.mda.config.IniConfig;
import com.brilliance.mda.runtime.mda.util.Decimals;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Strings;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.util.ObjectUtils;
import com.brilliance.isc.bo.*;
import com.brilliance.isc.common.api.bch.service.BchService;
import com.brilliance.isc.common.cache.atpbch.AtpBchCacheService;
import com.brilliance.isc.common.cache.pta.PtaCacheService;
import com.brilliance.isc.common.cache.pty.PtyCacheService;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.component.PtsptaToolComponent;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.context.SpringEnvContext;
import com.brilliance.isc.common.counter.service.CounterService;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.common.liaall.vo.LiaallVo;
import com.brilliance.isc.common.liaallg.vo.LiaallgVo;
import com.brilliance.isc.common.liaccv.vo.LiaccvVo;
import com.brilliance.isc.common.liaccv.vo.LiaccvgVo;
import com.brilliance.isc.common.limmod.service.LimCecmService;
import com.brilliance.isc.common.limmod.service.LimOptionService;
import com.brilliance.isc.common.limmod.service.LimmodService;
import com.brilliance.isc.common.limmod.vo.LimOccVo;
import com.brilliance.isc.common.limmod.vo.LimgrdVo;
import com.brilliance.isc.common.limmod.vo.LimmodVo;
import com.brilliance.isc.common.limmod.vo.LmegrdVo;
import com.brilliance.isc.common.register.lim.ILimRegister;
import com.brilliance.isc.common.transaction.help.TransactionHelpService;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.common.vo.BizAmdInfoVo;
import com.brilliance.isc.common.vo.PtsptaVo;
import com.brilliance.isc.common.wfmmod.service.WfmmodService;
import com.brilliance.isc.constant.LimCons;
import com.brilliance.isc.mda.dao.*;
import com.brilliance.isc.utils.BigDecimalUtils;
import com.brilliance.isc.utils.DateUtils;
import com.brilliance.isc.utils.StringUtils;
import com.brilliance.isc.vo.component.bptbck.BptbckVo;
import com.brilliance.isc.vo.domlc.DedBizInfoVo;
import com.brilliance.isc.vo.domlc.DidBizAmdInfoVo;
import com.brilliance.isc.vo.domlc.DidBizInfoVo;
import com.brilliance.isc.vo.lc.BedBizInfoVo;
import com.brilliance.isc.vo.lc.LedBizInfoVo;
import com.brilliance.isc.vo.lc.LidBizAmdInfoVo;
import com.brilliance.isc.vo.lc.LidBizInfoVo;
import com.brilliance.isc.vo.manager.StbVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

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

@Service
public class LimmodServiceImpl implements LimmodService {
    @Autowired
    private PtyCacheService ptyCacheService;
    @Autowired
    private PtyMapper ptyMapper;
    @Autowired
    private CodetableService codetableService;
    @Autowired
    private TransactionHelpService transactionHelpService;
    @Autowired
    private WfmmodService wfmmodService;
    @Autowired
    private CounterService counterService;
    @Autowired
    private StbMapper stbMapper;
    @Autowired
    private LimMapper limMapper;

    @Autowired
    private LmeMapper lmeMapper;
    @Autowired
    private LimtrnMapper limtrnMapper;
    @Resource(name = "limocc")
    private LimOptionService limOccservice;
    @Autowired
    private PtsptaToolComponent ptsptaToolComponent;
    @Autowired
    private TrnMapper trnMapper;
    @Resource
    private PtaCacheService ptaCacheService;
    @Resource
    private PtsMapper ptsMapper;


    @Autowired
    private AtpBchCacheService atpBchCacheService;

    @Resource
    private BchService bchService;

    public static final Logger logger = LoggerFactory.getLogger(LimmodServiceImpl.class);

    /**
     * 初始化注册对象
     *
     * @return
     */
    public ILimRegister limRegister() {
        //按照交易码，获取注册Spring的交易Bean
        String transName = SettleContext.getTransName();
        try {
            ILimRegister limRegister = SpringEnvContext.getBean(atpBchCacheService.getSdTransNameForRegister().toLowerCase() + "." + "LimRegister");
            return limRegister;
        } catch (NoSuchBeanDefinitionException e) {
            throw new CommonServiceException("没有找到交易注册类");
        }
    }

    /**
     * 提取额度用到的基本业务信息
     *
     * @param limmodVo
     */
    public void LimRegParstm(LimmodVo limmodVo) {
        logger.info("######开始进行额度提取业务信息");
        limmodVo.getErrorVo().clear();
        Liminit(limmodVo);
        limRegister().initBussinessLim(limmodVo);
        limRegister().limObtainWrkPts(limmodVo);

        if (StringUtils.isEmpty(limmodVo.getLimpts().getWrk().getExtkey())) {
            limmodVo.getLimpts().setErrorflg("E");
        }
        if ("B".equals(limmodVo.getLimpts().getWrk().getPtytyp())) {

            Pty typty = ptyCacheService.getPtyById(limmodVo.getLimpts().getWrk().getPtyinr());
            if (!ObjectUtils.isEmpty(typty)) {
                if (StringUtils.isEmpty(typty.getEcifno())) {
                    if (StringUtils.isEmpty(typty.getHeqinr())) {
                        throw new CommonServiceException("请先维护该占额同业客户的ECIF客户号");
                    }
                    Pty pntbank = ptyCacheService.getPtyById(typty.getHeqinr());
//                            listrst = ptyMapper.selectEcifnoByExtkey("EVERCNBJXXX");
                    limmodVo.setLimptspta(ptsptaToolComponent.getPtsptaFromPtyINR(pntbank.getInr()));
                    limmodVo.setEcifno(pntbank.getEcifno());
                    limmodVo.getLimptspta().setNam(pntbank.getEcifnam1());
                } else {
                    limmodVo.setEcifno(typty.getEcifno());
                    limmodVo.setLimptspta(limmodVo.getLimpts().getWrk());
                }
            }
            if (StringUtils.isEmpty(limmodVo.getEcifno())) {
                throw new CommonServiceException("请先维护该占额同业客户的ECIF客户号");
            }
        }
        if (!StringUtils.isEmpty(limmodVo.getOwnref())) {
            List<Lim> lims = limMapper.selectLimOderByOwnrefDesc(limmodVo.getOwnref());


            if (!StringUtils.isEmpty(limmodVo.getOwnref()) && StringUtils.isEmpty(limmodVo.getLimpts().getNonrevflg1())) {

                if (lims.size() > 0) {
                    if ("Y".equals(limmodVo.getLimpts().getDothflg())) {
                        limmodVo.getLimpts().setNonrevflg1("1");
                    } else {
                        limmodVo.getLimpts().setNonrevflg1(lims.get(0).getLimtype());
                    }
                } else {
                    if (SettleContext.getTransName().contains("CAN")) {
                        limmodVo.getLimpts().setNonrevflg1("1");
                    }
                }
            }
            //初始化前手交易金额
            BigDecimal oldccvamt = BigDecimal.ZERO;
            BigDecimal oldcomamt = BigDecimal.ZERO;
            if (lims.size() > 0) {
                oldcomamt = lims.get(0).getComamt();
                oldccvamt = lims.get(0).getCcvamt();
            } else {
                //兼容15年以前迁移历史业务数据没有额度的情况
                if (SettleContext.getTransName().contains("CAN")) {
                    for (LiaallgVo liaallgVo : limmodVo.getLiaall().getLiaallg()) {
                        oldcomamt = oldcomamt.add(liaallgVo.getOldamt());
                    }
                    for (LiaccvgVo liaccvgVo : limmodVo.getLiaccvVo().getLiaccvg()) {
                        oldccvamt = oldccvamt.add(liaccvgVo.getOldamt());
                    }
                }
            }
            limmodVo.setOldcomamt(oldcomamt);
            limmodVo.setOldccvamt(oldccvamt);
            /**
             * 设置前手转授权信息
             */
            if (!isLimStart(SettleContext.getTransName(), SettleContext.getUserSession().getBch().getBranch())) {
                //兼容没有前手额度数据的后手交易
                if (CollectionUtils.isEmpty(lims)) {
                    limmodVo.getLimpts().setNonrevflg1("1");
                    if ("Y".equals(limmodVo.getLimpts().getDothflg())) {
                        limmodVo.getLimpts().setNonrevflg2("2");
                    }
                }

                if (!CollectionUtils.isEmpty(lims)) {
                    Trn trn = new Trn();
                    trn.setInr(lims.get(0).getTrninr());
                    trn = trnMapper.selectByPrimaryKey(trn);

                    if (!ObjectUtils.isEmpty(trn) && !"R,A,D".contains(trn.getRelflg())) {
                        Map rulemap = limmodVo.getErrorVo().getRulemap();
                        limmodVo.getLimpts().setErrorflg("E");
                        rulemap.put("limmod.ownref", "请先复核该笔业务前手中涉及额度的交易");
                    }
                }
                String zsqkhbh = "";
                String sfzsqyw = "";
                String sffgsyw = "";
                String zgskhbh = "";
                if (lims.size() > 0) {
                    sfzsqyw = lims.get(0).getSfzsqyw();
                    zsqkhbh = lims.get(0).getMgskhbh();
                    limmodVo.getLimpts().setZsqkhbh(zsqkhbh);
                    limmodVo.getLimpts().setSfzsqyw(sfzsqyw);

                    sffgsyw = lims.get(0).getSffgsyw();
                    zgskhbh = lims.get(0).getZgskhbh();
                    limmodVo.getLimpts().setSffgsyw(sffgsyw);
                    limmodVo.getLimpts().setZgskhbh(zgskhbh);
                    /**
                     * 设置对公客户转授权信息
                     */
                    if ("Y".equals(limmodVo.getLimpts().getDothflg())) {
                        limmodVo.getLimpts().setOthfflg(lims.get(0).getOthfflg());
                        limmodVo.getLimpts().setOthmflg(lims.get(0).getOthmflg());
                        limmodVo.getLimpts().setOthmgs(lims.get(0).getOthmgs());
                        limmodVo.getLimpts().setOthzgs(lims.get(0).getOthzgs());
                    }
                    /**
                     * 设置前手柜员和机构信息
                     */
                    limmodVo.setUser(lims.get(0).getIniusr());
                    limmodVo.setBranch(lims.get(0).getBranch());
                }
            }
        }
        limRegister().afterInit(limmodVo);
        logger.info(String.format("######结束额度提取业务信息： Limpts %s", JSON.toJSON(limmodVo)));
    }

    public void checkData(LimmodVo limmodVo) {
        logger.info("######开始进行额度简单校验");
        Map rulemap = limmodVo.getErrorVo().getRulemap();
        if (StringUtils.isEmpty(limmodVo.getOwnref())) {
            limmodVo.getLimpts().setErrorflg("E");
            rulemap.put("limmod.ownref", "业务编号不可为空");
        }
        if ("1".equals(limmodVo.getLimQueryVo().getType()) && "1".equals(limmodVo.getLimpts().getQueryFlg())) {
            if (StringUtils.isEmpty(limmodVo.getLimpts().getNonrevflg1())) {
                limmodVo.getLimpts().setErrorflg("E");
//                rulemap.put("limmod.limpts.nonrevflg1","请选择统一授信额度类型");
            }
        }
        logger.info("######结束额度简单校验");
    }

    /**
     * 额度基本数据初始化 LIAALL LimRegParstm
     */
    public void Liminit(LimmodVo limmodVo) {
//
// 从业务中获取额度类型和币种金额
//
// 从表外中取还是从业务信息中取？
//
//
//
//#给LIMMOD下的字段赋值：
//#       EXTID/MODPTH/CUR/AMT/CCVAMT
//#
        LiaallVo liaallVo = limmodVo.getLiaall();
        LiaccvVo liaccvVo = limmodVo.getLiaccvVo();
        if (liaccvVo == null) {
            liaccvVo = new LiaccvVo();
        }
        //设置保证进金额参考liaall LimRegParstm
        limmodVo.setCcvamt(liaccvVo.getTotcovamt());
        //设置业务编号
        limmodVo.setOwnref(limmodVo.getRec().getOwnref());
        //设置 客户类型 1对公 2同业，双占的时候才设置
//        limmodVo.setType(limmodVo.getLimQueryVo().getType());
        if (!StringUtils.isEmpty(limmodVo.getLimpts().getWrk().getExtkey())) {
            Pts pts = limmodVo.getLimpts().getWrk().getPts();
            String idtype = getidtypeinr(pts.getPtyinr(), "C");
            limmodVo.setIdtyp(idtype);
        }
        limmodVo.setAccbranch(SettleContext.getUserSession().getBch() == null ? "3500" : SettleContext.getUserSession().getBch().getBranch());

    }

    /**
     * 保存额度表
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void limSav3000(LimmodVo limmodVo) {
        logger.info("########开始额度lim,lme,limtrn存表");
        logger.info(String.format("占用标志:%s", limmodVo.getLmaflg()));
        logger.info(String.format("释放标志:%s", limmodVo.getLmoflg()));
        logger.info(String.format("双占标志:%s", limmodVo.getLmcflg()));

        String cl43flg = Utils.cacheGetIniStr("intace.ini", "LMA", "open0");
        if ("Y".equals(cl43flg)) {
            if (limRegister().needRecalcLimits(limmodVo)) {
                //特殊交易处理
                setLmflg(limmodVo);
                //1.存LME，LIM
                if (limRegister().isLimitLma(limmodVo) || limRegister().isLimitLmo(limmodVo) || isLimitlmc(limmodVo)) {
                    limLmeSave2(limmodVo);
                }
                //limLmeSave老TD已经不用了，此处迟早注释删掉-就别看这个方法了弃用了
                if (limRegister().isLimitLma_1(limmodVo)) {
                    limLmeSave(limmodVo);
                }
                //存limtrn
                if (isLimitlmc(limmodVo) || isLimitSdh(limmodVo) || limRegister().isLimitLma(limmodVo) || limRegister().isLimitLmt(limmodVo) || limRegister().isLimitLmo(limmodVo)) {

                    limTrnSave(limmodVo);
                }
                //存wfe
                if (isLimitlmc(limmodVo)) {
                    wfmmodService.wfeAdd("LMC", "LMC", DateUtils.getNowDate(), BigDecimal.valueOf(21));
                } else {
                    if (limRegister().isLimitLmo(limmodVo)) {
                        limRegister().wfeAddClmRelease(limmodVo);
                    } else {
                        if (limRegister().isLimitLma(limmodVo)) {
                            limOccservice.limDataCal(limmodVo);
                            wfmmodService.wfeAdd("LMA", "LMA", DateUtils.getNowDate(), BigDecimal.valueOf(21));
                        }
                    }
                }
                if (limRegister().isLimitLmt(limmodVo) || limRegister().isLimitLma(limmodVo) || isLimitlmc(limmodVo) || limRegister().isLimitLmo(limmodVo) || isLimitSdh(limmodVo)) {
                    limRegister().wfeAddClmShare(limmodVo);
                }

            }
        }
        logger.info("########结束额度lim,lme,limtrn存表");
    }

    /**
     * 交易特殊处理
     */
    private void setLmflg(LimmodVo limmodVo) {
        String transName = SettleContext.getDirectTransName();
        BigDecimal ameamt = Decimals.ZERO_SCALE2;
        if (MdaUtils.compareTo(transName, "DITAME") == 0) {
            DidBizAmdInfoVo didBizAmdInfoVo = (DidBizAmdInfoVo) limmodVo.getAmdRec();
            ameamt = didBizAmdInfoVo.getAmeamt();
            if (MdaUtils.compareTo(ameamt, 0) < 0)
                limmodVo.setLmaflg(NULLSTR);
        }

        if (MdaUtils.compareTo(transName, "BDTSET") == 0 || MdaUtils.compareTo(transName, "BRTSET") == 0) {
            if (MdaUtils.compareTo(limmodVo.getRec().getTrtcreVo().getCrefinflg(), "X") == 0) {
                if (MdaUtils.compareTo(limmodVo.getLmoflg(), "Y") == 0) {
                    limmodVo.setLmoflg("N");
                    limmodVo.setLmcflg("Y");
                }
            }
        }
    }

    /**
     * 组装占用接口数据
     *
     * @param limmodVo
     */
    public void genCL43Data(LimmodVo limmodVo) {
        logger.info("##########开始额度占用数据组装");

        limmodVo.getLimOccVo().Qtls = limmodVo.getLim().getQtls();

//--此栏位是额度主体的客户号
//--代开信用证申请人是额度主体
//--202202分离式保函额度主体是被保证人此处应该是给错号
//--衍生品额度主体是申请人
        limmodVo.getLimOccVo().ECIFNO = limmodVo.getLim().getPtyextkey();
        limmodVo.getLimOccVo().KEHUMC = limmodVo.getLim().getPtynam();
        limmodVo.getLimOccVo().GUIYID = limmodVo.getLim().getIniusr();

        limmodVo.getLimOccVo().JIBAJQ = limmodVo.getLim().getBranch();
        limmodVo.getLimOccVo().YWPZHO = limmodVo.getLim().getLimtyp();

        limmodVo.getLimOccVo().YEWUCJ = limmodVo.getLim().getYwcj();
        limmodVo.getLimOccVo().GJJYBM = limmodVo.getLim().getInifrm();
        limmodVo.getLimOccVo().YEWUNO = limmodVo.getLim().getOwnref();
        limmodVo.getLimOccVo().GLYWBH = limmodVo.getLim().getPntref();

        limmodVo.getLimOccVo().BIZHON = limmodVo.getLim().getCurnum();
        limmodVo.getLimOccVo().YEWUJE = BigDecimalUtils.BigD2stringHalfUP(limmodVo.getLim().getAmt(), 2);
        limmodVo.getLimOccVo().YEWUYE = BigDecimalUtils.BigD2stringHalfUP(limmodVo.getLim().getComamt(), 2);
        limmodVo.getLimOccVo().ROCZHI = BigDecimalUtils.BigD2stringHalfUP(limmodVo.getLim().getDifamt(), 2);
        limmodVo.getLimOccVo().BZJYUE = BigDecimalUtils.BigD2stringHalfUP(limmodVo.getLim().getCcvamt(), 2);
        limmodVo.getLimOccVo().QISHIR = limmodVo.getLim().getCredat();
        limmodVo.getLimOccVo().DAOQIR = limmodVo.getLim().getEnddat();
        limmodVo.getLimOccVo().EDLEIX = limmodVo.getLimpts().getNonrevflg1();
        limmodVo.getLimOccVo().EDBHAO = limmodVo.getLim().getLimref();

        String dgzsqflg = "";
        String dgzsqkhh = "";
        String dgsfzgs = "";
        String dgzgskhh = "";
        String tyzsqflg = "";
        String tyzsqkhh = "";
        String tysfzgs = "";
        String trzgskhh = "";
        if (!StringUtils.isEmpty(limmodVo.getLimpts().getOth().getExtkey())) {
            dgzsqflg = limmodVo.getLimpts().getOthmflg();
            dgzsqkhh = limmodVo.getLimpts().getOthmgs();
            dgsfzgs = limmodVo.getLimpts().getOthfflg();
            dgzgskhh = limmodVo.getLimpts().getOthzgs();
            tyzsqflg = limmodVo.getLimpts().getSfzsqyw();
            tyzsqkhh = limmodVo.getLimpts().getZsqkhbh();
            tysfzgs = limmodVo.getLimpts().getSffgsyw();
            trzgskhh = limmodVo.getLimpts().getZgskhbh();
        } else {
            if ("1".equals(limmodVo.getIdtyp())) {
                dgzsqflg = limmodVo.getLimpts().getSfzsqyw();
                dgzsqkhh = limmodVo.getLimpts().getZsqkhbh();
                dgsfzgs = limmodVo.getLimpts().getSffgsyw();
                dgzgskhh = limmodVo.getLimpts().getZgskhbh();

            } else {
                tyzsqflg = limmodVo.getLimpts().getSfzsqyw();
                tyzsqkhh = limmodVo.getLimpts().getZsqkhbh();
                tysfzgs = limmodVo.getLimpts().getSffgsyw();
                trzgskhh = limmodVo.getLimpts().getZgskhbh();
            }
        }
        String zsQopen = IniConfig.getIniConfig("intace.ini", "CLM51", "open0");
        if ("Y".equals(zsQopen)) {
            limmodVo.getLimOccVo().SFZSQYW = dgzsqflg;
            limmodVo.getLimOccVo().ZSQKHBH = dgzsqkhh;
            limmodVo.getLimOccVo().SFFGSYW = dgsfzgs;
            limmodVo.getLimOccVo().ZGSKHBH = dgzgskhh;
        }
        limmodVo.getLmes().forEach(lme -> {

            LimOccVo.ItemFCL431 fcl431 = new LimOccVo.ItemFCL431();

            fcl431.EDMXBH = lme.getDginfref();
            fcl431.EDCPDM = lme.getDglimcod();
            fcl431.ZHYJIY = "";
            fcl431.HUIFXH = lme.getDgshxh() + "";
            limmodVo.getLimOccVo().FCL431.add(fcl431);
        });

        String finalTyzsqkhh = tyzsqkhh;
        String finalTyzsqflg = tyzsqflg;
        String finalTysfzgs = tysfzgs;
        String finalTrzgskhh = trzgskhh;
        limmodVo.getWrklmes().forEach(lme -> {
            LimOccVo.ItemFCL432 fcl432 = new LimOccVo.ItemFCL432();
            fcl432.TYKHBH = lme.getTyptyextkey();
            fcl432.TYSWIT = lme.getTyswiftno();
            fcl432.TYKHMC = lme.getTyptynam();
            fcl432.TYEDBH = lme.getTylimref();
            fcl432.TYMXBH = lme.getTyinfref();
            fcl432.EDCPDM = lme.getTylimcod();
            fcl432.TYZYJY = "";
            if ("Y".equals(zsQopen)) {
                fcl432.SFZSQYW = finalTyzsqflg;
                fcl432.ZSQKHBH = finalTyzsqkhh;
                fcl432.SFFGSYW = finalTysfzgs;
                fcl432.ZGSKHBH = finalTrzgskhh;
            }
            limmodVo.getLimOccVo().FCL432.add(fcl432);

        });


        limRegister().limOccRegister(limmodVo);
        logger.info(String.format("##########结束额度占用数据组装:LiaccvVo %s", JSON.toJSON(limmodVo.getLiaccvVo())));
        logger.info(String.format("##########结束额度占用数据组装:LimOccVo %s", JSON.toJSON(limmodVo.getLimOccVo())));
    }

    @Override
    public boolean isOrderBranch() {
        if (SettleContext.getUserSession().getBch() == null) {
            return false;
        }

        if ("6".equals(SettleContext.getUserSession().getBch().getBchtyp())) {
            return true;
        }
        return false;
    }

    /**
     * 保存limtrn
     *
     * @param limmodVo
     */
    public void limTrnSave(LimmodVo limmodVo) {
        limmodVo.getLimtrn().setObjtyp(limmodVo.getRec().getObjtyp());
        limmodVo.getLimtrn().setObjinr(limmodVo.getRec().getObjinr());
        limmodVo.getLimtrn().setOwnref(limmodVo.getOwnref());
        //设置角色信息
        PtsptaVo rol = getPtsptaFromPtslist(limmodVo.getPtsList(), limmodVo.getWrkrol());

        limmodVo.getLimtrn().setPtyextkey(rol.getExtkey());
        if (!StringUtils.isEmpty(limmodVo.getLimtrn().getPtyextkey())) {
            limmodVo.getLimtrn().setPtyextkey(limmodVo.getLimtrn().getPtyextkey().split("-")[0]);
        }
        limmodVo.getLimtrn().setPtynam(rol.getNam());
        limmodVo.getLimtrn().setLimtyp(codetableService.getTblLabel(limmodVo.getExtid(), "LMSCOD"));

        limmodVo.getLimtrn().setIniusr(StringUtils.isEmpty(limmodVo.getUser()) ? SettleContext.getUserSession().getUsr().getExtkey() : limmodVo.getUser());
        //1-保证2-抵押3-质押
        limmodVo.getLimtrn().setGuatyp("1");
        limmodVo.getLimtrn().setBranch(StringUtils.isEmpty(limmodVo.getBranch()) ? SettleContext.getUserSession().getBch().getBranch() : limmodVo.getBranch());
        limmodVo.getLimtrn().setValend(DateUtils.parseDateToStr("yyyyMMdd", limmodVo.getEnddat()));
        limmodVo.getLimtrn().setComamt(limmodVo.getComamt());

        limmodVo.getLimtrn().setObjamt(BigDecimal.ZERO);


        /**
         * 交易下的savelimtrn
         */
        limRegister().limTrnSave(limmodVo);

        limmodVo.getLimtrn().setTrninr(limmodVo.getTrninr());
        String inr = limtrnMapper.selectInrByTrnInr(limmodVo.getTrninr());
        if (StringUtils.isEmpty(inr)) {
            limmodVo.getLimtrn().setInr(counterService.dbCounterFormat("LIMTRN"));
            limtrnMapper.insert(limmodVo.getLimtrn());
        }

    }

    /**
     * 保存额度占用信息到表
     */
    public void limLmeSave2(LimmodVo limmodVo) {
//        ---存储占用、释放信息---
//综合授信ptytyp为B占用接口客户信息赋值（B  swift额度占用）
//综合授信ptytyp为C占用接口客户信息赋值（C1、C2）idtype 1对公2同业
//综合授信ptytyp为B 单笔单批ptytyp为C（BC1、BC2）
//综合授信ptytyp为C 单笔单批ptytyp为C（C1C1、C2C1
        limmodVo.getLim().setObjtyp(limmodVo.getRec().getObjtyp());
        limmodVo.getLim().setObjinr(limmodVo.getRec().getObjinr());
        limmodVo.getLim().setOwnref(limmodVo.getOwnref());
//设置角色信息

//        此处不需要这么整了老td只对wrk做了处理oth没做处理
//        PtsptaVo rol = "1".equals(limmodVo.getType()) ? limmodVo.getLimpts().getWrk() : limmodVo.getLimpts().getOth();
        PtsptaVo rol = limmodVo.getLimpts().getWrk();
        limmodVo.getLim().setPtyextkey(rol.getExtkey());
        limmodVo.getLim().setPtyinr(rol.getPtyinr());
        limmodVo.getLim().setPtynam(rol.getNam());
        limmodVo.getLim().setSttflg("");
        if ("1".equals(limmodVo.getLimpts().getQueryFlg())) {
            limmodVo.getLim().setSttflg("1");
        }
//          综合授信客户ptytyp为B时走此处swift号转换为ecifno
        if ("B".equals(limmodVo.getLimpts().getWrk().getPtytyp()) && StringUtils.isEmpty(limmodVo.getLimpts().getOth().getExtkey())) {
            limmodVo.getLim().setPtyextkey(limmodVo.getEcifno());
            limmodVo.getLim().setPtyinr(limmodVo.getLimptspta().getPtyinr());
            limmodVo.getLim().setPtynam(limmodVo.getLimptspta().getNam());
        }
        if (!StringUtils.isEmpty(limmodVo.getLim().getPtyextkey())) {
            limmodVo.getLim().setPtyextkey(limmodVo.getLim().getPtyextkey().split("-")[0]);
        }
        limmodVo.getLim().setIniusr(StringUtils.isEmpty(limmodVo.getUser()) ? SettleContext.getUserSession().getUsr().getExtkey() : limmodVo.getUser());
        limmodVo.getLim().setBranch(StringUtils.isEmpty(limmodVo.getBranch()) ? SettleContext.getUserSession().getBch().getBranch() : limmodVo.getBranch());
        limmodVo.getLim().setLimtyp(codetableService.getTblLabel(limmodVo.getExtid(), "LMSCOD"));

        limmodVo.getLim().setInifrm(SettleContext.getTransName());

        limmodVo.getLim().setCur(limmodVo.getCur());
        limmodVo.getLim().setCurnum(codetableService.getTblLabel(limmodVo.getCur(), "CURKEY"));
        limmodVo.getLim().setAmt(limmodVo.getAmt());
        limmodVo.getLim().setComamt(limmodVo.getComamt());
        limmodVo.getLim().setDifamt(limmodVo.getDifamt());
        limmodVo.getLim().setCcvamt(limmodVo.getCcvamt());
        limmodVo.getLim().setCredat(DateUtils.parseDateToStr("yyyy/MM/dd", limmodVo.getCredat()));
        limmodVo.getLim().setEnddat(DateUtils.parseDateToStr("yyyy/MM/dd", limmodVo.getEnddat()));
        //getlimref
        for (LimgrdVo limgrd : limmodVo.getLimQueryVo().getLimgrdVoList()) {
            if (!StringUtils.isEmpty(limgrd.getFlg())) {
                limmodVo.setLimref1(limgrd.getLimref());
                break;
            }
        }

        for (LmegrdVo lmegrdVo : limmodVo.getLimQueryVo().getLmegrdVos()) {
            if (!StringUtils.isEmpty(lmegrdVo.getFlg())) {
                limmodVo.setLimref2(lmegrdVo.getLimref());
                break;
            }
        }
        if (!ObjectUtils.isEmpty(limmodVo.getLimpts().getOth().getPts()) && !ObjectUtils.isEmpty(limmodVo.getLimpts().getOth().getPts().getExtkey())) {
            if ("2".equals(limmodVo.getIdtyp2())) {

                limmodVo.getLim().setLimtype("2");
                limmodVo.getLim().setLimref(limmodVo.getLimref1());

                if ("B".equals(limmodVo.getLimpts().getWrk().getPtytyp())) {
                    limmodVo.getLim().setLimtype("2");
                    limmodVo.getLim().setLimref(limmodVo.getLimref2());
                }
                if (MdaUtils.compareTo(SettleContext.getTransName(), "LITROG") == 0) {
                    limmodVo.getLim().setLimtype("2");
                    limmodVo.getLim().setLimref(limmodVo.getLimref2());
                }
            } else {
                limmodVo.getLim().setLimtype("2");
                limmodVo.getLim().setLimref(limmodVo.getLimref2());
            }
        } else {
            limmodVo.getLim().setLimref(limmodVo.getLimref1());
            limmodVo.getLim().setLimtype(limmodVo.getLimpts().getNonrevflg1());
        }
        limmodVo.getLim().setSta("W");
        limmodVo.getLim().setNccvamt(BigDecimal.ZERO);

//        if ("6".equals(SettleContext.getUserSession().getBch().getBchtyp())) {
//            if (SettleContext.getTransName().contains("OPN") || SettleContext.getTransName().contains("ODZ")) {
//                if (!StringUtils.isEmpty(limmodVo.getLmoflg())) {
//                    limmodVo.setLmoflg("");
//                }
//            }
//        }

        if (limRegister().isLimitLma(limmodVo)) {
            limmodVo.getLim().setQtls(counterService.dbCounterFormat("CLMLSH", 6));
        }
        String zsqopen = IniConfig.getIniConfig("intace.ini", "CLM51", "open0");
        if ("Y".equals(zsqopen)) {
            limmodVo.getLim().setSfzsqyw(limmodVo.getLimpts().getSfzsqyw());
            limmodVo.getLim().setMgskhbh(limmodVo.getLimpts().getZsqkhbh());
            limmodVo.getLim().setSffgsyw(limmodVo.getLimpts().getSffgsyw());
            limmodVo.getLim().setZgskhbh(limmodVo.getLimpts().getZgskhbh());
            limmodVo.getLim().setOthfflg(limmodVo.getLimpts().getOthfflg());
            limmodVo.getLim().setOthmgs(limmodVo.getLimpts().getOthmgs());
            limmodVo.getLim().setOthmflg(limmodVo.getLimpts().getOthmflg());
            limmodVo.getLim().setOthzgs(limmodVo.getLimpts().getOthzgs());
            limmodVo.getLim().setOthextkey(limmodVo.getLimpts().getOth().getExtkey());
        }


//涉及交易的处理
        limRegister().limLmeSave2(limmodVo);

//--提货注销恢复信用证额度时候特殊处理-----------
        if ("04".equals(limmodVo.getLim().getYwcj()) || "12".equals(limmodVo.getLim().getYwcj())) {

            limmodVo.getLim().setComamt(BigDecimal.ZERO);
            limmodVo.getLim().setCcvamt(BigDecimal.ZERO);
        }

        limmodVo.getLim().setTrninr(limmodVo.getTrninr());
        String inr = limMapper.selectInrByTrnInr(limmodVo.getTrninr());
        if (StringUtils.isEmpty(inr)) {
            inr = counterService.dbCounterFormat("LIM");
            limmodVo.getLim().setInr(inr);
            limMapper.insert(limmodVo.getLim());
        } else {
            limmodVo.getLim().setInr(inr);
            limMapper.updateByPrimaryKey(limmodVo.getLim());
        }
        PtsptaVo wrk = limmodVo.getLimpts().getWrk();
        PtsptaVo oth = limmodVo.getLimpts().getOth();
        int lmecode = 0;
        if (StringUtils.isEmpty(lmeMapper.selectInrByLimInr(limmodVo.getLim().getInr()))) {
            lmecode = 1;
        }

        if (!StringUtils.isEmpty(wrk.getExtkey())) {
            if (!"Y".equals(limmodVo.getLmoflg())) {
                limRegister().limLmeWRK(limmodVo, lmecode);
            }
        }

        if (!StringUtils.isEmpty(oth.getExtkey())) {
            if (!"Y".equals(limmodVo.getLmoflg()) && (lmecode > 0)) {
                limRegister().limLmeOTH(limmodVo);
            }
        }
    }

    /**
     * 单占的lme数据保存
     *
     * @param lmecode
     * @param ecifno1
     */
    public void limLmeWRK(LimmodVo limmodVo, Integer lmecode, String ecifno1, String dkflg, String rzdbflg1, String rzdbflg, String rzdbflg2, String ownref, String fenli) {

        int i = 0;
        limmodVo.getLimQueryVo().getLimgrdVoList().forEach(
                limgrdVo -> {
                    if ("X".equals(limgrdVo.getFlg())) {
                        if ("1".equals(limmodVo.getIdtyp()) ||
                                (StringUtils.isEmpty(dkflg) && "2".equals(limmodVo.getIdtyp())) ||
                                "Y".equals(rzdbflg1) || "Y".equals(rzdbflg) || "Y".equals(rzdbflg2)) {
                            if (lmecode != 0) {
                                Lme lme = new Lme();
                                Lme wklme = new Lme();
                                lme.setLiminr(limmodVo.getLim().getInr());
                                lme.setTrninr(limmodVo.getTrninr());
                                lme.setObjtyp(limmodVo.getLim().getObjtyp());
                                lme.setObjinr(limmodVo.getLim().getObjinr());
                                lme.setDginfref(limgrdVo.getInfref());
                                lme.setDglimcod(limgrdVo.getLimcod());
                                lme.setDglimcod(limgrdVo.getLimcodsave());
                                lme.setDglimamt(BigDecimal.ZERO);
                                lme.setDgshxh(limgrdVo.getShxh());
                                lme.setFxfl(limgrdVo.getFentyp());
                                if ("1".equals(limmodVo.getLimpts().getQueryFlg())) {
                                    lme.setDghfref(ownref);
                                    lme.setDghfcur(limmodVo.getLim().getCurnum());
                                    lme.setDghfamt(BigDecimal.ZERO);
                                    lme.setDghfccvamt(BigDecimal.ZERO);
                                    lme.setDghflimamt(limmodVo.getAmt());
                                }
                                lme.setInr(counterService.dbCounterFormat("LME"));
                                lmeMapper.insert(lme);
                                limmodVo.getLmes().add(lme);

                            }
                        } else {
                            if (lmecode != 0) {
                                Lme wklme = new Lme();
                                wklme.setLiminr(limmodVo.getLim().getInr());
                                wklme.setTrninr(limmodVo.getLim().getTrninr());
                                wklme.setObjtyp(limmodVo.getLim().getObjtyp());
                                wklme.setObjinr(limmodVo.getLim().getObjinr());

                                PtsptaVo wrk = limmodVo.getLimpts().getWrk();
                                String extkey1 = wrk.getPts().getExtkey().split("-")[0];
                                String extkey2 = "";
                                if (!StringUtils.isEmpty(wrk.getExtkey()) && "B".equals(wrk.getPtytyp())) {
                                    extkey2 = ptyMapper.getExtkeyByHeqInr(wrk.getPtyinr());
                                    if (!StringUtils.isEmpty(extkey2)) {
                                        extkey1 = extkey2;
                                    }

                                    if ("2".equals(limmodVo.getIdtyp())) {
                                        wklme.setTyptyextkey(extkey1);
                                        wklme.setTyswiftno("");
                                    } else {
                                        wklme.setTyptyextkey("");
                                        if (!StringUtils.isEmpty(limmodVo.getEcifno())) {
                                            wklme.setTyptyextkey(limmodVo.getEcifno());
                                        }
                                        wklme.setTyswiftno(extkey1);
                                    }
                                    if ("1".equals(limmodVo.getIdtyp()) && !StringUtils.isEmpty(fenli)) {
                                        wklme.setTyptyextkey(extkey1);
                                        wklme.setTyswiftno("");
                                    }
                                    if ("Y".equals(rzdbflg) || "Y".equals(rzdbflg1)) {
                                        wklme.setTyptyextkey(extkey1);
                                        wklme.setTyswiftno("");
                                    }
                                    wklme.setTyptynam("");
                                    wklme.setTylimref(limgrdVo.getLimref());
                                    wklme.setTyinfref(limgrdVo.getInfref());
                                    wklme.setTylimcod(limgrdVo.getLimcod());
                                    wklme.setTylimcod(limgrdVo.getLimcodsave());
                                    wklme.setTylimamt(BigDecimal.ZERO);
                                    wklme.setFxfl(limgrdVo.getFentyp());
                                    if (lmecode != 0) {
                                        wklme.setInr(counterService.dbCounterFormat("LME"));
                                        lmeMapper.insert(wklme);
                                        limmodVo.getWrklmes().add(wklme);
                                    }

                                }
                            }
                        }
                    }

                }
        );


    }

    @Deprecated
    public boolean isLmaStart(String transname) {
        if (isOrderBranch()) {
            return transname.contains(LimCons.SDH_START_TRANS) ? true : false;
        } else {
            return transname.contains(LimCons.START_TRANS) ? true : false;
        }
    }

    @Deprecated
    public boolean isLmaStart(String transname, String sdhflg) {
        if (transname.contains(LimCons.SDH_START_TRANS)) {
            return true;
        }
        if ("X".equals(sdhflg)) {
            return false;
        } else {
            return transname.contains(LimCons.START_TRANS) ? true : false;
        }
    }

    public boolean isLimStart(String transname, String branch) {
        if (branch == null) {
            return false;
        }
        String transcod = transname.substring(3, 6);
        if (StringUtils.stringAppend(LimCons.START_TRANS, ",", LimCons.SDH_START_TRANS).contains(transcod) || "BCTSET".equals(transname) || "BCTSET1".equals(transname)) {
            if (bchService.isOrderBranchByFrm(transname)) {
                return "1".equals(bchService.getStartFlgByBranchInifrm(branch, transname));
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 双占的lme保存
     *
     * @param flg
     * @param ecifno1
     */
    public void limLmeOTH(String flg, String ecifno1) {


    }

    /**
     * 保存额度占用信息到表只用于转授权
     * <p>
     * 此函数已被LIMLMESAVE2取代，现用于收单行起头交易占用额度后，有转授权信息的押汇中心无额度占用处理--
     **/
    public void limLmeSave(LimmodVo limmodVo) {

        limmodVo.getLim().setObjtyp(limmodVo.getRec().getObjtyp());
        limmodVo.getLim().setObjinr(limmodVo.getRec().getObjinr());
//设置角色信息
        PtsptaVo rol = getPtsptaFromPtslist(limmodVo.getPtsList(), limmodVo.getWrkrol());
        limmodVo.getLim().setPtyextkey(rol.getExtkey());
        limmodVo.getLim().setPtynam(rol.getNam());
        //  综合授信客户ptytyp为B时走此处swift号转换为ecifno
        if ("B".equals(limmodVo.getLimpts().getWrk().getPtytyp()) && StringUtils.isEmpty(limmodVo.getLimpts().getOth().getExtkey())) {

            limmodVo.getLim().setPtyextkey(limmodVo.getEcifno());
            limmodVo.getLim().setPtynam(limmodVo.getLimpts().getWrk().getNam());
        }
        if (!StringUtils.isEmpty(limmodVo.getLim().getPtyextkey())) {
            limmodVo.getLim().setPtyextkey(limmodVo.getLim().getPtyextkey().split("-")[0]);
        }
        limmodVo.getLim().setIniusr(StringUtils.isEmpty(limmodVo.getUser()) ? SettleContext.getUserSession().getUsr().getExtkey() : limmodVo.getUser());
        limmodVo.getLim().setBranch(StringUtils.isEmpty(limmodVo.getBranch()) ? SettleContext.getUserSession().getBch().getBranch() : limmodVo.getBranch());
        limmodVo.getLim().setLimtyp(codetableService.getTblLabel(limmodVo.getExtid(), "LMSCOD"));

        limmodVo.getLim().setInifrm(SettleContext.getTransName());

        limmodVo.getLim().setCur(limmodVo.getCur());
        limmodVo.getLim().setCurnum(codetableService.getTblLabel(limmodVo.getCur(), "CURKEY"));

        limmodVo.getLim().setAmt(limmodVo.getAmt());
        limmodVo.getLim().setComamt(limmodVo.getComamt());
        limmodVo.getLim().setDifamt(limmodVo.getDifamt());
        limmodVo.getLim().setCcvamt(limmodVo.getCcvamt());
        limmodVo.getLim().setCredat(DateUtils.parseDateToStr("yyyyMMdd", limmodVo.getCredat()));
        limmodVo.getLim().setEnddat(DateUtils.parseDateToStr("yyyyMMdd", limmodVo.getEnddat()));
        //getlimref
        for (LimgrdVo limgrd : limmodVo.getLimQueryVo().getLimgrdVoList()) {
            if (!StringUtils.isEmpty(limgrd.getFlg())) {
                limmodVo.setLimref1(limgrd.getLimref());
                break;
            }
        }

        for (LmegrdVo lmegrdVo : limmodVo.getLimQueryVo().getLmegrdVos()) {
            if (!StringUtils.isEmpty(lmegrdVo.getFlg())) {
                limmodVo.setLimref2(lmegrdVo.getLimref());
                break;
            }
        }
        String othextkey = limmodVo.getLimpts().getOth().getExtkey();
        if (!StringUtils.isEmpty(limmodVo.getLimpts().getOth().getPts().getExtkey())) {
            if ("2".equals(limmodVo.getIdtyp2())) {

                limmodVo.getLim().setLimtyp("2");
                limmodVo.getLim().setLimref(limmodVo.getLimref1());

                if ("B".equals(limmodVo.getLimpts().getWrk().getPtytyp())) {
                    limmodVo.getLim().setLimtyp("2");
                    limmodVo.getLim().setLimref(limmodVo.getLimref2());
                }
            } else {
                limmodVo.getLim().setLimtyp("2");
                limmodVo.getLim().setLimref(limmodVo.getLimref2());
            }
        } else {
            limmodVo.getLim().setLimref(limmodVo.getLimref1());
            limmodVo.getLim().setLimtype(limmodVo.getLimpts().getNonrevflg1());
        }
        limmodVo.getLim().setSta("D");
        limmodVo.getLim().setNccvamt(BigDecimal.ZERO);

        if (limRegister().isLimitLma(limmodVo)) {
            limmodVo.getLim().setQtls(counterService.dbCounterFormat("CLMLSH", 6));
        }
        String zsqopen = IniConfig.getIniConfig("intace.ini", "CLM51", "open0");
        if ("Y".equals(zsqopen)) {
            limmodVo.getLim().setSfzsqyw(limmodVo.getLimpts().getSfzsqyw());
            limmodVo.getLim().setMgskhbh(limmodVo.getLimpts().getZsqkhbh());
            limmodVo.getLim().setSffgsyw(limmodVo.getLimpts().getSffgsyw());
            limmodVo.getLim().setZgskhbh(limmodVo.getLimpts().getZgskhbh());
            limmodVo.getLim().setOthmflg(limmodVo.getLimpts().getOthmflg());
            limmodVo.getLim().setOthmgs(limmodVo.getLimpts().getOthmgs());
            limmodVo.getLim().setOthextkey(limmodVo.getLimpts().getOth().getExtkey());
        }
//涉及交易的处理
        limRegister().limLmeSave(limmodVo);

//--提货注销恢复信用证额度时候特殊处理-----------
        if ("04".equals(limmodVo.getLim().getYwcj()) || "12".equals(limmodVo.getLim().getYwcj())) {

            limmodVo.getLim().setComamt(BigDecimal.ZERO);
            limmodVo.getLim().setCcvamt(BigDecimal.ZERO);
        }

        limmodVo.getLim().setTrninr(limmodVo.getTrninr());
        String inr = limMapper.selectInrByTrnInr(limmodVo.getTrninr());
        if (StringUtils.isEmpty(inr)) {
            inr = counterService.dbCounterFormat("LIM");
            limmodVo.getLim().setInr(inr);
            limMapper.insert(limmodVo.getLim());
        } else {
            limmodVo.getLim().setInr(inr);
            limMapper.updateByPrimaryKey(limmodVo.getLim());
        }
//        else不再执行了，废弃掉，不再通过orderinr
//        if ("1".equals(收单行)) {
//        } else {
//            limmodVo.getLim().setOrdinr(limmodVo.getOrderinr());
//            String inr = limMapper.selectInrByOrderinr(limmodVo.getOrderinr(), null);
//            if (StringUtils.isEmpty(inr)) {
//                inr = counterService.dbCounterFormat("LIM");
//                limmodVo.getLim().setInr(inr);
//                limMapper.insert(limmodVo.getLim());
//            } else {
//                limmodVo.getLim().setInr(inr);
//                limMapper.updateByPrimaryKey(limmodVo.getLim());
//            }
//        }
    }

    /**
     * 判断是否收单行占用
     *
     * @param limmodVo
     * @return
     */
    public boolean isLimitSdh(LimmodVo limmodVo) {
        String bchtyp = SettleContext.getUserSession().getBch().getBchtyp();
        if (MdaUtils.compareTo(bchtyp, "6") == 0)
            return true;
        else
            return false;
    }

    /**
     * 判断是否组合
     *
     * @param limmodVo
     * @return
     */
    public boolean isLimitlmc(LimmodVo limmodVo) {
        if (limRegister().needRecalcLimits(limmodVo) && "Y".equals(limmodVo.getLmcflg())) {
            return true;
        }
        return false;
    }

    /**
     * 根据业务信息生成相关的额度TYPE
     *
     * @return
     */
    public String CreateLimitExtidNew(LimmodVo limmodVo, String flg1, String flg2, BigDecimal partcon) {

        String ret = "";
        String trntyp = limmodVo.getRec().getObjtyp().substring(0, 2);

        switch (trntyp) {
            case "GI":
                if (!"GE".equalsIgnoreCase(trntyp)) {

                    if ("OT".equals(flg1)) {
                        ret = "B_GIGT";
                    } else {
                        if ("ABCDFGHJSTUVWX".contains(flg2)) {
                            ret = StringUtils.stringAppend("GIGC", flg2);
                        } else {
                            if ("2".equals(flg2)) {
                                ret = "GIGCE";
                            } else {
                                ret = "GIGCO";
                            }
                        }
                    }

                } else {
                    if ("GHST".contains(flg2) && "FA".equals(flg1)) {

                        ret = "B_GEFA";
                    }
                    if ("GETAMC".equals(SettleContext.getTransName())) {

                        ret = "B_LECN";
                    }
                }
                break;
            case "GE":
                if ("GETAMC".equals(SettleContext.getTransName())) {
                    ret = "B_LECN";
                } else {
                    if (BigDecimal.valueOf(0).compareTo(partcon) < 0) {
                        ret = "B_LECN";
                    }
                }
                break;
            default:
                break;
        }

        return ret;
    }

    /**
     * 融资专用 由于融资是根据融资类型生成占用的额度品种，因此融资提成一个公共的
     *
     * @return
     */
    public String CreateLimitExtidNew2(LimmodVo limmodVo) {
        //!根据业务信息生成相关的额度TYPE

        String ret = "";
        String trntyp = limmodVo.getRec().getObjtyp().substring(0, 2);
        if (MdaUtils.compareTo(trntyp, "BF") == 0 || MdaUtils.compareTo(trntyp, "BO") == 0 || (MdaUtils.compareTo(trntyp, "BE") == 0 && MdaUtils.compareTo(limmodVo.getLim().getInifrm(), "BETAMC") != 0)) {
            trntyp = "BP";
        }
        BigDecimal dscbckamt = BigDecimal.ZERO;
        BptbckVo bptbckVo = limmodVo.getRec().getBptbckVo();
        if (bptbckVo != null) {
            dscbckamt = bptbckVo.getDscbckamt();
        }
        String typ = NULLSTR;
        String purTyp = NULLSTR;
        String pntTyp = NULLSTR;
        if (MdaUtils.compareTo(dscbckamt, 0) > 0) {
            if (MdaUtils.compareTo(SettleContext.getTransName(), "BETSET") == 0
                    || MdaUtils.compareTo(SettleContext.getTransName(), "BFTSET") == 0
                    || MdaUtils.compareTo(SettleContext.getTransName(), "BOTSET") == 0) {
                typ = bptbckVo.getWrkbpdgrp().getRec().getFintyp();
                purTyp = bptbckVo.getWrkbpdgrp().getRec().getRsktyp();
                pntTyp = bptbckVo.getWrkbpdgrp().getRec().getPnttyp();
            }
        }

//融资
        String dflg = NULLSTR;
        String distyp = NULLSTR;
        String flg = NULLSTR;
        if (MdaUtils.compareTo(limmodVo.getRec().getObjtyp(), "BCTSET") == 0) {
            String crefinflg = limmodVo.getRec().getTrtcreVo().getCrefinflg();
            String fintyp = limmodVo.getRec().getTrtcreVo().getTrdgrp().getRec().getFintyp();
            if (MdaUtils.compareTo(crefinflg, "X") == 0) {
                flg = fintyp;
                trntyp = "TR";
            }
        }
        if ("TR".equals(trntyp)) {
            switch (flg) {
                case "BRF":
                    ret = "LITR";
                    break;
                case "DRF":
                    ret = "DITR";
                    break;
                case "BCF":
                    ret = "BCTR";
                    break;
                case "ICF":
                    ret = "CPIT";
                    break;
                case "ECF":
                case "LOA":
                    ret = "CPTR";
                    break;
                case "PCL":
                    ret = "LEPC";
                    break;
                default:
                    ret = "";
            }
        }

        if ("BP".equals(trntyp)) {
            //国内证 dflg=D
            if ("BFTSET".equals(SettleContext.getTransName())) {
                dflg = "D";
            }
            switch (typ) {
                case "D":
                case "T":
                    distyp = purTyp;
                    if (MdaUtils.compareTo(distyp, "DIS") == 0) {   // 合格贴现
                        if (MdaUtils.compareTo(dflg, "D") == 0) {
                            ret = "B_DEBD";
                        } else {
                            ret = "B_LEBD";
                        }
                    }
                    if (MdaUtils.compareTo(distyp, "NNB") == 0) {   // 不合格贴现
                        if (MdaUtils.compareTo(dflg, "D") == 0) {
                            ret = "DEBD2";
                        } else {
                            ret = "LEBD3";
                        }
                    }
                    break;
                case "P":
                case "M":
                    if (MdaUtils.compareTo(purTyp, "NB0") == 0) {   // 合格押汇
                        if (MdaUtils.compareTo(dflg, "D") == 0) {
                            ret = "B_DETR";
                        } else {
                            ret = "B_LEBP";
                        }
                    }
                    if (MdaUtils.compareTo(purTyp, "DSB") == 0) {   // 不合格押汇
                        if ("BED,BFD".contains(pntTyp) || MdaUtils.compareTo(pntTyp, "") == 0) {
                            if (MdaUtils.compareTo(dflg, "D") == 0) {
                                ret = "DETR2";
                            } else {
                                ret = "LEBP3";
                            }
                        }
                        if (MdaUtils.compareTo(pntTyp, "BOD") == 0) {
                            ret = "BOBP";
                        }
                    }
                    if (MdaUtils.compareTo(purTyp, "BO") == 0) {
                        ret = "BOBP";
                    }
                    break;
                case "F":
                    ret = "B_LEFF";
                    break;
                case "U":
                    ret = "B_LURP";
                    break;
                case "I":
                    ret = "CPIT";
                    break;
                case "G":
                    ret = "B_DEBG";
                    break;
                case "V":
                    ret = "B_DEBV";
                    break;
                default:
                    ret = "";
            }
        }

        return ret;
    }

    /**
     * 是否重算额度
     *
     * @return
     */
    public boolean NeedRecalcLimits() {

        return true;
    }

    public void ordBchDeal(LimmodVo limmodVo, String srv) {
        logger.info("正在处理收单行上收的复核的工作流{}{}", SettleContext.getTransName(), limmodVo.getTrninr());
        Lim lim = limmodVo.getLim();
        lim.setOrdinr(limmodVo.getTrninr());
        lim.setVer(StringUtils.stringAppend(lim.getVer(), srv));
        limMapper.updateByPrimaryKey(lim);
    }

    public void rootBchDeal(LimmodVo limmodVo) {
        logger.info("正在处理总行复核的工作流{}{}", SettleContext.getTransName(), limmodVo.getTrninr());
        List<Lim> lims = limMapper.selectLimOderByOwnrefDesc(limmodVo.getOwnref());
        if (CollectionUtils.isEmpty(lims)) {
            return;
        }
        Lim lim = lims.get(0);
        if (StringUtils.isEmpty(lim.getOrdinr())) {
            return;
        }
        if (!lim.getVer().contains("O") && !lim.getVer().contains("T")) {
            return;
        }
        lim.setTrninr(limmodVo.getTrninr());
        lim.setOrdinr("");
        lim.setInifrm(SettleContext.getTransName());
        String inr = counterService.dbCounterFormat("LIM");
        lim.setInr(inr);
        limMapper.insert(lim);
        if (lim.getVer().contains("O")) {
            wfmmodService.wfeAdd("LMO", "LMO", DateUtils.getNowDate(), BigDecimal.valueOf(21));
            logger.info("注册LMO 工作流{}{}", SettleContext.getTransName(), limmodVo.getTrninr());
        }

        List<Limtrn> limtrns = limtrnMapper.selectLimtrnOderByOwnrefDesc(limmodVo.getOwnref());
        Limtrn limtrn = limtrns.get(0);
        limtrn.setTrninr(limmodVo.getTrninr());
        limtrn.setInr(counterService.dbCounterFormat("LIMTRN"));
        limtrnMapper.insert(limtrn);
        wfmmodService.wfeAdd("LMT", "LMT", DateUtils.getNowDate(), BigDecimal.valueOf(21));
        logger.info("注册LMT 工作流{}{}", SettleContext.getTransName(), limmodVo.getTrninr());


    }

    /**
     * 获取同业编号
     *
     * @return
     */
    public String getidtypeinr(String inr, String ptytyp) {
        return ptyMapper.selectIdtypeInr(inr, ptytyp);
    }

    /**
     *
     */
    public PtsptaVo getPtsptaFromPtslist(List<PtsptaVo> ptsptaVoList, String rol) {

        List<PtsptaVo> ptsptaVos = ptsptaVoList.stream().filter(ptsptaVo -> {
            return rol.equalsIgnoreCase(ptsptaVo.getRol());
        }).collect(Collectors.toList());
        if (ptsptaVos.size() > 0) {
            return ptsptaVos.get(0);
        }
        return null;
    }

    public BigDecimal GEToldCCVAMT(LimmodVo limmodVo, String ptyinr) {

        return BigDecimal.ZERO;
    }

    public String getFxfl(String ownref) {

        return limMapper.selectFxfl(ownref);
    }

    /**
     * lmeMapper.deleteByLiminr(inr);
     * 回滚额度信息表
     *
     * @param trninr
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void limRePair(String trninr) {
        logger.info(String.format("开始 回滚额度信息表trninr :%s", trninr));
        String inr = limMapper.selectInrByTrnInr(trninr);

        if (!StringUtils.isEmpty(inr)) {
            lmeMapper.deleteByLiminr(inr);
        }

        limMapper.updateByinr(inr);
        limtrnMapper.deleteByTrninr(trninr);
        logger.info("回滚额度信息表成功");
    }

    public <T> T createCopyObject(Object object, com.fasterxml.jackson.core.type.TypeReference<T> type) {

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(objectMapper.writeValueAsString(object), type);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void clearLimgrd(LimmodVo limmodVo) {
        String mac = calmac(limmodVo);
        if (!StringUtils.isEmpty(limmodVo.getLimpts().getMac())) {
            if (!limmodVo.getLimpts().getMac().equals(mac)) {
                limmodVo.getLimQueryVo().getLimgrdVoList().clear();
                limmodVo.getLimQueryVo().getLmegrdVos().clear();
            }
        }
        limmodVo.getLimpts().setMac(mac);
    }

    String calmac(LimmodVo limmodVo) {
        Map<String, Object> macMap = new LinkedHashMap<>();
//        macMap.put("ownref", limmodVo.getOwnref());
//        macMap.put("comamt", limmodVo.getComamt());
//        macMap.put("ccvamt", limmodVo.getCcvamt());
        macMap.put("extkey", limmodVo.getLimpts().getWrk().getExtkey());
        String data = JSON.toJSONString(macMap);
        logger.info("#########the liminit macdata is {}", data);
        String mac = DigestUtils.sha1Hex(DigestUtils.md5(data));
        return mac;
    }

    public boolean cL43oPn(LimmodVo limmodVo) {
        StbVo stbVo = new StbVo();
        stbVo.setTbl("CL43OP");
        List<Stb> stbs = stbMapper.queryByPage(stbVo);
        logger.info("额度开关{}", stbs.get(0).getCod());
        boolean rst = "Y".equals(stbs.get(0).getCod()) ? true : false;
        if (!rst) {
            limmodVo.getLimpts().setOpnflg("N");
        }
        return rst;
    }

    public boolean RW02oPn() {
        StbVo stbVo = new StbVo();
        stbVo.setTbl("RW02OP");
        List<Stb> stbs = stbMapper.queryByPage(stbVo);
        logger.info("预警开关{}", stbs.get(0).getCod());
        boolean rst = "Y".equals(stbs.get(0).getCod()) ? true : false;
        return rst;
    }

    public void clearOth(LimmodVo limmodVo) {
        limmodVo.getLimpts().setOth(new PtsptaVo());
        limmodVo.getLimpts().setPfcod2("");
        limmodVo.getLimpts().setNonrevflg2("");
        limmodVo.getLimQueryVo().getLmegrdVos().clear();
    }

    public List<PtsptaVo> collectPtsptaListFromObj(String objtyp, String objinr) {
        List<PtsptaVo> ptsptaVos = new ArrayList<>();
        List<Pts> ptslist = ptsMapper.getPtsByObjInrTyp(objinr, objtyp);
        if (ptslist.size() > 0) {
            ptslist.forEach(pts -> {
                PtsptaVo ptsptaVo = new PtsptaVo();
                ptsptaVo.setRol(pts.getRol());
                ptsptaVo.setNam(pts.getNam());
                ptsptaVo.setExtkey(pts.getExtkey());
                ptsptaVo.setDftdsp(pts.getDftdsp());
                ptsptaVo.setDftcur(pts.getDftcur());
                ptsptaVo.setDftact(pts.getDftact());
                ptsptaVo.setDftfeecur(pts.getDftfeecur());
                ptsptaVo.setDftactptainr(pts.getDftactptainr());
                ptsptaVo.setDftselrol(pts.getDftsetrol());
                ptsptaVo.setGlggrpflg(pts.getGlggrpflg());
                ptsptaVo.setAdrblk(pts.getAdrblk());
                ptsptaVo.setPts(pts);
                if (StringUtils.isNotEmpty(pts.getPtainr())) {
                    ptsptaVo.setPta(ptaCacheService.getPtaByInr(pts.getPtainr()));
                }
                ptsptaVos.add(ptsptaVo);
            });
        }
        return ptsptaVos;
    }

    public PtsptaVo huoquRol(PtsptaVo pts) {
        PtsptaVo ptsptaVo = null;
        if (MdaUtils.isEmpty(pts)) {
            ptsptaVo = new PtsptaVo();
            ptsptaVo.reset();
        } else {
            ptsptaVo = pts;
        }
        return ptsptaVo;

    }

    /**
     * 获取保函业务品种
     *
     * @param gartyp
     * @return
     * @throws Exception
     */
    public String getGidTrnCodeOwnref(String gartyp) {
        String trncode; // 业务品种
        if (gartyp.startsWith("A")) {
            trncode = "05140201";
        } else if (gartyp.startsWith("B")) {
            trncode = "05140202";
        } else if (gartyp.startsWith("C")) {
            trncode = "05140203";
        } else if (gartyp.startsWith("D")) {
            trncode = "05140204";
        } else if (gartyp.startsWith("F")) {
            trncode = "05140206";
        } else if (gartyp.startsWith("2")) {
            trncode = "05140210";
        } else if (gartyp.startsWith("G")) {
            trncode = "05140101";
        } else if (gartyp.startsWith("H")) {
            trncode = "05140102";
        } else if (gartyp.startsWith("J")) {
            trncode = "05140205";
        } else if (gartyp.startsWith("S")) {
            trncode = "05140104";
        } else if (gartyp.startsWith("T")) {
            trncode = "05140103";
        } else if (gartyp.startsWith("U")) {
            trncode = "05140207";
        } else if (gartyp.startsWith("V")) {
            trncode = "051419";
        } else if (gartyp.startsWith("X")) {
            trncode = "05140208";
        } else if (gartyp.startsWith("W")) {
            trncode = "05140105";
        } else {
            trncode = "05140299";
        }
        return trncode;
    }
}
