package com.brilliance.isc.common.bop.cfa.cfagit.service.impl;

import com.brilliance.mda.runtime.mda.util.*;
import com.brilliance.isc.bo.Cfaerr;
import com.brilliance.isc.bo.model.Cfagit;
import com.brilliance.isc.common.bop.cfa.cfagit.service.CfaDependService;
import com.brilliance.isc.counter.service.SerialCounterService;
import com.brilliance.isc.mda.dao.CfacouMapper;
import com.brilliance.isc.mda.dao.CfaerrMapper;
import com.brilliance.isc.vo.lg.GidBizAmdInfoVo;
import com.brilliance.isc.vo.lg.NidBizAmdInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

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

/**
 * @author yangxd
 * @version 1.0
 * @description:
 * @data 2023/7/10 15:37
 */
@Service
public class CfaDependServiceImpl implements CfaDependService {

    @Resource
    CfacouMapper cfacouMapper;
    @Resource
    CfaerrMapper cfaerrMapper;
    @Autowired
    private SerialCounterService serialCounterService;

//    private Cfagit cfagit = null;

    private static ThreadLocal<Cfagit> cfagitVar = new ThreadLocal<>();

    @Override
    public void setCfagitPro(Cfagit cfagitv) {
//        cfagit = cfagitv;
        if (MdaUtils.isEmpty(cfagitv)) {
            logger.error("Cfagit空对象");
        }
        cfagitv.reset();
        cfagitVar.set(cfagitv);
    }

    @Override
    public void getCfaReference(String cfatyp, Date reldat)
    {
        Cfagit cfagit = cfagitVar.get();
        //待确定
        String objtyp = Codetables.getCodeTableKeyOfTd(cfatyp,"CFACOD", Systems.getLang());
        String decnum = cfagit.getRecgrp().getBas().getGuarantorcode();
        String ref = NULLSTR;
        if( MdaUtils.isEmpty(cfagit.getRecgrp().getBas().getExguarancode()) || ( ! MdaUtils.isEmpty(cfagit.getRecgrp().getBas().getExguarancode()) && ! validReference( cfatyp, cfagit.getRecgrp().getBas().getContractdate() ) ) )
        {
            ref = getCFARef ( reldat, objtyp, decnum, false, "" );
            if( ! MdaUtils.isEmpty(ref) )
            {
                cfagit.getRecgrp().getBas().setExguarancode( ref);
            }
            if( MdaUtils.isEmpty(ref) )
            {
                MdaUtils.exitRule();
            }
        }
        /**
         //清空履约编号，防止repair操作时，履约编号有问题
         $vrfcnt = GridCount( RECGRP\\VRF )
         for $i = 1 to $vrfcnt
         Clear( RECGRP\\VRF( $i )\\COMPLIANCENO )
         nex**/
    }

    @Override
    public String getChangeNo(String rptno) {
        int counum = dbCFACounter( rptno, Strings.parseDate("01/01/2012") );
        String couVal = MdaUtils.toString(counum,-4);
        return couVal;
    }

    @Override
    public String getCFARef(Date dat, String typ, String decnum, boolean valid, String validref) {
        //!生成正式流水号
        //!===================================
        //!        Dat 生成流水号的日期
        //!        Typ 业务类型
        //!	  OwnExtKey 地区机构号
        //!        valid  验证编号标志
        //!        validref 待验证编号
        //!===================================
        String couVal = NULLSTR;
        String couNam = NULLSTR;
        int counum = 0;
        if( valid )
        {
            //$CouVal = "000000"
            couVal = Strings.mid(validref,23,6);
        }
        else
        {
            couNam = typ + decnum;
            counum = dbCFACounter( couNam, dat );
            while( MdaUtils.compareTo(Decimals.mul(Numerics.round(Decimals.div(counum,100),0),100),counum) == 0 )
            {
                counum = dbCFACounter( couNam, dat );
            }
            couVal = MdaUtils.toString(counum,-6);
        }
        //$bopref = Typ + Decnum + FmtDate( Dat, "YYYYMMDD" ) + $CouVal
        String bopref = typ + decnum + Formats.format(dat,"YYYYMMDD") + cfaMapNumber( couVal, typ, valid );
        return bopref;
    }

    @Override
    public void setCFAERRSta(Cfagit cfagitv, String objTyp, String instyp,int numOfList) {
        //若是error数据,更改cfaerr中sta状态
        String bussno = "";
        String errinr = "";
//        Argument<String> _errinrBox = Argument.box(errinr);
        String rptno = NULLSTR;
        String changeno = NULLSTR;
        switch( objTyp )
        {
            //注释掉的是二期需要处理的，后续维护
//            case "EAD":
//            case  "EAF":
//                rptno = Datas.getContent(this,MdaDriver.getModuleInfo(recmod,2) + "\\EXDEBTCODE");
//                switch( instyp )
//                {
//                    case "BAS":
//                        bussno = rptno;
//                        break;
//                    case "DCL":
//                        changeno = Datas.getContent(this,MdaDriver.getModuleInfo(recmod,2) + "\\CHANGENO");
//                        bussno = rptno + "," + changeno;
//                        break;
//                }
//                break;
            case "EBA":
                rptno = cfagitv.getRecgrp().getBas().getExguarancode();
                switch( instyp )
                {
                    case "BAS":
                    case  "DCL":
                        bussno = rptno;
                        break;
                    case "VRF":
                        changeno = cfagitv.getRecgrp().getVrf().get(numOfList).getComplianceno();
                        bussno = rptno + "," + changeno;
                        break;
                }
                break;
//            case "ECA":
//                rptno = Datas.getContent(this,MdaDriver.getModuleInfo(recmod,2) + "\\DOFOEXLOCODE");
//                switch( instyp )
//                {
//                    case "BAS":
//                        bussno = rptno;
//                        break;
//                    case "DCL":
//                        changeno = Datas.getContent(this,MdaDriver.getModuleInfo(recmod,2) + "\\CHANGENO");
//                        bussno = rptno + "," + changeno;
//                        break;
//                }
//                break;
        }
        Cfaerr cfaerr = cfaerrMapper.selectByRptno(bussno);
//        String selsql = "select inr from cfaerr where rptno = '" + bussno + "'";
//        ctx.getDaoSession().dbExecuteSQL(selsql);
//        int err = 0;
//        if( ctx.getErrorCode() <= 0 )
//        {
//            ctx.getDaoSession().dbFetchFields("",_errinrBox);
//            errinr = _errinrBox.value;
//            err = ctx.getErrorCode();
//        }
        String updsql = NULLSTR;
        int error = 0;
        if( ! MdaUtils.isEmpty(cfaerr) )
        {
//            updsql = "update cfaerr set sta = 'D' where rptno = '" + bussno + "'";
            cfaerrMapper.updateByRptno(bussno);
        }
    }

    @Override
    public void setAmeAmtAndExpDat(Cfagit cfagit) {
        BigDecimal ameamt = Decimals.ZERO_SCALE2;
        BigDecimal newAmt = Decimals.ZERO_SCALE2;
        Date oldExpDat = NULLDATE;
        Date newExpDat = NULLDATE;
        String transName = cfagit.getTransName().toUpperCase();
        String matchStr = Strings.mid(transName,4,3);
        if(matchStr.equals("AME")) {
            switch (Strings.mid(transName, 1, 2)) {
                case "GI":
                    if (null != cfagit.getAmdRec()) {
                        GidBizAmdInfoVo cfagitAmdRec = (GidBizAmdInfoVo) cfagit.getAmdRec();
                        ameamt = cfagitAmdRec.getAmeamt();
                        newAmt = cfagitAmdRec.getNewamt();
                        oldExpDat = cfagitAmdRec.getOldExpDat();
                        newExpDat = cfagitAmdRec.getNewexpdat();
                    }
                    break;
                case "NI":
                    if (null != cfagit.getAmdRec()) {
                        NidBizAmdInfoVo cfagitAmdRec = (NidBizAmdInfoVo) cfagit.getAmdRec();
                        ameamt = cfagitAmdRec.getAmeamt();
                        newAmt = cfagitAmdRec.getNewamt();
                        oldExpDat = cfagitAmdRec.getOldExpDat();
                        newExpDat = cfagitAmdRec.getNewexpdat();
                    }
                    break;
            }

            if (ameamt.doubleValue() < 0 && newExpDat.getTime() > oldExpDat.getTime()) {
                cfagit.getRecgrp().getBas().setGuaranamount(newAmt.subtract(ameamt));
            }
            if (ameamt.doubleValue() > 0 && newExpDat.getTime() < oldExpDat.getTime()) {
                cfagit.getRecgrp().getBas().setMaturity(oldExpDat);
            }
        }
        return;

    }

    private boolean validReference(String cfatyp,Date reldat)
    {
        Cfagit cfagit = cfagitVar.get();
        //!校验业务编号
        if( MdaUtils.isEmpty(cfagit.getRecgrp().getBas().getExguarancode()) )
        {
            return  false;
        }
        String objtyp = Codetables.getCodeTableKeyOfTd(cfatyp,"CFACOD",Systems.getLang());
        String decnum = cfagit.getRecgrp().getBas().getGuarantorcode();
        //$ref = CFAREF.GetCFARef ( reldat, $objtyp, $decnum, FALSE, "" )
        String ref = getCFARef( reldat, objtyp, decnum, true, cfagit.getRecgrp().getBas().getExguarancode() );
        int vrfcnt = 0;
        if( MdaUtils.compareTo(ref,cfagit.getRecgrp().getBas().getExguarancode()) == 0 )
        {
            return  true;
        }
        else
        {
            //清空履约编号，防止repair操作时，履约编号有问题
            int count = cfagit.getRecgrp().getVrf().size();
            for(int  i = 1;i <= vrfcnt;i++)
            {
                cfagit.getRecgrp().getVrf().get(i).setComplianceno(NULLSTR);
            }
            return  false;
        }
    }

    /**
      * @description
      * @param
      * @return
      */
    private String cfaMapNumber(String bnno,String typ,boolean valid)
    {
        //!按照外管规定生成申报号码的后六位
        //!===================================
        //!
        //!返回值：业务流水号的后六位
        //!变量：  bnno  获取的流水号(6位)
        //!        typ 业务编号的类型
        //!
        //!===================================
        String str = " ";
        String returnstr = "";
        if( !valid )
        {
            switch( typ )
            {
                case "82":  //ECA
                    returnstr = "9" + Strings.mid(bnno,2,5);
                    break;
                default:
                    returnstr = bnno;
            }
        }
        else
        {
            returnstr = bnno;
        }
        return returnstr;
    }

    private int dbCFACounter(String counam,Date dat)
    {
        //!按照当日方式获取流水号函数
        //!===================================
        //!返回值：返回的当日流水号
        //!变量：  counam  流水号的类型值
        //!        dat 获取流水号的日期
        //!备注:函数中使用了DBCommit ，应在整个事务开始之前调用该函数
        //!===================================
        return dbcounterCFACou( counam, dat );
    }

    private int dbcounterCFACou(String counam,Date dat)
    {
        String vcounam = Strings.trim(counam);
        return (int) serialCounterService.genSerialNumberByDb("cfacou",vcounam,dat);
        /*Cfagit cfagit = cfagitVar.get();
        //对mac码计数用
        //数据存储在cfacou中
        String vcounam = Strings.trim(counam);
        int count = 0;
        int cou = 0;
        //查询当前mac码的统计数值
//        MdaUtils.clear(cfagit.getCfaref().getCfacou());
        cfagit.getCfaref().getCfacou().setCounam( counam);
        cfagit.getCfaref().getCfacou().setCoudat( dat);
        //DBRead( CFACOU, counam, "COUNAM", dat, "COUDAT" )
        Cfacou cfacouDb = cfacouMapper.selectByCouPro(cfagit.getCfaref().getCfacou());
//        if(MdaUtils.isEmpty(cfacouMapper.selectByCouPro(cfagit.getCfaref().getCfacou())))
        if(MdaUtils.isEmpty(cfacouDb))
        {
            cfagit.getCfaref().getCfacou().setCoudat( dat);
            cfagit.getCfaref().getCfacou().setCounam( counam);
            cfagit.getCfaref().getCfacou().setCoustp( 1);
            cfagit.getCfaref().getCfacou().setCouval( 1);
            cfacouMapper.insert(cfagit.getCfaref().getCfacou());
        }
        else
        {
//            cfagit.getCfaref().getCfacou().setCouval( cfagit.getCfaref().getCfacou().getCouval() + cfagit.getCfaref().getCfacou().getCoustp());
            cfagit.getCfaref().getCfacou().setCoustp(cfacouDb.getCoustp());
            cfagit.getCfaref().getCfacou().setCouval( cfacouDb.getCouval() + cfacouDb.getCoustp());
            cfacouMapper.updateByCouPro(cfagit.getCfaref().getCfacou());
        }

        count = (int)cfagit.getCfaref().getCfacou().getCouval();
        return count;*/
    }
}
