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

import com.brilliance.isc.bo.Dzghxx;
import com.brilliance.isc.bo.Smh;
import com.brilliance.isc.bo.Trn;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.counter.service.CounterService;
import com.brilliance.isc.common.esb.account.IAccountFeign;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.common.gedmod.service.GedmodService;
import com.brilliance.isc.common.gedmod.vo.Ge34Request;
import com.brilliance.isc.common.gedmod.vo.Ge34Response;
import com.brilliance.isc.common.gedmod.vo.GedmodVo;
import com.brilliance.isc.common.setglg.vo.SetglgVo;
import com.brilliance.isc.common.setgll.vo.SetgllVo;
import com.brilliance.isc.common.transaction.help.TransactionHelpService;
import com.brilliance.isc.common.transaction.vo.BaseTransactionVo;
import com.brilliance.isc.common.transaction.vo.SimpleSetmodVo;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.esb.model.inner.*;
import com.brilliance.isc.esb.model.inner.item.ItemGe34;
import com.brilliance.isc.mda.dao.DzghxxMapper;
import com.brilliance.mda.runtime.mda.impl.Argument;
import com.brilliance.mda.runtime.mda.util.Decimals;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class GedmodServiceImpl implements GedmodService {

    private static Logger log = LoggerFactory.getLogger(GedmodServiceImpl.class);

    @Autowired
    private TransactionHelpService transactionHelpService;

    @Autowired
    private CounterService counterService;

    @Autowired
    private DzghxxMapper dzghxxMapper;

    @Autowired(required = false)
    private IAccountFeign accountFeign;

    @Override
    public Ge34Response callGe34(Ge34Request ge34Request) {
        Ge34Response response = new Ge34Response();
        InnerReqEtradeGe34 reqGe34 = new InnerReqEtradeGe34(ge34Request.getEcifno(), ge34Request.getBusinessno());
        InnerReq<InnerReqEtradeGe34> innerReqGe34 = new InnerReq<>(reqGe34);
        InnerRes<InnerResEtradeGe34> innerResGe34 = accountFeign.callEtradeGe34(innerReqGe34);
        try {
            //分析接口返回码
            if (innerResGe34 == null) {
                response.setErrorMsg(Strings.formatText("查询EtradeGe34接口结果为空:$1", ge34Request.getBusinessno()));
                return response;
            }
            if (!"AAAAAAA".equals(innerResGe34.header.code)) {
                log.error("查询EtradeGe34接口{}出错, {}", ge34Request.getBusinessno(), innerResGe34.header.description);
                response.setErrorMsg(Strings.formatText("查询EtradeGe34接口结果为空:$1", ge34Request.getBusinessno()));
                return response;
            }
            //获取接口返回信息,组装liaccvAcctVo
            if (innerResGe34.DATA != null && innerResGe34.DATA.shslst != null && innerResGe34.DATA.shslst.size() > 0) {
                List<ItemGe34> shslst = innerResGe34.DATA.shslst;
                response.setBusinessno(shslst.get(0).businessno);
                response.setCurrency(shslst.get(0).currency);
                response.setHavegwfed(new BigDecimal(shslst.get(0).havegwfed));
                response.setApplystatus(shslst.get(0).applystatus);
                response.setCuswbzh(shslst.get(0).cuswbzh);
                response.setDuifzh(shslst.get(0).duifzh);
                response.setPaytype(shslst.get(0).paytype);
            } else {
                response.setErrorMsg(Strings.formatText("查询EtradeGe34接口结果为空:$1", ge34Request.getBusinessno()));
            }
            return response;
        } catch (Throwable e) {
            log.error("查询EtradeGe34接口出错", e);
            response.setErrorMsg("查询EtradeGe34接口出错，请联系管理员");
        }
        return response;
    }

    public void getKehuzhAndAmtwibzhh(GedmodVo gedmodVo, SimpleSetmodVo setmodVo, SetglgVo setglg, Argument<String> accountArg, Argument<BigDecimal> amtwibzhhArg, Argument<BigDecimal> amtArg) {
        String pty_account = "";
        BigDecimal amtwibzhh = BigDecimal.ZERO;
        String rol = "";
        String doccur = gedmodVo.getDzghxx().getCur();
        switch (SettleContext.getDirectTransName()) {
            case "CPTOPN":
                rol = "ORC";
                break;
            case "BRTSET":
                rol = "APL";
                break;
            case "BCTSET":
                rol = "DRE";
                break;
            case "JSTOPN":
                rol = "APL";
                break;
            default:
                break;
        }
        if (StringUtils.isNotEmpty(rol) && StringUtils.isNotEmpty(doccur)) {
            for (SetgllVo setgllVo : setglg.getSetgll()) {
                if(MdaUtils.compareTo(setgllVo.getRol(), rol) == 0
                        && MdaUtils.compareTo(setgllVo.getCur(), doccur) == 0
                        && MdaUtils.compareTo(setgllVo.getAcccur(), doccur) == 0
                        && MdaUtils.compareTo(setgllVo.getDebcdtflg(),"D") == 0) {
                    pty_account = setgllVo.getAct();
                    if(MdaUtils.compareTo(setgllVo.getAct(), gedmodVo.getDzghxx().getWibzhh()) == 0) {
                        amtwibzhh = Decimals.add(amtwibzhh, setgllVo.getFmtamt());
                    }
                }
            }
        }
        if (accountArg != null) {
            accountArg.setValue(pty_account);
        }
        if (amtwibzhhArg != null) {
            amtwibzhhArg.setValue(amtwibzhh);
        }
        if (amtArg != null) {
            amtArg.setValue(setmodVo.getDocamt());
        }
    }

    /**
     *   source:gedmod.0000.script
     */
    public void savDZGHXX(GedmodVo vo, BaseTransactionVo baseTransactionVo) {
        if( MdaUtils.compareTo(vo.getZjly(),"1") == 0 ) {
            if(!MdaUtils.isEmpty(vo.getDzghxx().getGhedbh())) {
                transactionHelpService.getTransactionStoreSet().setGedmod(vo);
                Trn trn = transactionHelpService.getTransactionStoreSet().getTrnmodVo().getTrn();
                Dzghxx dzghxx = new Dzghxx();
                BeanUtils.copyProperties(vo.getDzghxx(), dzghxx);
                dzghxx.setObjtyp(trn.getObjtyp());
                dzghxx.setObjinr(trn.getObjinr());
                dzghxx.setTrninr(trn.getInr());
                //国结业务编号
                dzghxx.setOwnref(trn.getOwnref());
                //E结算业务编号
                Smh smh = transactionHelpService.getTransactionStoreSet().getTrnmodVo().getSmh();
                if (smh != null) {
                    dzghxx.setEjsref(smh.getF20());
                }
                //客户账号类型
                dzghxx.setKhzhlx("0");
                //调整规则，解冻金额不再自动取值，改为界面新增栏位手动录入
                /**
                 #解冻金额
                 if DZGHXX\\AMT > DZGHXX\\AMTGWF then
                 DZGHXX\\AMTUNFREZ = DZGHXX\\AMTGWF
                 else
                 DZGHXX\\AMTUNFREZ = DZGHXX\\AMT
                 endif

                 **/
                switch(SettleContext.getDirectTransName()) {
                    case "CPTOPN":
                    case "CPTATO":
                        //交易类型 2：付汇 4：结汇 5-信用证付款 6-托收付款7-线下汇出汇款8-线下信用证付款9-线下托收付款
                        dzghxx.setJioylx("2");
                        if(MdaUtils.isEmpty(dzghxx.getEjsref())) {
                            dzghxx.setJioylx("7");
                        }
                        break;
                    case "JSTOPN":
                        //交易类型 0：付汇   1：结汇
                        dzghxx.setJioylx("4");
                        break;
                    case "BCTSET":
                        dzghxx.setJioylx("6");
                        if(MdaUtils.isEmpty(dzghxx.getEjsref())) {
                            dzghxx.setJioylx("9");
                        }
                        break;
                    case "BRTSET":
                        dzghxx.setJioylx("5");
                        if(MdaUtils.isEmpty(dzghxx.getEjsref())) {
                            dzghxx.setJioylx( "8");
                        }
                        break;
                }
                //柜员号
                dzghxx.setUserno(SettleContext.getUserSession().getUsr().getExtkey());
                //机构
                dzghxx.setBranch(SettleContext.getUserSession().getWrkbch().getBranch());
                Argument<String> accountArg = new Argument<>();
                Argument<BigDecimal> amtwibzhhArg = new Argument<>();
                Argument<BigDecimal> amtArg = new Argument<>();
                this.getKehuzhAndAmtwibzhh(vo, baseTransactionVo.getSetmod(), baseTransactionVo.getSetglg(), accountArg, amtwibzhhArg, amtArg);
                dzghxx.setKehuzh(accountArg.getValue());
                dzghxx.setAmtwibzhh(amtwibzhhArg.getValue());
                dzghxx.setAmt(amtArg.getValue());
                //外币账号对应核心机构号8023接口
                if(MdaUtils.compareTo(dzghxx.getKehuzh(), dzghxx.getWibzhh()) == 0
                        && !MdaUtils.isEmpty(dzghxx.getWibzhh())) {
                    String account = dzghxx.getWibzhh();
                    //组装8023接口请求对象
                    InnerReq8023 req8023 = new InnerReq8023(account);
                    InnerReq<InnerReq8023> innerReq8023 = new InnerReq<>(req8023);
                    InnerRes<InnerRes8023> innerRes8023 = accountFeign.call8023(innerReq8023);
                    try {
                        if (innerRes8023 != null && innerRes8023.DATA != null && "AAAAAAA".equals(innerRes8023.header.code)) {
                            dzghxx.setAccbch(innerRes8023.DATA.yngyjg);
                        } else {
                            throw new CommonServiceException(Strings.formatText("查询Account8023接口结果为空:$1", account));
                        }
                    } catch (Throwable e) {
                        log.error("查询Account8023接口出错", e);
                        throw new CommonServiceException(Strings.formatText("查询Account8023接口结果为空:$1", account));
                    }
                }
                dzghxx.setInr(counterService.dbCounterFormat("DZGHXX"));
                dzghxxMapper.insert(dzghxx);
            }
        }
    }
}
