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

import cn.hutool.core.date.DateUtil;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.isc.bo.Bch;
import com.brilliance.isc.bo.Pbl;
import com.brilliance.isc.bo.Pty;
import com.brilliance.isc.common.bop.service.PblmodService;
import com.brilliance.isc.common.bop.service.Rmb2111Service;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.component.DyncDaoService;
import com.brilliance.isc.common.context.BopContext;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.rmbbop.entity.Tbk;
import com.brilliance.isc.common.rmbbop.model.Tdbgrp;
import com.brilliance.isc.common.rmbbop.vo.Rmb2111;
import com.brilliance.isc.common.setgll.vo.SetgllVo;
import com.brilliance.isc.common.sysmod.SysmodService;
import com.brilliance.isc.common.util.BopUtils;
import com.brilliance.isc.common.util.RmbbopUtils;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.common.vo.BizInfoVo;
import com.brilliance.isc.mda.dao.PblMapper;
import com.brilliance.isc.mda.dao.TbkMapper;
import com.brilliance.isc.vo.collection.BcdBizInfoVo;
import com.brilliance.isc.vo.lc.BrdBizInfoVo;
import com.brilliance.isc.vo.remit.CpdBizInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


@Service("tdb")
public class Rmb2111ServiceImpl implements Rmb2111Service {
    @Autowired
    private DyncDaoService dyncDaoService;
    @Autowired
    private CodetableService codetableService;
    @Autowired
    private PblmodService pblmodService;
    @Autowired
    private SysmodService sysmodService;
    @Autowired
    private TbkMapper tbkMapper;
    @Autowired
    private PblMapper pblMapper;


    @Override
    public void save(Rmb2111 rmb2111) {
        //保存人民币跨境支出信息
        String objinr = rmb2111.getRecgrp().getAds().getInr();
        if (!MdaUtils.isEmpty(objinr)) {
            Pbl pbl = pblMapper.selectByObjtypAndObjinr("TDB", objinr);
            rmb2111.getPblmod().setWrkpbl(pbl);
        }
        pblmodService.storeAllinBusTx(rmb2111);
//            wfmmodService.wfeAdd("BCK", "BCK", new Date(), BigDecimal.valueOf(24));
//            wfmmodService.wfeAdd("RSD", "RSD", new Date(), BigDecimal.valueOf(24));
    }

    @Override
    public void updrmb(Rmb2111 rmb2111) {
        pblmodService.mappingRMBDataCommon(rmb2111);
        mappingRMBDataAAAAAA(rmb2111);
        setTbk(rmb2111);
    }

    @Override
    public void saveSpt(Rmb2111 rmb2111) {
        BopUtils.saveSpt(rmb2111.getObjtyp() + "ADD");
    }

    private void setTbk(Rmb2111 rmb2111) {
        Tdbgrp recgrp = rmb2111.getRecgrp();
        for (int i = 0; i < recgrp.getTbk().size(); i++) {
            Tbk tbk = recgrp.getTbk().get(i);
            tbk.setSeqno(i + 1);
            //明细操作类型
            tbk.setListopertype("1");
            //融资合同备案号
//            $CONTRACTNO = GetContentN( "\\RMBBOP\\RMB2108\\RECGRP\\ADS\\LEVYNO" )
//            if GetContentN( "\\RMBBOP\\RMB2108\\RMBFLG" ) = "1" then
//            MappingField_RMB( GetField( "RECP\TBKPP(" + tejRow + ")\CONTRACTNO" ), $CONTRACTNO )
//            else
//            MappingField_RMB( GetField( "RECP\TBKPP(" + tejRow + ")\CONTRACTNO" ), "" )
//            endif
//            tbk.setCuststate("0001");
//            ExecuteDefault( RECP\RECGRP\TBK )
        }
    }

    private void mappingRMBDataAAAAAA(Rmb2111 rmb2111) {
        Tdbgrp recgrp = rmb2111.getRecgrp();
        //付款币种
        recgrp.getAds().setPayercny(RmbbopUtils.getCur());
        //付款日期
        recgrp.getAds().setPayerdate(DateUtil.date());
        //MappingField2( GetField( "RECGRP\\ADS\\actiondesc" ), "申报无误" )
        //付款人名称
        recgrp.getAds().setPayername(RmbbopUtils.getPty("APL").getNam1());

        Pty pty = RmbbopUtils.getPty(RmbbopUtils.getTranRol());
        switch (pty.getIdtype()) {
            case "1":
                recgrp.getAds().setPayerattr("2003");
                break;
            case "2":
                //###同业客户包含银行2001和非银行金融机构2002####
                //###境内个人1001，境外个人1002####
            case "D":
            case "F":
            default:
                recgrp.getAds().setPayerattr("");
        }
        //付款人机构代码或身份证件号码
        recgrp.getAds().setPayerorgcode(pty.getIdcode());
        //付款人账号
        recgrp.getAds().setPayeracct(RmbbopUtils.getBasic().getLeft());
        String transName = SettleContext.getTransName().substring(0, 6);
        BigDecimal othamt;
        if (StringUtils.equals(transName.substring(0, 2), "CP")) {
            othamt = RmbbopUtils.getTxccy();
        } else {
            othamt = RmbbopUtils.getActuccy();
        }
        if (StringUtils.equals(transName, "DFTSET")) {
            othamt = RmbbopUtils.getAmt().abs();
        }
        //总金额
        recgrp.getAds().setAllamt(othamt);

        //收款人常驻国家（地区）代码
        String cty = null;
        //----收款人账户类型-----
        BizInfoVo bizInfo = BopContext.getBizInfo();
        switch (bizInfo.getObjtyp()) {
            case "BCD":
                BcdBizInfoVo bcdBizInfoVo = (BcdBizInfoVo) bizInfo;
                //收款人账号
                recgrp.getAds().setPayeeacct(BopUtils.getPtsByRol("RMI").getDftact());
                //收款人名称
                recgrp.getAds().setPayeename(BopUtils.getPtsByRol("DRR").getNam());
                //结算方式
                switch (bcdBizInfoVo.getDoctypcod()) {
                    case "A":
                        recgrp.getAds().setBalancemode("DA");
                        break;
                    case "P":
                        recgrp.getAds().setBalancemode("DP");
                        break;
                    default:
                        recgrp.getAds().setBalancemode("OT");
                }
                cty = bcdBizInfoVo.getStacty();
                break;
            case "BRD":
                BrdBizInfoVo brdBizInfoVo = (BrdBizInfoVo) bizInfo;
                //收款人名称
                recgrp.getAds().setPayeename(BopUtils.getPtsByRol("BEN").getNam());
                //结算方式
                recgrp.getAds().setBalancemode("LC");
                cty = brdBizInfoVo.getStacty();
                break;
            case "CPD":
                CpdBizInfoVo cpdBizInfoVo = (CpdBizInfoVo) bizInfo;
                //对手客户名称，刘文青要求统一修改为取pts的nam
                //收款人名称
                recgrp.getAds().setPayeename(BopUtils.getPtsByRol("PYE").getNam());
                //结算方式
                switch (cpdBizInfoVo.getPaytype()) {
                    case "0":
                        recgrp.getAds().setBalancemode("TT");
                        break;
                    case "1":
                        recgrp.getAds().setBalancemode("DD");
                        break;
                    case "2":
                        recgrp.getAds().setBalancemode("MT");
                        break;
                    default:
                        recgrp.getAds().setBalancemode("OT");
                        break;
                }
                //收款人账号
                recgrp.getAds().setPayeeacct(cpdBizInfoVo.getPyeact());
                cty = cpdBizInfoVo.getPayeecountcode();
                break;
            case "GID":
            case "GCD":
            case "NID":
            case "NCD":
                //结算方式
                recgrp.getAds().setBalancemode("GT");
                String hndtyp = Utils.getFieldValue(bizInfo, "hndtyp");
                if (StringUtils.equals(hndtyp, "OT")) {
                    //转开保函付款人名称取APL临时名称
                    //收款人名称
                    recgrp.getAds().setPayeename(BopUtils.getPtsByRol("APL").getNam());
                } else {
                    //文青姐要求，进口保函付款也要自动带出收款人名称，并取BEN角色名称
                    recgrp.getAds().setPayeename(BopUtils.getPtsByRol("BEN").getNam());
                }
                cty = Utils.getFieldValue(bizInfo, "stacty");
                break;
            case "DFD":
                //结算方式
                recgrp.getAds().setBalancemode("OT");
                //收款人名称
                recgrp.getAds().setPayeename(BopUtils.getPtsByRol("DFF").getNam());
                cty = BopUtils.getAdrByRol("DFF").getLoccty();
                break;
        }
        if (StringUtils.isNotEmpty(cty)) {
            String payeecountrycode = cty.length() == 2 ? codetableService.getTblLabel(cty, "CTYCOD") : cty;
            recgrp.getAds().setPayeecountrycode(payeecountrycode);
        }
        //收款行行号
        String sbhbic = null;
        String sbhhh = null;
        switch (transName) {
            case "CPTOPN":
                CpdBizInfoVo cpdBizInfoVo = (CpdBizInfoVo) bizInfo;
                switch (cpdBizInfoVo.getSwftyp()) {
                    case "103":
                    case "202":
                        sbhbic = RmbbopUtils.getOutSwift("AWI").getLeft();
                        break;
                    case "200":
                        sbhbic = RmbbopUtils.getOutSwift("BEI").getLeft();
                        break;
                    case "CIU":
                        List<SetgllVo> setgll = BopContext.getSetglg().getSetgll();
                        SetgllVo setgllVo = setgll.stream().filter(i -> "CIU".equals(i.getSftmt()))
                                .findAny().orElseGet(SetgllVo::new);
                        setgllVo.reset();
                        sbhhh = setgllVo.getSespay().getCipmod().getPyebchkey();
                }
                // 自贸分账核算单元，在报文、申报和报送环节，需要体现主账户（FT）账号，ZMQ仅在账务处理时采用
                Bch bch = SettleContext.getUserSession().getBch();
                if ("X".equalsIgnoreCase(bch.getZmqflg())) {
                    recgrp.getAds().setPayeracct(cpdBizInfoVo.getZmqacc());
                }
                break;
            case "BCTSET":
                sbhbic = BopUtils.getPtaByRol("RMI").getPtyextkey();
                break;
            case "BRTSET":
            case "GITSET":
            case "NITSET":
            case "GITPSE":
            case "NITPSE":
                sbhbic = BopUtils.getPtaByRol("PRB").getPtyextkey();
                break;
            case "DFTSET":
                sbhbic = BopUtils.getPtaByRol("DFF").getPtyextkey();
                break;
        }
        String recebankcode = StringUtils.isEmpty(sbhbic) ? sbhhh : StringUtils.substring(sbhbic, 0, 11);
        if (StringUtils.isNotEmpty(recebankcode)) {
            recgrp.getAds().setRecebankcode(recebankcode);
        }
        //是否退款
        recgrp.getAds().setIfrefund("N");
//        if (!MdaUtils.isEmpty(rmb2111.getNewnum())) {
//            for (int i = 0; i < rmb2111.getNewnum(); i++) {
//                //明细主键
//                rmbbopRequestVo.getRmbbop2111Vo().getRecgrp().getTbk().get(i).setSeqno(i+1);
//                //明细操作类型
//                rmbbopRequestVo.getRmbbop2111Vo().getRecgrp().getTbk().get(i).setListopertype("1");
//                String bustypecode = recgrp.getTbk().get(i).getBustypecode();
//                BigDecimal payamt = recgrp.getTbk().get(i).getPayamt();
//                if (!(MdaUtils.compareTo(bustypecode, "200012") == 0 && payamt.doubleValue() > 30000)) {
//                    recgrp.getTbk().get(i).setActualpayercode(Strings.mid(sbhbic, 1, 11));
//                    recgrp.getTbk().get(i).setActualpayername(nam);
//                }
//            }
//        }
    }


    @Override
    public void saveChildData(Rmb2111 rmb2111) {
        Tdbgrp recgrp = rmb2111.getRecgrp();
        //savdatafrompanel
        pblmodService.setListData(rmb2111.getPblmod(), recgrp.getTbk());
        recgrp.getAds().setPaymentlist(recgrp.getTbk().size());
        //存储TBK数据
        for (Tbk tbk : recgrp.getTbk()) {
            tbk.setObjinr(recgrp.getAds().getInr());
            tbk.setObjtyp(rmb2111.getObjtyp());
            if (dyncDaoService.dyncReadNoDataByInr(tbk))
                sysmodService.sdbUpdateWithLog(tbk);
            else
                sysmodService.sdbInsertWithLog(tbk);
        }
    }

    @Override
    public void rmbLoadContract(Rmb2111 rmb2111) {
        rmb2111.getRecgrp().getAds().setPaymentlist(rmb2111.getNewnum());
        int tbk = rmb2111.getRecgrp().getAds().getPaymentlist();
        if (tbk > 0) {
            List<Tbk> tbkList = rmb2111.getRecgrp().getTbk();
            for (int i = 0; i < tbk; i++) {
                Tbk newtbk = new Tbk();
                newtbk.setObjtyp("TDB");
                newtbk.setObjinr(rmb2111.getRecgrp().getAds().getInr());
                newtbk.setSeqno(i + 1);
                newtbk = tbkMapper.selectByObjInfo(newtbk);
                if (newtbk != null) {
                    tbkList.add(newtbk);
                }
            }
        }
    }

    @Override
    public List<String> setRMBPresaveoldValue(Rmb2111 rmb2111) {
        rmb2111.getRecgrp().getAds().setPaymentlist(rmb2111.getNewnum());
        int tbk = rmb2111.getRecgrp().getAds().getPaymentlist();
        List<String> list = new ArrayList<>();
        if (tbk > 0) {
            rmb2111.getRecgrp().getTbk().forEach(tbkObj -> {
                if (!MdaUtils.isEmpty(tbkObj.getSeqno()) && !MdaUtils.isEmpty(tbkObj.getListopertype())) {
                    list.add(tbkObj.getSeqno() + "TBK" + "\t" + tbkObj.getListopertype());
                }
            });
        }
        return list;
    }


}
