package com.brilliance.isc.common.component;

import com.brilliance.isc.bo.Bch;
import com.brilliance.isc.bo.Dtaret;
import com.brilliance.isc.bo.model.Jsdgrp;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.counter.service.CounterService;
import com.brilliance.isc.common.transaction.help.TransactionHelpService;
import com.brilliance.isc.common.trnmod.service.TrnmodService;
import com.brilliance.isc.common.trnmod.vo.TrnmodVo;
import com.brilliance.isc.mda.dao.DtaretMapper;
import com.brilliance.mda.runtime.mda.IStream;
import com.brilliance.mda.runtime.mda.impl.Argument;
import com.brilliance.mda.runtime.mda.impl.StreamImpl;
import com.brilliance.mda.runtime.mda.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;

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

@Component
public class JstmodComponent {

    @Autowired
    private CounterService counterService;
    @Autowired
    private TrnmodService trnmodService;
    @Autowired
    private TransactionHelpService transactionHelpService;
    @Autowired
    private DtaretMapper dtaretMapper;


    public String getRef(String ownref,String trn) {
        Bch wrkbch = SettleContext.getUserSession().getWrkbch();
        if(MdaUtils.isEmpty(ownref)){
            ownref = generateDefaultRef(trn);
        }
        if ("FWD".equalsIgnoreCase(trn) && Strings.len(Strings.trim(ownref)) != 14) {
            ownref = Strings.mid(ownref,1,13) + wrkbch.getBchflg();
        }
        if (("JH".equalsIgnoreCase(trn) || "SH".equalsIgnoreCase(trn)) && Strings.len(Strings.trim(ownref)) != 13) {
            ownref = Strings.mid(ownref,1,12) + wrkbch.getBchflg();
        }
        return ownref;
    }

    private String generateDefaultRef(String trn) {
        StringBuilder ownRefBufferBuilder = new StringBuilder();
        String branch = getBranchRef();
        // 交易代码 比如 TT
        ownRefBufferBuilder.append(trn);

        // 4位分行编码
        ownRefBufferBuilder.append(branch);

        // 2位年份
        ownRefBufferBuilder.append(Strings.mid(MdaUtils.toString(Dates.getYear(Dates.today()), 4), 3, 2));

        // 5位流水号
        ownRefBufferBuilder.append(MdaUtils.toString(counterService.dbCounter(trn + branch), -4));

        return ownRefBufferBuilder.toString();
    }

    private String getBranchRef() {
        Bch bch = SettleContext.getUserSession().getBch();
        if (bch != null) {
            return bch.getBranch();
        }
        return NULLSTR;
    }



    public void sav(Jsdgrp jsdgrp){
        if(MdaUtils.isEmpty(jsdgrp.getRec().getCredat())) {
            jsdgrp.getRec().setCredat(Dates.today());
        }
        String frm = SettleContext.getTransName();
        if(MdaUtils.compareTo(frm,"JSTOPN") == 0){
            jsdgrp.getRec().setCredat(Dates.today());
        }
        trnmodService.trnStoreContract(jsdgrp);
        Dtaret dtaret = jsdgrp.getDtaret();
        dtaret.setOwnref(jsdgrp.getRec().getOwnref());
        dtaret.setObjtyp("JSD");
        dtaret.setObjinr(jsdgrp.getRec().getInr());
        // TODO 待确认，找卓燊
//        this.getJsdgrp().getDtaret().setTrninr( ctx.absGet(Trnmod.class).getTrn().getInr());
        TrnmodVo trnmodVo = transactionHelpService.getTransactionStoreSet().getTrnmodVo();
        dtaret.setTrninr(trnmodVo.getTrn().getInr());
        if(MdaUtils.compareTo(frm,"JSTOPN") == 0){
            if(MdaUtils.compareTo(jsdgrp.getRec().getMaimpz(),"3") == 0){
                dtaret.setDxuhao("0");
                String dtaretInr0 = counterService.dbCounterFormat("DTARET");
                dtaret.setInr(dtaretInr0);
                dtaretMapper.insert(dtaret);

                dtaret.setDxuhao("1");
                String dtaretInr1 = counterService.dbCounterFormat("DTARET");
                dtaret.setInr(dtaretInr1);
                dtaretMapper.insert(dtaret);
            } else {
                dtaret.setDxuhao("0");
                dtaret.setYewubh(jsdgrp.getRec().getYewubh());
                String dtaretInr = counterService.dbCounterFormat("DTARET");
                dtaret.setInr(dtaretInr);
                dtaretMapper.insert(dtaret);
            }
        } else {
            dtaret.setDxuhao(jsdgrp.getRec().getDiaoqi());
            dtaret.setYewubh(jsdgrp.getRec().getYewubh());
            String dtaretInr = counterService.dbCounterFormat("DTARET");
            dtaret.setInr(dtaretInr);
            dtaretMapper.insert(dtaret);
        }
    }

    public BigDecimal getcshpct(Jsdgrp jsdgrp){
        //设置保证金应收比例
        BigDecimal ret = new BigDecimal("0");
        Date from = null;
        Date till = null;
        if((MdaUtils.compareTo(jsdgrp.getRec().getMaimpz(),"1") == 0 || MdaUtils.compareTo(jsdgrp.getRec().getMaimpz(),"4") == 0 || MdaUtils.compareTo(jsdgrp.getRec().getMaimpz(),"5") == 0 ) && jsdgrp.getRec().getOpndat() != jsdgrp.getRec().getQixiri()){
            ret = Strings.parseDecimal(Strings.trim(Codetables.getCodetableLabelOfTd("J1","BZJBL",Systems.getLang())));
        } else {
            if(MdaUtils.compareTo(jsdgrp.getRec().getMaimpz(),"2") == 0 || MdaUtils.compareTo(jsdgrp.getRec().getMaimpz(),"3") == 0 || MdaUtils.compareTo(jsdgrp.getRec().getMaimpz(),"6") == 0 || MdaUtils.compareTo(jsdgrp.getRec().getMaimpz(),"7") == 0){
                if(MdaUtils.compareTo(jsdgrp.getRec().getMaimpz(),"3") == 0){
                    from = jsdgrp.getRec().getOpndat();
                    till = jsdgrp.getBlk().getQixiri();
                } else {
                    from = jsdgrp.getRec().getOpndat();
                    till = jsdgrp.getRec().getQixiri();
                }
                // TODO 保证金
//                ret = ctx.absGet(Liaall.class).getLiaccv().getcshpct(from, till);
            }
        }
        return  ret;

    }
    public HashMap<String,String> split8091Data(String rtntext){
        HashMap<String, String> result = new HashMap<>();
        //!分割核心返回的字符串，获得客户号和科目代码
        //!==================================================
        //!返回值：业务代号
        //!变量:   8091核心返回值
        //!==================================================
        String fgf = "|+|";
        //0交易名
        int start = 1;                                     //起始位置
        int len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1; //截取的长度
        String jiaoym = Strings.mid(rtntext,start,len);
        //1账号
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String zhangh = Strings.mid(rtntext,start,len);
        //2账户中文名
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String zhuzwm = Strings.mid(rtntext,start,len);
        //3客户中文名
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String kehzwm = Strings.mid(rtntext,start,len);
        //4科目存储
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String kemucc = Strings.mid(rtntext,start,len);
        //5主账号
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String zhuzzh = Strings.mid(rtntext,start,len);
        //6营业机构号
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String yngyjg = Strings.mid(rtntext,start,len);
        //7机构中文名称
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String jigomc = Strings.mid(rtntext,start,len);
        //8账务机构号
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String zhngjg = Strings.mid(rtntext,start,len);
        //9货币代号
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String huobdh = Strings.mid(rtntext,start,len);
        //10业务代号
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String yewudh = Strings.mid(rtntext,start,len);
        String kmdm = yewudh;
        //11账号序号
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String zhaoxh = Strings.mid(rtntext,start,len);
        //12客户号
        start = start + len + 3;
        len = Strings.pos(Strings.mid(rtntext,start),fgf) - 1;
        String kehhao = Strings.mid(rtntext,start,len);
        String khh = kehhao;
        result.put("khh",khh);
        result.put("kmdm",kmdm);
        return result;
    }

    public String get8091InterfaceData(String sndAct){
        //!调用核心交易获取返回数据
        //!SndAct 输入的账号
        //!返回数据
        String rtnText = "";
        String sndStr = "";
        sndStr = Strings.trim(sndAct) + "|" + "|||";
        IStream stream = new StreamImpl();
        Streams.streamSet(stream,sndStr);
        String vrtnText = "";
        Argument<String> vrtnTextBox = new Argument<String>();
        // TODO 调用8091接口
//        BigDecimal rtn = ctx.absGet(Sysmod.class).callInterfaceStream ( "SELACT", "8091", stream, vrtnTextBox );
        BigDecimal rtn = Decimals.ZERO_SCALE0;
        if(MdaUtils.compareTo(rtn,0) != 0){
            // TODO 抛异常？还是return？
//            ctx.setErrorMessage(MdaUtils.getI18NString("jstmod","CT000000"));
//            MdaUtils.exitRule();
            return "exception";
        } else {
            if(!MdaUtils.isEmpty(vrtnText)){
                rtnText = vrtnText;
            } else {
                // TODO 抛异常？还是return？
//                ctx.setMessage(MdaUtils.getI18NString("jstmod","CT000001"));
//                MdaUtils.exitRule();
                return "exception";
            }
        }
        return rtnText;
    }

    public String get8091RtntextData(String rtntext,int posi) {
        //!获取Rtntext 指定位置的数据域
        //!===================================
        //!返回值: $Data   数据域内容
        //!变量:   Rtntext  调用8091交易返回信息
        //!        Posi    数据域位置(第Posi个数据)
        //!===================================
        String data = "";
        String vrtntext = rtntext;
        String sep = "|+|";
        int pos = 0;
        for(int  i = 1;i <= posi - 1;i++){
            pos = Strings.pos(vrtntext,sep);
            vrtntext = Strings.mid(vrtntext,pos + 3);
        }
        pos = Strings.pos(vrtntext,sep);
        data = Strings.mid(vrtntext,1,pos - 1);
        return data;
    }

}
