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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.brilliance.isc.bo.Bch;
import com.brilliance.isc.bo.Pty;
import com.brilliance.isc.common.api.bch.service.BchService;
import com.brilliance.isc.common.cache.pty.PtyCacheService;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.esb.ResultVo;
import com.brilliance.isc.common.esb.clm.IClmFeign;
import com.brilliance.isc.common.esb.rwms.IRwmsFeign;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.common.limmod.service.LimOptionService;
import com.brilliance.isc.common.limmod.service.LimmodService;
import com.brilliance.isc.common.limmod.vo.LimQueryVo;
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.esb.model.inner.*;
import com.brilliance.isc.transfer.esb.IEsbMapper;
import com.brilliance.isc.utils.BigDecimalUtils;
import com.brilliance.isc.utils.StringUtils;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Strings;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service("limquery")
public class LimqueryServiceImpl implements LimOptionService<InnerResCL81> {


    @Autowired
    private LimmodService limmodService;
    @Autowired
    private CodetableService codetableService;
    @Autowired(required = false)
    private IClmFeign clmFeign;

    @Autowired(required = false)
    private IRwmsFeign rwmsFeign;

    @Autowired
    private PtyCacheService ptyCacheService;
    private final Logger logger = LoggerFactory.getLogger(LimqueryServiceImpl.class);

    @Autowired
    private BchService bchService;

    /**
     * 额度查询入口
     */
    public void assertLim(LimmodVo limmodVo) {
        logger.info("-----------开始处理额度查询{}{}------------", limmodVo.getRec().getOwnref(), SettleContext.getTransName());
        if (!limmodService.cL43oPn(limmodVo)) {
            return;
        }
        limmodService.LimRegParstm(limmodVo);
//        limmodService.checkData(limmodVo);
        LimRegParstm(limmodVo);
        logger.info("-----------结束额度查询{}{}------------", limmodVo.getRec().getOwnref(), SettleContext.getTransName());

    }

    /**
     * 额度查询注册
     *
     * @param limmodVo
     */
    public void LimRegParstm(LimmodVo limmodVo) {
        if ("E".equals(limmodVo.getLimpts().getErrorflg())) {
            return;
        }
        limDataCal(limmodVo);
        limmodService.limRegister().limQureyRegister(limmodVo);
        if (limmodService.RW02oPn()) {
            ResultVo result = callRw02(limmodVo);
            limmodVo.setRw02ConfirmInfos(result.getConfirmMsg());
            limmodVo.setRw02Rmatch(result.getRmatch());
        }
        callEsb(limmodVo);
        saveTables(limmodVo);

    }

    /**
     * 公共计算逻辑
     *
     * @param limmodVo
     */
    public void limDataCal(LimmodVo limmodVo) {

        LimQueryVo limQueryVo = limmodVo.getLimQueryVo();
//根据2016/03/25与额度系统的最新业务规则
//综合授信的时候，串用标志 传“可串”，额度品种传“本品种”
//传额度品种时:
//（1）本品种的不串用的额度记录(向下追溯)
//（2）所有串用的额度记录
//单笔单批的时候，串用标志 传“不可串”，额度品种传“本品种” 走3.1或4.1逻辑（单笔单批只能查询出未被使用的额度记录）；
//（1）传合同流水号（1）展示复核合同流水号\额度品种的合同流水信息
//（2）不传合同流水号（1）展示复核额度品种的合同流水信息
//同业和对公查询都走上面逻辑。
//
//#参数typ为1时是左边的查询typ为2时就是右边的
        String juscod = "";
        String swiftno = "";
        String limnum = "";
        String limsta = "";
        String rzbch = SettleContext.getUserSession().getBch().getBranch();

        if (!StringUtils.isEmpty(limmodVo.getBranch())) {
            rzbch = limmodVo.getBranch();
        }
//额度品种
        String limvar = limmodVo.getLimQueryVo().getLimvar();
        if (MdaUtils.isEmpty(limvar)) {
            limvar = "";
        }
//    串用标志:0表示不串用，1表示串
        String linflg = "";
        String jioygy = SettleContext.getUserSession().getUsr().getExtkey();
        if (!StringUtils.isEmpty(limmodVo.getUser())) {
            jioygy = limmodVo.getUser();
        }
        //此处如果OTH对象为空则认为typ是1，因为只有同业取值才会
        if (MdaUtils.isEmpty(limmodVo.getLimpts().getOth().getPtyinr()))
            limQueryVo.setType("1");
        String jinbjg = rzbch;
        String extkey = "";
        String limtyp = "";
        String idtype = "";
        if ("1".equals(limQueryVo.getType())) {
            extkey = limmodVo.getLimpts().getWrk().getExtkey();
            limtyp = limmodVo.getLimpts().getNonrevflg1();
            idtype = limmodService.getidtypeinr(limmodVo.getLimpts().getWrk().getPtyinr(), "C");
        } else {
            extkey = limmodVo.getLimpts().getOth().getExtkey();
            limtyp = limmodVo.getLimpts().getNonrevflg2();
            idtype = limmodService.getidtypeinr(limmodVo.getLimpts().getOth().getPtyinr(), "C");

        }
        if ("2".equalsIgnoreCase(limtyp)) {

            linflg = "0";
            if ("1".equalsIgnoreCase(limQueryVo.getType())) {

                limnum = limmodVo.getLimpts().getPfcod1();

            } else {

                limnum = limmodVo.getLimpts().getPfcod2();
            }
        } else {

            linflg = "1";
        }
        limvar = codetableService.getTblLabel(limmodVo.getExtid(), "LMSCOD");

        //这部分移动至业务交易
        if ("1".equalsIgnoreCase(limQueryVo.getType())) {
            if ("B".equalsIgnoreCase(limmodVo.getLimpts().getWrk().getPtytyp())) {
                if ("05".equalsIgnoreCase(Strings.mid(limvar, 1, 2))) {
                    limvar = "05";

                }
                if (!MdaUtils.isEmpty(limmodVo.getEcifno())) {
                    extkey = limmodVo.getEcifno();

                }
            }

        }
        String khtyp = "";
        if ("1".equalsIgnoreCase(idtype)) {

            khtyp = "1";
        } else {

            khtyp = "2";
        }

        extkey = extkey.split("-")[0];
        limQueryVo.setKhtyp(khtyp);
        limQueryVo.setExtkey(extkey);
        limQueryVo.setSwiftno(swiftno);
        limQueryVo.setJuscod(juscod);
        limQueryVo.setLimnum(limnum);
        limQueryVo.setLimvar(limvar);
        limQueryVo.setLimsta(limsta);
        limQueryVo.setRzbch(rzbch);
        limQueryVo.setSfcxlm(linflg);
        limQueryVo.setBchusr(jioygy);
        limQueryVo.setLimtyp(limtyp);
        limQueryVo.setAccbch(rzbch);

        limmodVo.getLimpts().setPfcod1("");
    }

    /**
     * 调接口
     *
     * @param limmodVo
     */
    public void callEsb(LimmodVo limmodVo) {
        if (logger.isDebugEnabled()) {
            logger.debug("开始调用额度查询接口{}", JSON.toJSONString(limmodVo.getLimQueryVo()));
        }
        InnerReq<InnerReqCL81> innerReqCL81InnerReq = new InnerReq<InnerReqCL81>(IEsbMapper.INSTANCE.copyLimQuery(limmodVo.getLimQueryVo()));
        InnerRes<InnerResCL81> innerResCL81InnerRes = clmFeign.callCL81(innerReqCL81InnerReq);

        if ("AAAAAAA".equals(innerResCL81InnerRes.header.code)) {
            responseMapping(innerResCL81InnerRes, limmodVo);
            if (logger.isDebugEnabled()) {
                logger.debug("额度接口调用查询成功");
            }
        } else {

            throw new CommonServiceException(StringUtils.stringAppend("额度查询接口调用失败:", innerResCL81InnerRes.header.description));
        }
    }

    public ResultVo callRw02(LimmodVo limmodVo) {
        ResultVo resultVo = new ResultVo();
        InnerReq<InnerReqRW02> req = new InnerReq<InnerReqRW02>();
        InnerReqRW02 data = new InnerReqRW02();
        Header header = new Header();
        String ptyinr = "";
        if (limmodVo != null && limmodVo.getLimQueryVo() != null && "2".equals(limmodVo.getLimQueryVo().getType())) {
            ptyinr = limmodVo.getLimpts().getOth().getPtyinr();
        } else {
            ptyinr = limmodVo.getLimpts().getWrk().getPtyinr();
        }
        Pty wrkpty = ptyCacheService.getPtyById(ptyinr);
        if (wrkpty != null) {
            data.csname = wrkpty.getNam1();
            data.certid = wrkpty.getJuscod();
            req.DATA = data;
            req.header = header;
            InnerRes<InnerResRW02> innerRes = rwmsFeign.callRW02(req);
            if ("AAAAAAA".equals(innerRes.header.code)) {
                resultVo.setSuccess(true);
                InnerResRW02 res = innerRes.DATA;
                List<String> confirmMsg = new ArrayList<>();
                confirmMsg.add(StringUtils.formatText("客户名称：$1", res.csname));
                confirmMsg.add(StringUtils.formatText("组织机构代码：$1", res.certid));
                confirmMsg.add(StringUtils.formatText("预警黑灰名单返回结果：$1", getMatchStr(res.rmatch)));
                confirmMsg.add(StringUtils.formatText("名单名称：$1", res.ltname));
                confirmMsg.add(StringUtils.formatText("名单调入时间：$1", res.atdate));
                confirmMsg.add(StringUtils.formatText("政策例外调入时间：$1", res.policy));
                confirmMsg.add(StringUtils.formatText("问题客户调入时间：$1", res.probcs));
                boolean confirmFlg = getContinueBool(res.rmatch);
                confirmMsg.add(StringUtils.formatText("$1", confirmFlg ? "是否继续？" : "不允许release！"));
                resultVo.setConfirmMsg(confirmMsg);
                resultVo.setConfirm(confirmFlg);
                resultVo.setRmatch(res.rmatch);
            } else {
                throw new CommonServiceException(StringUtils.stringAppend("预警接口调用失败:", innerRes.header.description));
            }
        }
        return resultVo;
    }

    public String getMatchStr(String rmatch) {
        String rmatchstr = "";
        switch (rmatch) {
            case "05":
                rmatchstr = "05：不通过-黑/退出";
                break;
            case "06":
                rmatchstr = "06:通过-黄";
                break;
            case "07":
                rmatchstr = "07：不通过-存在未完成处置的预警信号";
                break;
            case "01":
                //01:通过-黑+政策例外
                rmatchstr = "01:通过-黑+政策例外";
                break;
            case "02":
                rmatchstr = "02:通过-黑+名单例外客户";
                break;
            case "03":
                rmatchstr = "03:通过-灰";
                break;
            case "04":
                break;
            default:
        }

        return rmatchstr;
    }

    public boolean getContinueBool(String rmatch) {
        boolean confirmFlg = false;
        switch (rmatch) {
            case "05":
                break;
            case "06":
                confirmFlg = true;
                break;
            case "07":
                break;
            case "01":
                //01:通过-黑+政策例外
                confirmFlg = true;
                break;
            case "02":
                confirmFlg = true;
                break;
            case "03":
                confirmFlg = true;
                break;
            case "04":
                break;
            default:
        }
        return confirmFlg;
    }

    /**
     * 存表
     *
     * @param limmodVo
     */
    public void saveTables(LimmodVo limmodVo) {


    }

    /**
     * 将返回结果做映射
     *
     * @param innerResCL81InnerRes
     * @param limmodVo
     */
    public void responseMapping(InnerRes<InnerResCL81> innerResCL81InnerRes, LimmodVo limmodVo) {

        List<LimgrdVo> limgrdVoList = limmodVo.getLimQueryVo().getLimgrdVoList();
        List<LmegrdVo> lmegrdVoList = limmodVo.getLimQueryVo().getLmegrdVos();

        limmodVo.getOldlimQueryVo().setLmegrdVos(MdaUtils.deepClone(lmegrdVoList));
        if ("1".equals(limmodVo.getLimQueryVo().getType()))
            limgrdVoList.clear();
        else
            lmegrdVoList.clear();

        if (!MdaUtils.isEmpty(innerResCL81InnerRes.DATA.lstCL812)) {
            for (InnerResCL81.ItemCL812 fcl82 : innerResCL81InnerRes.DATA.lstCL812) {
                if ("1".equals(limmodVo.getLimQueryVo().getType())) {
                    LimgrdVo limgrdVo = new LimgrdVo();
                    limgrdVo.setLimtyp(limmodVo.getLimpts().getNonrevflg1());
                    limgrdVo.setLimref(fcl82.tb2xx01);
                    limgrdVo.setInfref(fcl82.tb2xx02);
                    limgrdVo.setLimcod(fcl82.tb2xx03);
                    limgrdVo.setLimcodsave(fcl82.tb2xx03);
                    limgrdVo.setLimcod(codetableService.getTblLabel(fcl82.tb2xx03, "LMSTXT"));
                    limgrdVo.setRemark(fcl82.tb2xx04);
                    if (!MdaUtils.isEmpty(fcl82.tb2xx05)) {
                        fcl82.tb2xx05 = codetableService.getTblKey(fcl82.tb2xx05, "CURKEY");
                    }
                    limgrdVo.setCur(fcl82.tb2xx05);
                    limgrdVo.setCpsxed(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx06));
                    limgrdVo.setBalamt(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx07));
                    limgrdVo.setUseamt(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx08));
                    limgrdVo.setCpsxck(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx09));
                    limgrdVo.setCpkyck(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx10));
                    limgrdVo.setCpyyck(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx11));
                    limgrdVo.setLbwamt(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx12));
                    limgrdVo.setLbwamt1(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx13));
                    limgrdVo.setLbwamt2(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx14));
                    limgrdVo.setLcpsta(fcl82.tb2xx15);
                    limgrdVo.setBxh(fcl82.tb2xx16);
                    limgrdVo.setBcy(fcl82.tb2xx17);
                    limgrdVo.setCyremark(fcl82.tb2xx18);
                    limgrdVo.setCcvpct(fcl82.tb2xx19);
                    if (!MdaUtils.isEmpty(fcl82.tb2xx20)) {
                        limgrdVo.setCredat(DateUtil.parse(fcl82.tb2xx20, "yyyy-MM-dd"));
                    }
                    if (!MdaUtils.isEmpty(fcl82.tb2xx21)) {
                        limgrdVo.setMatdat(DateUtil.parse(fcl82.tb2xx21, "yyyy-MM-dd"));
                    }
                    limgrdVo.setBdj(fcl82.tb2xx22);
                    if (!MdaUtils.isEmpty(fcl82.tb2xx23)) {
                        limgrdVo.setDondat(DateUtil.parse(fcl82.tb2xx23, "yyyy-MM-dd"));
                    }
                    limgrdVo.setBzz(fcl82.tb2xx24);
                    if (!MdaUtils.isEmpty(fcl82.tb2xx25)) {
                        limgrdVo.setZhzdat(DateUtil.parse(fcl82.tb2xx25, "yyyy-MM-dd"));
                    }
                    limgrdVo.setFentyp(fcl82.tb2xx26);
                    limgrdVo.setFentxt(fcl82.tb2xx27);
                    if (!MdaUtils.isEmpty(fcl82.tb2xx26)) {
                        limgrdVo.setFentxt(codetableService.getTblLabel(fcl82.tb2xx26, "FENTYP"));
                    }
                    limgrdVoList.add(limgrdVo);
                } else {
                    LmegrdVo lmegrdVo = new LmegrdVo();
                    lmegrdVo.setLimref(fcl82.tb2xx01);
                    lmegrdVo.setInfref(fcl82.tb2xx02);
                    lmegrdVo.setLimcod(fcl82.tb2xx03);
                    lmegrdVo.setLimcodsave(fcl82.tb2xx03);
                    lmegrdVo.setLimcod(codetableService.getTblLabel(fcl82.tb2xx03, "LMSTXT"));
                    lmegrdVo.setRemark(fcl82.tb2xx04);
                    if (!MdaUtils.isEmpty(fcl82.tb2xx05)) {
                        fcl82.tb2xx05 = codetableService.getTblKey(fcl82.tb2xx05, "CURKEY");
                    }
                    lmegrdVo.setCur(fcl82.tb2xx05);
                    lmegrdVo.setCpsxed(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx06));
                    lmegrdVo.setBalamt(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx07));
                    lmegrdVo.setUseamt(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx08));
                    lmegrdVo.setCpsxck(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx09));
                    lmegrdVo.setCpkyck(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx10));
                    lmegrdVo.setCpyyck(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx11));
                    lmegrdVo.setLbwamt(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx12));
                    lmegrdVo.setLbwamt1(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx13));
                    lmegrdVo.setLbwamt2(BigDecimalUtils.string2BigDecimal(fcl82.tb2xx14));
                    lmegrdVo.setLcpsta(fcl82.tb2xx15);
                    lmegrdVo.setBxh(fcl82.tb2xx16);
                    lmegrdVo.setBcy(fcl82.tb2xx17);
                    lmegrdVo.setCyremark(fcl82.tb2xx18);
                    lmegrdVo.setCcvpct(fcl82.tb2xx19);
                    if (!MdaUtils.isEmpty(fcl82.tb2xx20)) {
                        lmegrdVo.setCredat(DateUtil.parse(fcl82.tb2xx20, "yyyy-MM-dd"));
                    }
                    if (!MdaUtils.isEmpty(fcl82.tb2xx21)) {
                        lmegrdVo.setMatdat(DateUtil.parse(fcl82.tb2xx21, "yyyy-MM-dd"));
                    }
                    lmegrdVo.setBdj(fcl82.tb2xx22);
                    if (!MdaUtils.isEmpty(fcl82.tb2xx23)) {
                        lmegrdVo.setDondat(DateUtil.parse(fcl82.tb2xx23, "yyyy-MM-dd"));
                    }
                    lmegrdVo.setBzz(fcl82.tb2xx24);
                    if (!MdaUtils.isEmpty(fcl82.tb2xx25)) {
                        lmegrdVo.setZhzdat(DateUtil.parse(fcl82.tb2xx25, "yyyy-MM-dd"));
                    }
                    lmegrdVo.setFentyp(fcl82.tb2xx26);
                    lmegrdVo.setFentxt(fcl82.tb2xx27);
                    if (!MdaUtils.isEmpty(fcl82.tb2xx26)) {
                        lmegrdVo.setFentxt(codetableService.getTblLabel(fcl82.tb2xx26, "FENTYP"));
                    }
                    lmegrdVoList.add(lmegrdVo);
                }
            }

        }
        if (!MdaUtils.isEmpty(innerResCL81InnerRes.DATA.lstCL811)) {
            int count = 0;
            for (InnerResCL81.ItemCL811 fcl81 : innerResCL81InnerRes.DATA.lstCL811) {
                for (LmegrdVo lmegrdVo : lmegrdVoList) {
                    if (lmegrdVo.getLimref().equals(fcl81.tbxx04)) {
                        if ("2".equals(limmodVo.getLimQueryVo().getType())) {
                            if (lmegrdVoList.size() != 0) {
                                lmegrdVo.setLimtyp(fcl81.tbxx01);
                                lmegrdVo.setCecmsx(fcl81.tbxx02);
                                lmegrdVo.setRuzhjg(fcl81.tbxx03);
                                if (StringUtils.isEmpty(lmegrdVo.getLimref())) {
                                    lmegrdVo.setLimref(fcl81.tbxx04);
                                }
                                lmegrdVo.setZzsxbh(fcl81.tbxx05);
                                lmegrdVo.setDaikxz(fcl81.tbxx06);
                                if (!MdaUtils.isEmpty(fcl81.tbxx07)) {
                                    lmegrdVo.setLimcur(codetableService.getTblKey(fcl81.tbxx07, "CURKEY"));

                                }
                                lmegrdVo.setLimamt(BigDecimalUtils.string2BigDecimal(fcl81.tbxx08));
                                lmegrdVo.setLsbamt(BigDecimalUtils.string2BigDecimal(fcl81.tbxx09));
                                lmegrdVo.setBallsbamt(BigDecimalUtils.string2BigDecimal(fcl81.tbxx10));
                                lmegrdVo.setUselsbamt(BigDecimalUtils.string2BigDecimal(fcl81.tbxx11));
                                lmegrdVo.setLimsta(fcl81.tbxx12);

                                if (!MdaUtils.isEmpty(fcl81.tbxx13)) {
                                    lmegrdVo.setValdat(DateUtil.parse(fcl81.tbxx13, "yyyy-MM-dd"));

                                }
                                if (!MdaUtils.isEmpty(fcl81.tbxx14)) {
                                    lmegrdVo.setEnddat(DateUtil.parse(fcl81.tbxx14, "yyyy-MM-dd"));

                                }
                                lmegrdVo.setBfx(fcl81.tbxx15);
                                lmegrdVo.setGuatyp(fcl81.tbxx16);
                                lmegrdVo.setGuaval(fcl81.tbxx17);
                            }

                        }
                    }
                }
                for (LimgrdVo limgrdVo : limgrdVoList) {
                    if (limgrdVo.getLimref().equals(fcl81.tbxx04)) {
                        if ("1".equals(limmodVo.getLimQueryVo().getType())) {
                            if (limgrdVoList.size() != 0) {
                                limgrdVo.setLimtyp(fcl81.tbxx01);
                                limgrdVo.setCecmsx(fcl81.tbxx02);
                                limgrdVo.setRuzhjg(fcl81.tbxx03);
                                if (StringUtils.isEmpty(limgrdVo.getLimref())) {
                                    limgrdVo.setLimref(fcl81.tbxx04);
                                }
                                limgrdVo.setZzsxbh(fcl81.tbxx05);
                                limgrdVo.setDaikxz(fcl81.tbxx06);
                                if (!MdaUtils.isEmpty(fcl81.tbxx07)) {
                                    limgrdVo.setLimcur(codetableService.getTblKey(fcl81.tbxx07, "CURKEY"));

                                }
                                limgrdVo.setLimamt(BigDecimalUtils.string2BigDecimal(fcl81.tbxx08));
                                limgrdVo.setLsbamt(BigDecimalUtils.string2BigDecimal(fcl81.tbxx09));
                                limgrdVo.setBallsbamt(BigDecimalUtils.string2BigDecimal(fcl81.tbxx10));
                                limgrdVo.setUselsbamt(BigDecimalUtils.string2BigDecimal(fcl81.tbxx11));
                                limgrdVo.setLimsta(fcl81.tbxx12);

                                if (!MdaUtils.isEmpty(fcl81.tbxx13)) {
                                    limgrdVo.setValdat(DateUtil.parse(fcl81.tbxx13, "yyyy-MM-dd"));

                                }
                                if (!MdaUtils.isEmpty(fcl81.tbxx14)) {
                                    limgrdVo.setEnddat(DateUtil.parse(fcl81.tbxx14, "yyyy-MM-dd"));

                                }
                                limgrdVo.setBfx(fcl81.tbxx15);
                                limgrdVo.setGuatyp(fcl81.tbxx16);
                                limgrdVo.setGuaval(fcl81.tbxx17);
                            }
                        }
                    }
                }
            }
        }
        String accbch = SettleContext.getUserSession().getBch().getBranch();
        String branch1 = bchService.getDirectParentBch(accbch).getBranch();
        logger.info("当前业务全辖机构为:{}", branch1);
        List<Bch> bchsstr = bchService.listAllChildAndItselfBch(branch1);
        String bchsstrs = "";
        for (Bch bch : bchsstr) {
            bchsstrs = StringUtils.stringAppend(bchsstrs, ",", bch.getBranch());
        }

        logger.info("当前记账机构下辖机构为:{}", bchsstrs);

        if (!"B".equals(limmodVo.getLimpts().getWrk().getPtytyp())) {
            String finalBchsstrs = bchsstrs;
            limgrdVoList = limgrdVoList.stream().filter(limgrdVo -> {
                Bch branch = bchService.getDirectAccBch(limgrdVo.getRuzhjg());
                if (!ObjectUtils.isEmpty(branch) && finalBchsstrs.contains(branch.getBranch())) {
                    return true;
                }
                return false;
            }).collect(Collectors.toList());
        }
        limgrdVoList.sort(Comparator.comparing(LimgrdVo::getLimcodsave));
        lmegrdVoList.sort(Comparator.comparing(LmegrdVo::getLimcodsave));
        int i = 1;
        int j = 1;
        for (LimgrdVo limgrdVo : limgrdVoList) {
            limgrdVo.setShxh(i++);
        }
        for (LmegrdVo lmegrdVo : lmegrdVoList) {
            lmegrdVo.setShxh(j++);
        }

        limmodVo.getOldlimQueryVo().getLimgrdVoList().forEach(limgrdVo -> {
            if ("X".equals(limgrdVo.getFlg())) {
                limmodVo.getLimpts().setPfcod1(limgrdVo.getLimref());
            }
        });
        limmodVo.getOldlimQueryVo().getLmegrdVos().forEach(lmegrdVo -> {
            if ("X".equals(lmegrdVo.getFlg())) {
                limmodVo.getLimpts().setPfcod2(lmegrdVo.getLimref());
            }
        });
        limQueryBanlance(limmodVo, limgrdVoList);

        limQueryBanlance2(limmodVo, lmegrdVoList);
    }

    public void limQueryBanlance(LimmodVo limmodVo, List<LimgrdVo> limgrdVoList) {
        if (CollectionUtils.isEmpty(limmodVo.getOldlimQueryVo().getLimgrdVoList())) {
            limmodVo.getLimQueryVo().setLimgrdVoList(limgrdVoList);
            return;
        }
        List<LimgrdVo> tmplimgrdVoList = (List<LimgrdVo>) limmodService.createCopyObject(limmodVo.getOldlimQueryVo().getLimgrdVoList(), new com.fasterxml.jackson.core.type.TypeReference<List<LimgrdVo>>() {
        });
        if (tmplimgrdVoList.size() > 0) {
            tmplimgrdVoList.stream().map(limgrdVo -> {
                if ("X".equals(limgrdVo.getFlg())) {
                    limgrdVo.setFlg("");
                }
                return limgrdVo;
            }).collect(Collectors.toList());
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String oldlimgrd = "";
        String limgrd = "";
        try {
            oldlimgrd = objectMapper.writeValueAsString(tmplimgrdVoList);
            limgrd = objectMapper.writeValueAsString(limgrdVoList);
        } catch (JsonProcessingException e) {
            logger.error("额度查询序列化异常{}", e.getMessage());
        }
        if (limgrdVoList.size() > 0 && limgrd.equals(oldlimgrd)) {
            limmodVo.getLimQueryVo().setLimgrdVoList(limmodVo.getOldlimQueryVo().getLimgrdVoList());
        } else {
            limmodVo.getLimQueryVo().setLimgrdVoList(limgrdVoList);
        }
    }

    public void limQueryBanlance2(LimmodVo limmodVo, List<LmegrdVo> lmegrdVoList) {
        if (CollectionUtils.isEmpty(limmodVo.getOldlimQueryVo().getLmegrdVos())) {
            limmodVo.getLimQueryVo().setLmegrdVos(lmegrdVoList);
            return;
        }
        List<LmegrdVo> tmplmegrdVoList = (List<LmegrdVo>) limmodService.createCopyObject(limmodVo.getOldlimQueryVo().getLmegrdVos(), new com.fasterxml.jackson.core.type.TypeReference<List<LmegrdVo>>() {
        });
        if (tmplmegrdVoList.size() > 0) {
            tmplmegrdVoList.stream().map(lmegrdVo -> {
                if ("X".equals(lmegrdVo.getFlg())) {
                    lmegrdVo.setFlg("");
                }
                return lmegrdVo;
            }).collect(Collectors.toList());
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String oldlimgrd = "";
        String limgrd = "";
        try {
            oldlimgrd = objectMapper.writeValueAsString(tmplmegrdVoList);
            limgrd = objectMapper.writeValueAsString(lmegrdVoList);
        } catch (JsonProcessingException e) {
            logger.error("额度查询序列化异常{}", e.getMessage());
        }
        if (lmegrdVoList.size() > 0 && limgrd.equals(oldlimgrd)) {
            limmodVo.getLimQueryVo().setLmegrdVos(limmodVo.getOldlimQueryVo().getLmegrdVos());
        } else {
            limmodVo.getLimQueryVo().setLmegrdVos(lmegrdVoList);
        }
    }
}
