package com.brilliance.isc.common.txnhold.handler;


import cn.hutool.core.lang.Assert;
import com.brilliance.mda.runtime.mda.util.Dates;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.isc.bo.Atp;
import com.brilliance.isc.bo.Bch;
import com.brilliance.isc.bo.Spt;
import com.brilliance.isc.bo.Trn;
import com.brilliance.isc.common.component.PtsptaToolComponent;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.quemod.service.QuemodService;
import com.brilliance.isc.common.sysmod.SysmodService;
import com.brilliance.isc.common.transaction.help.TransactionHelpService;
import com.brilliance.isc.common.transaction.help.TransactionServiceSet;
import com.brilliance.isc.common.transaction.txnhold.service.TxnHoldService;
import com.brilliance.isc.common.transaction.txnhold.vo.TxnHoldVo;
import com.brilliance.isc.common.transaction.vo.BaseTransactionVo;
import com.brilliance.isc.common.transaction.vo.TrnInfo;
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.QueMapper;
import com.brilliance.isc.mda.dao.SptMapper;
import com.brilliance.isc.mda.dao.TrnMapper;
import com.brilliance.isc.mda.dao.UsgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

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

@Component
public class MtabutTxnHoldHandler implements ITxnHoldHandler {

    @Autowired
    private TxnHoldService txnHoldService;

    @Autowired
    private SysmodService sysmodService;

    @Autowired
    private QuemodService quemodService;

    @Autowired
    private TransactionHelpService transactionHelpService;

    @Autowired
    private TrnmodService trnmodService;

    @Autowired
    private TrnMapper trnMapper;

    @Autowired
    private QueMapper queMapper;

    @Autowired
    private SptMapper sptMapper;

    @Autowired
    private UsgMapper usgMapper;

    @Resource
    private PtsptaToolComponent ptsptaToolComponent;

    /**
     * Mtabut.HandleInterruptTransactionZZZZ
     *
     * @param txnHoldVo
     */
    @Override
    public void handleInterruptTransaction(TxnHoldVo txnHoldVo) {
        // set \\SYSMOD\\OBJNAM by posting xxTMOD.SetObjNam
        Object rec = transactionHelpService.getTransactionStoreSet().getRec();
        TransactionServiceSet transactionStoreSet= transactionHelpService.getTransactionStoreSet();
        BaseTransactionVo transactionVo = txnHoldVo.getBaseTransactionVo();
        Spt spt = transactionVo.getSpt();
        if(spt!=null && StringUtils.isNotEmpty(spt.getInr())){
            spt=sptMapper.selectByPrimaryKey(spt);
        }
        String objName = sysmodService.internalSetObjNam(rec, transactionVo);
        String transName = SettleContext.getTransName();
        String sptSta = NULLSTR;
        String pntInr = NULLSTR;
        String pntTyp = NULLSTR;
        String recName = ptsptaToolComponent.getCustomerName(transName,transactionStoreSet.getRec(),transactionStoreSet.getPtsList());
        Assert.notNull(spt);
        spt.setCtmnam(recName);
        if (!"INF".equals(getTrn1()) && !"SEL".equals(getTrn2()) && !"TRNREL".equals(transName)) {
            //ctx.absGet(Trnmod.class).troFree();
            if (spt != null && sysmodService.sptIsExeLoaded(spt.getSta())) {
                sptSta = "COR";
                /*Streams.streamClear(sptStr);
                Platform.sptGetLoadDataStream(sptStr);
                if( MdaUtils.isEmpty(ctx.absGet(Sysmod.class).getSptdata()) ) {
                    Streams.streamSet(ctx.absGet(Sysmod.class).getSptdata(),sptStr);
                } else {
                    Streams.streamInsert(ctx.absGet(Sysmod.class).getSptdata(),0,sptStr);
                }*/
            } else {
                if (spt != null && sysmodService.sptIsAnyLoaded(spt.getSta())) {
                    updateOriginalTRN(spt);
                }
                sptSta = SptAfterBreak;
                //这里改造不需要Istream存盘数据，直接把BaseTransactionVo jackson序列化就行
                /*if(!MdaUtils.isEmpty(ctx.absGet(Trnmod.class).getBimdata()) ) {
                    if( MdaUtils.isEmpty(ctx.absGet(Sysmod.class).getSptdata()) ) {
                        Streams.streamSet(ctx.absGet(Sysmod.class).getSptdata(),ctx.absGet(Trnmod.class).getBimdata());
                    } else {
                        Streams.streamInsert(ctx.absGet(Sysmod.class).getSptdata(),0,ctx.absGet(Trnmod.class).getBimdata());
                    }
                    // As streams are now saved on savedata the not necessary ones should be deleted
                    Streams.streamClear(ctx.absGet(Trnmod.class).getBimdata());
                }
                Platform.sptSaveDataRoot();*/
                Atp atp = SettleContext.getUserSession().getAtp();
                Bch bch = SettleContext.getUserSession().getBch();
                Bch workBch = SettleContext.getUserSession().getWrkbch();
                Bch hldbch = SettleContext.getUserSession().getHldbch();
                //USG弃用
            /*    Usg usg = null;
                List<Usg> usgList = usgMapper.getUsgByEtyextkey(SettleContext.getUserEty().getExtkey());
                if (usgList != null && usgList.size() > 0) {
                    usg = usgList.get(0);
                }*/
                //>>>---------业务经办行-----------
                //if IsEmpty( \\SYSMOD\\SPT\\BCHKEYINR ) then
                Assert.notNull(spt);
                spt.setBchkeyinr(hldbch.getInr());
                /**
                 $bchkey = getProcessBCHKEY
                 \\SYSMOD.Getxxdfields ( "BCH", "INR", $bchkey, "Y", \\SYSMOD\\SPT\\BCHKEYINR )
                 **/
                //endif
                //<<< ZL-----------------------------------------------
                //>>>---------业务所属行----------
                Assert.notNull(spt);
                if (MdaUtils.isEmpty(spt.getBranchinr())) {
                    spt.setBranchinr(workBch.getInr());
                }
                //>>>---------收单行上收业务的BREAK时候的标志----------
//                ("X".equals(atp.getNegflg()) && "X".equals(usg.getCusmgrflg()))
                Assert.notNull(spt);
                if(sysmodService.isIncomingSptsta(spt.getSta())) {
                    sptSta=spt.getSta();
                }else{
                    if (("X".equals(atp.getNegflg()))
                            || ("X".equals(atp.getNegflg()) && !bch.getBchkey().equals(bch.getBranch())
                            && StringUtils.isNotEmpty(bch.getBranch()))) {
                        sptSta = "CMB";
                    }
                }
                Assert.notNull(spt);
                spt.setCredat(Dates.today());
                if (!"TRN".equals(spt.getObjtyp())
                        || ("TRN".equals(spt.getObjtyp()) && StringUtils.isEmpty(spt.getObjinr()))) {
                    spt.setObjtyp(Utils.recGetObj(rec));
                    spt.setObjinr(Utils.recGetInr(rec));
                }
                /**
                 //国内信用证的typ不同
                 $frm = Mid( GetFramename, 1, 2 )
                 if $frm == "DI" or $frm == "DE" or $frm == "BD" or $frm == "BF" then
                 \\SYSMOD\\SPT\\OBJTYP = $frm + "D"
                 endif
                 **/
                Trn trn = new Trn();
                trnmodService.setWfsAmount(trn);
                Assert.notNull(spt);
                spt.setRelamt(trn.getReloriamt());
                spt.setRelcur(trn.getReloricur());
                //防止重复到单号，因此在spt表中存入单据号
                String ref = Utils.getFieldValue(rec, "ownref");
                if (StringUtils.isNotEmpty(ref)) {
                    Assert.notNull(spt);
                    spt.setOwnref(ref);
                }
                TrnInfo trnInfo = transactionVo.getTrnInfo();
                if (trnInfo != null ) {
                    Assert.notNull(spt);
                    spt.setImginr(trnInfo.getImginr());
                }
                String paytyp = Utils.getFieldValue(rec, "paytyp");
                if (StringUtils.isNotEmpty(paytyp) && paytyp.length() == 1) {
                    //\\SYSMOD\\SPT\\IMGINR = $paytyp
                    //汇款交易存汇入还是汇出
                    Assert.notNull(spt);
                    spt.setPaytyp(paytyp);
                }
                //国内证使用flg202存储国内证标志
                String dflg = Utils.getFieldValue(rec, "dflg");
                if (StringUtils.isNotEmpty(dflg)) {
                    Assert.notNull(spt);
                    spt.setFlg202(dflg);
                }
                String frm = transName.substring(0, 2);
                switch (frm) {
                    case "BD":
                    case "BF":
                        spt.setFlg202("D");
                        break;
                    case "TR":
                        //---DZTEST---
                        dflg = Utils.getFieldValue(transactionVo, "lidgrp\\rec\\dflg");
                        if (StringUtils.isEmpty(dflg)) {
                            dflg = Utils.getFieldValue(transactionVo, "didgrp\\rec\\dflg");
                        }
                        if ("D".equals(dflg)) {
                            spt.setFlg202("D");
                        }
                        break;
                    case "BP":
                        dflg = Utils.getFieldValue(transactionVo, "ledgrp\\rec\\dflg");
                        if (StringUtils.isEmpty(dflg)) {
                            dflg = Utils.getFieldValue(transactionVo, "dedgrp\\rec\\dflg");
                        }
                        if ("D".equals(dflg)) {
                            spt.setFlg202("D");
                        }
                        break;
                    default:
                }
                if (StringUtils.isEmpty(spt.getObjinr())) {
                    //---DZTEST---
                    if (!"LTD".equals(Utils.recGetObj(rec))) {
                        pntInr = Utils.getFieldValue(rec, "pntinr");
                        pntTyp = Utils.getFieldValue(rec, "pnttyp");
                    } else {
                        // LTD has always as Parent LED
                        pntInr = Utils.getFieldValue(rec, "ledinr");
                        pntTyp = "LED";
                    }
                    if (!MdaUtils.isEmpty(pntInr) && !MdaUtils.isEmpty(pntTyp)) {
                        spt.setObjtyp(pntTyp);
                        spt.setObjinr(pntInr);
                    }
                }
            }
            // write ORD when activated
            trnmodService.trnORDBreak(spt, objName,transactionVo);
            spt.setDelflg(NULLSTR);
            sysmodService.sptSaveEntry(spt, rec, sptSta, transactionVo, objName);
             //更新暂存的que 的渠道
//            TrnmodVo trnmod =transactionHelpService.getTransactionStoreSet().getTrnmodVo();
//            if(trnmod.getSpt()!=null) {
//                Que que = queMapper.selectByObjtypAndObjinr("SPT", spt.getInr());
//                String channel = sysmodService.getChannelFromSta(trnmod.getSpt().getSta());
//                que.setChannel(channel);
//                que.setMsgtyp(trnmod.getSpt().getMsgtyp());
//                sysmodService.sdbUpdate(que);
//            }
            sysmodService.sweSaveEntry(null, spt, "PEN", spt.getInr(), "");
        }
    }

    /**
     * mtabut init200
     *
     * @return
     */
    private String getTrn1() {
        if (StringUtils.isNotEmpty(SettleContext.getTransName())) {
            return SettleContext.getTransName().substring(0, 3);
        }
        return null;
    }

    /**
     * mtabut init200
     *
     * @return
     */
    private String getTrn2() {
        if (StringUtils.isNotEmpty(SettleContext.getTransName())) {
            return SettleContext.getTransName().substring(3);
        }
        return null;
    }

    /**
     * source:mtabut.0029.script
     */
    public void updateOriginalTRN(Spt spt) {
        // Set RELFLG of the transaction that was loaded via SPT to `Picked Up`
        if (spt != null
                && StringUtils.isNotEmpty(spt.getInr())
                && !sysmodService.sptIsExeLoaded(spt.getSta())) {
            if ("TRN".equals(spt.getObjtyp())
                    && StringUtils.isNotEmpty(spt.getObjinr())) {
                trnMapper.updateTrnRelflag(spt.getObjinr(), "P");
            }
        }
    }
}
