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

import com.brilliance.mda.runtime.mda.util.Dates;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Strings;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import com.brilliance.isc.bo.Fale01;
import com.brilliance.isc.bo.model.Cfabop;
import com.brilliance.isc.common.bop.cfa.cfabop.register.CfabopRegister;
import com.brilliance.isc.common.bop.cfa.cfabop.service.CfaReportService;
import com.brilliance.isc.common.bopset.service.CfabopService;
import com.brilliance.isc.common.context.SpringEnvContext;
import com.brilliance.isc.common.counter.service.CounterService;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.common.setfeg.vo.SetfelVo;
import com.brilliance.isc.common.setmod.vo.SetmodVo;
import com.brilliance.isc.common.transaction.help.TransactionHelpService;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.mda.dao.ActMapper;
import com.brilliance.isc.mda.dao.Fale01Mapper;
import com.brilliance.isc.mda.dao.PtyMapper;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CfabopServiceImpl implements CfabopService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "eca.bop")
    private CfaReportService cfaecaService;

    @Resource(name = "ead.bop")
    private CfaReportService cfaeadService;

    @Resource(name = "eaf.bop")
    private CfaReportService cfaeafService;

    @Autowired
    private PtyMapper ptyMapper;

    @Autowired
    private ActMapper actMapper;

    @Autowired
    private Fale01Mapper fale01Mapper;

    @Autowired
    private TransactionHelpService transactionHelpService;

    @Autowired
    private CounterService counterService;


    @Override
    public void saveCfaData(Cfabop cfabop) {
        //进行存盘
        String transName = cfabop.getTransName();

        //国内外汇贷款
        String ecacfaflg = cfabop.getCfaeca().getCfaflg();
        if(!MdaUtils.isEmpty(ecacfaflg)&&!"4".equals(ecacfaflg)){
            logger.info("{} Serivce 保存资本项目申报-国内外汇贷款信息", transName);
            cfaecaService.cfaBopSaveData(cfabop);
        }
        //海外代付
        String eadcfaflg = cfabop.getCfaead().getCfaflg();
        if(!MdaUtils.isEmpty(eadcfaflg)&&!"4".equals(eadcfaflg)){
            logger.info("{} Serivce 保存资本项目申报-海外代付信息", transName);
            cfaeadService.cfaBopSaveData(cfabop);
        }
        //远期信用证
        String eafcfaflg = cfabop.getCfaeaf().getCfaflg();
        if(!MdaUtils.isEmpty(eafcfaflg)&&!"4".equals(eafcfaflg)){
            logger.info("{} Serivce 保存资本项目申报-远期信用证信息", transName);
            cfaeafService.cfaBopSaveData(cfabop);
        }
    }


    @Override
    public Cfabop calCfaData(Cfabop cfabop) {
        //进行试算
        String transName = cfabop.getTransName();

        //国内外汇贷款
        String ecacfaflg = cfabop.getCfaeca().getCfaflg();
        if(!MdaUtils.isEmpty(ecacfaflg)&&!"4".equals(ecacfaflg)){
            logger.info("{} Serivce 计算资本项目申报-国内外汇贷款信息", transName);
            this.registerCfabopBizInfo(cfabop,"ECA");
            cfaecaService.cfaMappingData(cfabop);
        }
        //海外代付
        String eadcfaflg = cfabop.getCfaead().getCfaflg();
        if(!MdaUtils.isEmpty(eadcfaflg)&&!"4".equals(eadcfaflg)){
            logger.info("{} Serivce 计算资本项目申报-海外代付信息", transName);
            this.registerCfabopBizInfo(cfabop,"EAD");
            cfaeadService.cfaMappingData(cfabop);
        }
        //远期信用证
        String eafcfaflg = cfabop.getCfaeaf().getCfaflg();
        if(!MdaUtils.isEmpty(eafcfaflg)&&!"4".equals(eafcfaflg)){
            logger.info("{} Serivce 计算资本项目申报-远期信用证信息", transName);
            this.registerCfabopBizInfo(cfabop,"EAF");
            cfaeafService.cfaMappingData(cfabop);
        }

        return cfabop;
    }

    @Override
    public Cfabop getCfaPreData(Cfabop cfabop,String Cfatype,String ownref) {
        //模型重置
        cfabop.reset();
        //加载前手报送数据
        //国内外汇贷款
        if("ECA".equals(Cfatype)){
            cfaecaService.cfaGetPreData(cfabop,ownref);
        }

        //海外代付
        if("EAD".equals(Cfatype)){
            cfaeadService.cfaGetPreData(cfabop,ownref);
        }

        //远期信用证
        if("EAF".equals(Cfatype)){
            cfaeafService.cfaGetPreData(cfabop,ownref);
        }



      return cfabop;
    }



    @Override
    public void repairCfaData(String trninr) {
        //退回此业务下所有资本报送数据
        if(!MdaUtils.isEmpty(trninr)){
            cfaecaService.cfabopRePair(trninr);
            cfaeadService.cfabopRePair(trninr);
            cfaeafService.cfabopRePair(trninr);
        }

    }

    @Override
    public void registerCfabopBizInfo(Cfabop cfabop,String Cfatype) {
        //依据业务类型构建报送业务数据
        String objtyp = cfabop.getRec().getObjtyp();
        try {
            CfabopRegister cfabopService = SpringEnvContext.getBean(objtyp.toLowerCase()+".cfabopRegister");
            cfabopService.registerCfabopBizInfo(cfabop,Cfatype.toUpperCase());
        } catch (NoSuchBeanDefinitionException e) {
            throw new CommonServiceException("没有找到报送数据构建类:"+objtyp);
        }
    }

    @Override
    public List<Fale01> calFale01Date(SetmodVo setmodVo) {
        //通过费用记录生成 E01表记录 现收
        //1.费用的科目为 0732、2116、2392、2405、2406、1926
        //2.客户所属国家地区非中国，通过ECIF信息判断

        Map<String,BigDecimal> sumamt = new HashMap<String,BigDecimal>();
        String ownref = setmodVo.getRec().getOwnref();
        //遍历费用记录
        List<SetfelVo> setfellist = setmodVo.getSetfeg().getSetfel();
        for (int i = 0; i < setfellist.size(); i++) {
            String ptyinr = setfellist.get(i).getRolptyinr();
            String feedsp = setfellist.get(i).getDsp();
            String feeacc = setfellist.get(i).getFeeacc();
            String feecur = setfellist.get(i).getCur();
            BigDecimal feeamt = new BigDecimal(0);
            if(!MdaUtils.isEmpty(setfellist.get(i).getAmt())){
                feeamt = setfellist.get(i).getAmt();
            }
            //跳过非现收
            if(!"X".equals(feedsp)){
                continue;
            }

            //通过核心客户号查询 ecfi 表获取国家地区代码
            String ecifcounntry = ptyMapper.selectEcifCountryByPtyinr(ptyinr);
            if("CHN".equals(ecifcounntry)){
                continue;
            }

            //通过账号获取 科目号
            String trmcod = actMapper.getTxmcodByExtkey(feeacc);
            if (StringUtils.isEmpty(trmcod)) {
                String termid = "";
                if(feeacc.length() == 20) {
                    termid = Strings.mid(feeacc,10,4);
                }
                if( feeacc.length() == 17 ) {
                    termid = Strings.mid(feeacc,7,4);
                }
                if( feeacc.length() == 21 ) {
                    termid = Strings.mid(feeacc,12,4);
                }
                if(!MdaUtils.isEmpty(termid)){
                    trmcod= termid;
                }
            }

            if(!"0732".equals(trmcod)&&!"2116".equals(trmcod)&&!"2392".equals(trmcod)&&!"2405".equals(trmcod)&&!"2406".equals(trmcod)&&!"1926".equals(trmcod)){
                continue;
            }

            //合并同国别 币种 科目的金额
            String e01key = feecur+","+ecifcounntry+","+trmcod;
            if(sumamt.containsKey(e01key)){
                sumamt.put(e01key,feeamt.add(sumamt.get(e01key)));
            }else{
                sumamt.put(e01key,feeamt);
            }


        }

        //生成 e01 表记录
        List<Fale01> e01list = new ArrayList<>();
        for(Map.Entry<String,BigDecimal> entry:sumamt.entrySet()){
            //拆分key 获取 国别 币种 科目
            String[] keys = entry.getKey().split(",");
            String feecur = keys[0];
            String ecifcounntry = keys[1];
            String trmcod = keys[2];

            //生成 fale01 记录
            Fale01 fale01 = new Fale01();
            fale01.setObjcode("110000000700");
            fale01.setE0101cur(feecur);
            fale01.setE0101("226000");
            fale01.setE0102(ecifcounntry);
            fale01.setE0103(entry.getValue());
            fale01.setOwnref(ownref);
            fale01.setTrmcod(trmcod);
            if("0732".equals(trmcod)){
                fale01.setDeptyp("交易银行部国结处");
            }else{
                fale01.setDeptyp("交易银行部贸易融资处");
            }
            fale01.setTrmcod(trmcod);
            fale01.setTrninr(transactionHelpService.getTrninr());
            fale01.setCredat(Dates.today());



            e01list.add(fale01);

        }


        return e01list;
    }

    @Override
    public void saveFale01Date(List<Fale01> fale01List) {
        //数据库插入
        for (Fale01 fale01 : fale01List) {
            fale01.setInr(counterService.dbCounterFormat("FALE01"));
            //防止前端传值丢失 补充一些字段赋值
            fale01.setSta("W");
            fale01.setTrninr(transactionHelpService.getTrninr());
            fale01.setCredat(Dates.today());
            fale01Mapper.insert(fale01);
        }

    }
}
