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

import com.brilliance.mda.runtime.mda.impl.Argument;
import com.brilliance.mda.runtime.mda.util.Dates;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Strings;
import com.brilliance.isc.bo.*;
import com.brilliance.isc.bo.model.Dftcre;
import com.brilliance.isc.common.cbsmod.service.XrtmodService;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.component.DftmodComponent;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.context.SpringEnvContext;
import com.brilliance.isc.common.dftcre.service.DftcreService;
import com.brilliance.isc.common.dftcre.service.DftpService;
import com.brilliance.isc.common.register.dftcre.IDftcreRegister;
import com.brilliance.isc.common.sysmod.SysmodService;
import com.brilliance.isc.common.transaction.help.TransactionHelpService;
import com.brilliance.isc.common.trnmod.service.TrnmodService;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.mda.dao.DfdMapper;
import com.brilliance.isc.mda.dao.DftMapper;
import com.brilliance.isc.mda.dao.PtsMapper;
import com.brilliance.isc.vo.component.trtcre.TrtcreVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

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

@Service
public class DftcreServiceImpl implements DftcreService {

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

    @Autowired
    private XrtmodService xrtmodService;

    @Autowired
    private TrnmodService trnmodService;

    @Autowired
    private TransactionHelpService transactionHelpService;

    @Autowired
    private SysmodService sysmodService;

    @Autowired
    private DftpService dftpService;

    @Autowired
    private CodetableService codetableService;

    @Autowired
    private DfdMapper dfdMapper;

    @Autowired
    private DftMapper dftMapper;

    @Autowired
    private PtsMapper ptsMapper;

    @Autowired
    private DftmodComponent dftmodComponent;

    public void assertDftcre(Dftcre dftcreVo) {
        dftcreVo.getDfdgrp().getRec().setStttendat(Dates.today());
        String objtyp = dftcreVo.getRec().getObjtyp();
        IDftcreRegister dftcreRegister = null;
        try {
            dftcreRegister = SpringEnvContext.getBean(objtyp.toLowerCase() + "." + "dftcreRegister");
        } catch (NoSuchBeanDefinitionException e) {
            log.warn("没有找到融资处理注册类, 不涉及融资处理流程");
        }
        if (dftcreRegister == null) {
            return;
        }
        //根据xxxgrp初始化数据
        dftcreRegister.setDFDfieldsfromXXX(dftcreVo);
        //执行初始化赋值
        defaultOricur(dftcreVo);
        defaultOriamt(dftcreVo);
        defaultDfdgrpRecFintyp(dftcreVo);
        defaultDfdgrpCbsMaxCur(dftcreVo);
        defaultDfdgrpRecTrntyp(dftcreVo);
        defaultDfdgrpRecNam(dftcreVo);
        defaultInitFields(dftcreVo);
        defaultDftpPansta(dftcreVo);
        defaultDfdgrpRecInvtyp(dftcreVo);
        dftpService.defaultDfdgrpRecIntprd(dftcreVo.getDfdgrp());
        dftpService.defaultDfdgrpRecOwnusr(dftcreVo.getDfdgrp());
        dftpService.defaultDfdgrpRecFlttyp(dftcreVo.getDfdgrp());
    }

    /**
     * 1.删除dfd dft数据
     * 2.删除关联pts数据
     *
     * @param trn
     */
    @Override
    public void rollbackDftcreDatas(Trn trn) {
        String objtyp = trn.getObjtyp();
        IDftcreRegister dftcreRegister = null;
        try {
            dftcreRegister = SpringEnvContext.getBean(objtyp.toLowerCase() + "." + "dftcreRegister");
        } catch (NoSuchBeanDefinitionException e) {
            log.warn("没有找到融资处理注册类, 不涉及融资处理流程");
        }
        if (dftcreRegister == null) {
            return;
        }
        boolean isNeedRepair = dftcreRegister.isNeedRepair(trn);
        if (isNeedRepair) {
            Dfd dfd = dfdMapper.getDfdByParentInrAndType(trn.getObjtyp(), trn.getObjinr());
            if (dfd != null) {
                sysmodService.sdbDeleteWithLog(dfd);
                Dft dft = dftMapper.getDftByInr(dfd.getInr());
                if (dft != null) {
                    sysmodService.sdbDeleteWithLog(dft);
                }
                List<Pts> ptsList = ptsMapper.getPtsByObjInrTyp(dfd.getInr(), "DFD");
                if (ptsList != null && ptsList.size() > 0) {
                    ptsMapper.batchDelete(ptsList);
                }
            }
        }
    }

    /**
     * source:dftcre.0000.script
     */
    public void defaultOricur(Dftcre dftcreVo) {
        if (MdaUtils.compareTo(SettleContext.getTransName(), "BPTOPN") == 0 || MdaUtils.compareTo(SettleContext.getTransName(), "TRTOPN") == 0) {
            return;
        }
        dftcreVo.setOricur(dftcreVo.getRec().getDoccur());
    }

    /**
     * source:dftcre.0001.script
     */
    public void defaultOriamt(Dftcre dftcreVo) {
        if (MdaUtils.compareTo(SettleContext.getTransName(), "BPTOPN") == 0 || MdaUtils.compareTo(SettleContext.getTransName(), "TRTOPN") == 0) {
            return;
        }
        dftcreVo.setOriamt(dftcreVo.getRec().getDocamt());
    }

    /**
     * source:dftcre.0003.script
     */
    public void defaultDfdgrpRecFintyp(Dftcre dftcreVo) {
        //如create finance有值 则为我行融资 否则为我行风险参与
        //国内证只有我行风险参与
        String finflg = "";
        TrtcreVo trtcreVo = dftcreVo.getRec().getTrtcreVo();
        if (trtcreVo != null) {
            finflg = trtcreVo.getCrefinflg();
        }
        String frame = SettleContext.getTransName();
        //Systems.resetEnabled(this.getDfdgrp().getRec(),"fintyp");
        //if IsEmpty( DFDGRP\\REC\\FINTYP ) then
        if (!MdaUtils.isEmpty(finflg)) {
            dftcreVo.getDfdgrp().getRec().setFintyp("A");
        } else {
            if (MdaUtils.compareTo(frame, "TRTOPN") == 0 || MdaUtils.compareTo(frame, "BPTOPN") == 0) {
                dftcreVo.getDfdgrp().getRec().setFintyp("A");
            } else {
                dftcreVo.getDfdgrp().getRec().setFintyp("B");
            }
        }
//        if(MdaUtils.compareTo(frame, "BFTSET") == 0) {
//            dftcreVo.getDfdgrp().getRec().setFintyp("B");
//        }
    }

    /**
     * source:dftcre.0006.scriptf
     */
    public void defaultDfdgrpCbsMaxCur(Dftcre dftcreVo) {
        if (!dftcreVo.getDfdgrp().getCbs().getMax().isModified("cur")) {
            //if (MdaUtils.compareTo(SettleContext.getDirectTransName(), "BRTSET") != 0 && MdaUtils.compareTo(SettleContext.getDirectTransName(), "BCTSET") != 0) {
                dftcreVo.getDfdgrp().getCbs().getMax().setCur(dftcreVo.getOricur());
                dftcreVo.getDfdgrp().getCbs().getOpn1().setCur(dftcreVo.getOricur());
                dftcreVo.getDfdgrp().getRec().setRescur(dftcreVo.getOricur());
            //}
        }
    }

    /**
     * source:dftcre.0009.script
     */
    public void defaultExtrat(Dftcre dftcreVo) {
        BigDecimal rat = null;
        BigDecimal sqrrat = null;
        BigDecimal ret = null;
        if (MdaUtils.compareTo(dftcreVo.getOricur(), dftcreVo.getDfdgrp().getCbs().getMax().getCur()) != 0) {
            if (!dftcreVo.isModified("extrat")) {
                rat = new BigDecimal("0.00");
                sqrrat = new BigDecimal("0.00");
                Argument<BigDecimal> ratBox = new Argument<BigDecimal>("", rat);
                Argument<BigDecimal> sqrratBox = new Argument<BigDecimal>("", sqrrat);
                xrtmodService.getRateXrt(dftcreVo.getOricur(), dftcreVo.getDfdgrp().getCbs().getMax().getCur(), false, "S", Dates.today(), ratBox, sqrratBox);

                rat = ratBox.value;
                sqrrat = sqrratBox.value;

                ret = rat;
            } else {
                ret = dftcreVo.getExtrat();
            }
        } else {
            ret = new BigDecimal("1.00");
            dftcreVo.resetModified("extrat");
        }
        dftcreVo.setExtrat(ret);
    }

    /**
     * source:dftcre.0016.script
     */
    public void defaultDfdgrpRecTrntyp(Dftcre dftcreVo) {
        if (MdaUtils.isEmpty(dftcreVo.getDfdgrp().getRec().getTrntyp())) {
            String typ = Strings.mid(SettleContext.getTransName(), 1, 2);
            if (MdaUtils.compareTo(typ, "TR") == 0) {
                dftcreVo.getDfdgrp().getRec().setTrntyp("CP");
            } else if (MdaUtils.compareTo(typ, "BP") == 0) {
                if (MdaUtils.compareTo(dftcreVo.getRec().getPnttyp(), "BED") == 0) {
                    dftcreVo.getDfdgrp().getRec().setTrntyp("BE");
                } else if (MdaUtils.compareTo(dftcreVo.getRec().getPnttyp(), "BOD") == 0) {
                    dftcreVo.getDfdgrp().getRec().setTrntyp("BO");
                } else if (MdaUtils.isEmpty(dftcreVo.getRec().getPnttyp())) {
                    dftcreVo.getDfdgrp().getRec().setTrntyp("CI");
                }
            } else {
                dftcreVo.getDfdgrp().getRec().setTrntyp(typ);
            }
        }
    }

    /**
     * source:dftcre.0018.script
     */
    public String defaultDfdgrpRecNam(Dftcre dftcreVo) {
        String recName="";
        if(dftcreVo.getDfdgrp()!=null && dftcreVo.getDfdgrp().getApl()!=null){
            recName= dftcreVo.getDfdgrp().getApl().getNam();
        }
        dftcreVo.getDfdgrp().getRec().setNam(recName);
        return recName;
        /*String fintyp = codetableService.getTblLabel(dftcreVo.getDfdgrp().getRec().getFintyp(), "DFTFIN");
        if (!dftcreVo.getDfdgrp().getRec().isModified("nam")) {
            String nam = fintyp + " " + dftcreVo.getDfdgrp().getCbs().getMax().getCur() + Utils.fmtAmount(dftcreVo.getDfdgrp().getCbs().getMax().getAmt(), dftcreVo.getDfdgrp().getCbs().getMax().getCur()) + " " + "." + dftcreVo.getDfdgrp().getApl().getNam();
            if (nam.length() > 40) {
                nam = nam.substring(0, 40);
            }
            dftcreVo.getDfdgrp().getRec().setNam(nam);
        }
        return dftcreVo.getDfdgrp().getRec().getNam();*/
    }

    /**
     * source:dftcre.0020.script
     */
    public void defaultInitFields(Dftcre dftcreVo) {
        if (!dftcreVo.getDfdgrp().getRec().isModified("guaflg")) {
            dftcreVo.getDfdgrp().getRec().setGuaflg("0");
        }
        dftcreVo.getDfdgrp().getRec().setIssdat(Dates.today());
        dftcreVo.getDfdgrp().getRec().setOpndat(Dates.today());
    }

    /**
     * source:dftcre.0030.script
     */
    public void defaultDftpPansta(Dftcre dftcreVo) {
        if (!MdaUtils.isEmpty(dftcreVo.getDfflag())) {
            dftcreVo.getDftp().setPansta(PanStaEdit);
        } else {
            dftcreVo.getDftp().setPansta(PanStaShow);
        }
    }

    /**
     * source:dftcre.0034.script
     */
    public void defaultDfdgrpRecInvtyp(Dftcre dftcreVo) {
        String frame = SettleContext.getDirectTransName();
        if (!dftcreVo.getDfdgrp().getRec().isModified("invtyp")) {
            if (StringUtils.isNotEmpty(dftcreVo.getDfflag())) {
                if( MdaUtils.compareTo(frame,"TRTOPN") == 0 || MdaUtils.compareTo(frame,"BPTOPN") == 0) {
                    dftcreVo.getDfdgrp().getRec().setInvtyp(dftcreVo.getRec().getInvtyp());
                } else {
                    dftcreVo.getDfdgrp().getRec().setInvtyp(dftcreVo.getRec().getTrtcreVo().getTrdgrp().getRec().getInvtyp());
                }
            } else {
                dftcreVo.getDfdgrp().getRec().setInvtyp(NULLSTR);
            }
        }
    }

    /**
     * source:dftcre.0015.script
     */
    public void cbsSavDftCre(Dftcre dftcreVo) {
        if (!MdaUtils.isEmpty(dftcreVo.getDfflag())) {
            String fintyp = codetableService.getTblLabel(dftcreVo.getDfdgrp().getRec().getFintyp(), "DFTFIN");
            trnmodService.cbsTrnStore("MAXAMT", "AMT1", Dates.today(), dftcreVo.getDfdgrp().getCbs().getMax().getCur(), dftcreVo.getDfdgrp().getCbs().getMax().getAmt(), Strings.getText("$1 opening", fintyp), dftcreVo.getDfdgrp().getRec(), transactionHelpService.getTrninr());
        }

    }

    /**
     * 同业代付存盘
     *
     * @param dftcreVo
     */
    @Override
    public void saveDftcre(Dftcre dftcreVo) {
        if (!MdaUtils.isEmpty(dftcreVo.getDfflag())) {
            if (StringUtils.isEmpty(dftcreVo.getDfdgrp().getRec().getPntinr())) {
                dftcreVo.getDfdgrp().getRec().setPntinr(dftcreVo.getRec().getObjinr());
            }
            Bch bch = SettleContext.getUserSession().getBch();
            Bch wrkbch = SettleContext.getUserSession().getWrkbch();
            //设置业务表的机构信息
            sysmodService.setRecBchInfo(dftcreVo.getDfdgrp().getRec(), bch, wrkbch);
            dftmodComponent.sav(dftcreVo.getDfdgrp());
            cbsSavDftCre(dftcreVo);
        }
    }
}
