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

import com.brilliance.mda.runtime.mda.util.*;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import com.brilliance.isc.bo.*;
import com.brilliance.isc.bo.model.Cfagit;
import com.brilliance.isc.bo.model.Eblmod;
import com.brilliance.isc.common.api.bch.service.BchService;
import com.brilliance.isc.common.bopset.service.EblmodService;
import com.brilliance.isc.common.component.PtsptaToolComponent;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.sysmod.SysmodService;
import com.brilliance.isc.common.transaction.help.TransactionHelpService;
import com.brilliance.isc.common.vo.PtsptaVo;
import com.brilliance.isc.counter.service.SerialCounterService;
import com.brilliance.isc.mda.dao.*;
import com.brilliance.isc.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

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

/**
 * @author yangxd
 * @version 1.0
 * @description:
 * @data 2023/6/9 10:37
 */
@Service
public class EblmodServiceImpl implements EblmodService {

    private final Logger log = LoggerFactory.getLogger(EblmodServiceImpl.class);

    @Autowired
    private TransactionHelpService transactionHelpService;

    @Autowired
    private TrnMapper trnMapper;

    @Autowired
    private BchService bchService;

    @Autowired
    private PtsptaToolComponent ptsptaToolComponent;

    @Autowired
    private PtyMapper ptyMapper;

    @Resource
    CfaerrMapper cfaerrMapper;

    @Autowired
    CfacouMapper cfacouMapper;

    @Autowired
    EblMapper eblMapper;

    @Autowired
    SysmodService sysmodService;

    @Autowired
    SerialCounterService serialCounterService;


    @Override
    public void setEblData(Cfagit cfagit,String typeOfCfa, Date relDate) {
        //!设置控制表EBL的数据
        //!===================================
        //!变量：  path    pancel存取路径
        //!        objtyp  处理的对象名
        //!===================================
        if(!MdaUtils.isEmpty(transactionHelpService.getTrninr()) )
        {
            cfagit.getEblmod().getEbl().setTrninr(transactionHelpService.getTrninr());
        }
        cfagit.getEblmod().getEbl().setOwnusr(SettleContext.getUserSession().getUsr().getExtkey());
        cfagit.getEblmod().getEbl().setCredat(Dates.today());
        cfagit.getEblmod().getEbl().setCretim(Dates.now());
        cfagit.getEblmod().getEbl().setObjtyp(typeOfCfa);
        cfagit.getEblmod().getEbl().setReldat(relDate);
    }

    @Override
    public void setEblData(Eblmod eblmod, String typeOfCfa, Date relDate) {
        //!设置控制表EBL的数据
        //!===================================
        //!变量：  path    pancel存取路径
        //!        objtyp  处理的对象名
        //!===================================
        if(!MdaUtils.isEmpty(transactionHelpService.getTrninr()) )
        {
            eblmod.getEbl().setTrninr(transactionHelpService.getTrninr());
        }
        eblmod.getEbl().setOwnusr(SettleContext.getUserSession().getUsr().getExtkey());
        eblmod.getEbl().setCredat(Dates.today());
        eblmod.getEbl().setCretim(Dates.now());
        eblmod.getEbl().setObjtyp(typeOfCfa);
        eblmod.getEbl().setReldat(relDate);
    }

    @Override
    public void setRecordSig(Cfagit cfagit,String iRec) {
    if (cfagit.getEblmod().getDectyp().equals("S"))
        cfagit.getEblmod().getCfasig().setEblinr(cfagit.getEblmod().getWrkebl().getInr());
    else
        cfagit.getEblmod().getCfasig().setEblinr(cfagit.getEblmod().getEbl().getInr());
    cfagit.getEblmod().getCfasig().setUsr(MdaUtils.toString(SettleContext.getSessionUserVo().getId()));
    cfagit.getEblmod().getCfasig().setDat(Dates.today());
    cfagit.getEblmod().getCfasig().setTim(Numerics.time());
    cfagit.getEblmod().getCfasig().setSta("");
    cfagit.getEblmod().getCfasig().setTxt(/*"Frame "+*/cfagit.getEblmod().getEbl().getObjtyp() + iRec);
    }

    @Override
    public void setRecordSig(Eblmod eblmod, String iRec) {
        if ("S".equals(eblmod.getDectyp())){
            eblmod.getCfasig().setEblinr(eblmod.getWrkebl().getInr());
        }
        else{
            eblmod.getCfasig().setEblinr(eblmod.getEbl().getInr());
        }

        eblmod.getCfasig().setUsr(MdaUtils.toString(SettleContext.getSessionUserVo().getId()));
        eblmod.getCfasig().setDat(Dates.today());
        eblmod.getCfasig().setTim(Numerics.time());
        eblmod.getCfasig().setSta("");
        eblmod.getCfasig().setTxt("FRAME: "+SettleContext.getTransName() +" "+ iRec);
    }

    @Override
    public boolean isCheckField(String accept, String typ) {
        //!判断当前状态下是否需要进行数据域的检核
        //!===================================
        //!返回值：ture   需要检核
        //!        false  不需要检核
        //!变量：  Accept  用户已确认
        //!        typ 当前交易类型 A新增 C修改 D删除
        //!===================================
        if( !isEmptyVal(accept) && MdaUtils.compareTo(typ,"D") != 0 )
        {
            return  true;
        }
        return false;
    }

    @Override
    public boolean checknoWaitingStaCFA(String trninr) {

        //!检查当前CFA记录交易状态是否为"R"或"C"(UNDO)
        //!===================================
        //!返回值：True   Release
        //!        False  Not Release
        //!变量：  trninr  对应数据的TRNINR
        //!===================================
        String relflg = "";
        if( MdaUtils.isEmpty(trninr) )
        {
            return  true;
        }
        else
        {
            relflg = "R";
            Trn trnTemp = trnMapper.selectByTrninrAndRelflg(trninr,relflg);
            if (MdaUtils.isEmpty(trnTemp))
                return  false;

            if (!trnTemp.getInr().isEmpty())
                return true;
        }

        return false;
    }

    private boolean isEmptyVal(String txt){

        //!判断当前的PANSTA是否为空状态
        //!===================================
        //!返回值：True  为空
        //!        False 非空
        //!变量：  txt PANSTA 状态字 (X  非空，其他字均为空)
        //!===================================
        if( MdaUtils.compareTo(txt,"X") != 0 )
        {
            return  true;
        }
        else
        {
            return  false;
        }
    }

    /**
     * 通过机构编号获取金融机构标识码
     * @param bchcod 机构号
     * @return 金融机构标识码
     */
    @Override
    public String getDecnum(String bchcod)
    {
        String decnum = "";
        Bch bch = bchService.getByBranch(bchcod);
        if(bch != null){
            decnum = bch.getDecnum();
        }
        return decnum;

    }

    /**
     * 通过角色获取 pty 数据
     * @param rol
     * @param ptsList
     * @return
     */
    @Override
    public Pty getPtyFieldsCFA(String frmname,String rol, List<PtsptaVo> ptsList) {
        if(MdaUtils.isEmpty(rol)){
                switch( frmname )
                {
                    case "BCTSET":
                        rol = "DRE";
                        break;
                    case  "TRTOPN":
                    case  "TRTAME":
                        rol = "FIP";
                        break;
                    case  "BPTOPN":
                    case  "BPTAME":
                        rol = "FIA";
                        break;
                    case  "CPTOPN":
                    case  "CPTATO":
                        rol = "ORC";
                        break;
                    default:
                        rol = "APL";
                }
            }
        PtsptaVo ptspta = ptsptaToolComponent.getPtsFromListByRol(ptsList, rol);
        if(!MdaUtils.isEmpty(ptspta)){
            String ptyinr = ptspta.getPtyinr();
            Pty pty = ptyMapper.selectByPtyinr(ptyinr);
            return pty;
        }
        return null;
    }

    @Override
    public void setCFAERRSta(String objTyp, String instyp, String rptno, String changeno) {
        String bussno = "";
        switch( objTyp )
        {
            case "EAD":
            case  "EAF":
                switch( instyp )
                {
                    case "BAS":
                        bussno = rptno;
                        break;
                    case "DCL":
                        bussno = rptno + "," + changeno;
                        break;
                }
                break;
            case "EBA":
                switch( instyp )
                {
                    case "BAS":
                    case  "DCL":
                        bussno = rptno;
                        break;
                    case "VRF":
                        bussno = rptno + "," + changeno;
                        break;
                }
                break;
            case "ECA":
                switch( instyp )
                {
                    case "BAS":
                        bussno = rptno;
                        break;
                    case "DCL":
                        bussno = rptno + "," + changeno;
                        break;
                }
                break;
        }

        Cfaerr cfaerr = cfaerrMapper.selectByRptno(bussno);
        if( ! MdaUtils.isEmpty(cfaerr) )
        {
            cfaerrMapper.updateByRptno(bussno);
        }

    }

    @Override
    public String getHeqBankCountry(String ptyinr) {
        String heqcty = "";
        Pty heqpty = ptyMapper.selectHeqBankByPTyinr(ptyinr);
        if(heqpty != null){
            heqcty = Strings.mid(heqpty.getExtkey(),5,2);
        }
        return heqcty;
    }

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

    @Override
    public int dbcounterCFACou(String counam, Date dat) {
        String vcounam = Strings.trim(counam);
        return (int) serialCounterService.genSerialNumberByDb("cfacou",vcounam,dat);
        //对mac码计数用
        //数据存储在cfacou中
        /*String vcounam = Strings.trim(counam);
        int count = 0;
        int cou = 0;
        Cfacou cfacou = new Cfacou();
        cfacou.setCounam( counam);
        cfacou.setCoudat( dat);
        Cfacou cfacouDb = cfacouMapper.selectByCouPro(cfacou);
        if(MdaUtils.isEmpty(cfacouDb))
        {
            cfacou.setCoudat( dat);
            cfacou.setCounam( counam);
            cfacou.setCoustp( 1);
            cfacou.setCouval( 1);
            cfacouMapper.insert(cfacou);
        }
        else
        {
            cfacou.setCoustp(cfacouDb.getCoustp());
            cfacou.setCouval( cfacouDb.getCouval() + cfacouDb.getCoustp());
            cfacouMapper.updateByCouPro(cfacou);
        }

        count = (int)cfacou.getCouval();
        return count;*/
    }

    @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 = dbcounterCFACou( couNam, dat );
            while( MdaUtils.compareTo(Decimals.mul(Numerics.round(Decimals.div(counum,100),0),100),counum) == 0 )
            {
                counum = dbcounterCFACou( couNam, dat );
            }
            couVal = MdaUtils.toString(counum,-6);
        }
        String bopref = typ + decnum + Formats.format(dat,"YYYYMMDD") + cfaMapNumber( couVal, typ, valid );
        return bopref;
    }

    @Override
    public 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;
    }

    @Override
    public boolean isValidEntpCode(String code) {
        ///检测组织机构代码
        if(MdaUtils.isEmpty(code)){
            return false;
        }

        int[] ws = { 3, 7, 9, 10, 5, 8, 4, 2 };
        String str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String regex = "([0-9A-Z]){8}[0-9|X]";
        if (!code.matches(regex))
        {
            return false;
        }
        int sum = 0;
        for (int i = 0; i < 8; i++)
        {
            sum += str.indexOf(String.valueOf(code.charAt(i))) * ws[i];
        }
        int c9 = 11 - (sum % 11);
        String sc9 = String.valueOf(c9);
        if (11 == c9)
        {
            sc9 = "0";
        }
        else if (10 == c9)
        {
            sc9 = "X";
        }
        return sc9.equals(String.valueOf(code.charAt(8)));
    }

    @Override
    public boolean cfaStoreEBL(Eblmod eblmod, String transName) {
        String objFlg = "";
        if(!MdaUtils.isEmpty(eblmod.getEbl().getInr())){
            Ebl selebl = eblMapper.selectByInr(eblmod.getEbl().getInr());
            if(!MdaUtils.isEmpty(selebl)){
                objFlg = "F";
            }
        }
        //存在则更新，否则插入
        if(MdaUtils.isEmpty(objFlg)){
            sysmodService.sdbInsert(eblmod.getEbl());
        }else{
            sysmodService.sdbUpdate(eblmod.getEbl());
        }

        //记录 cfasig 表
        this.setRecordSig(eblmod,transName);
        sysmodService.sdbInsert(eblmod.getCfasig());
        return true;
    }


}
