package com.brilliance.isc.common.transaction.newcheck.monmod;


import com.brilliance.isc.bo.Pty;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.esb.tymd.ITymdFeign;
import com.brilliance.isc.common.forexmod.RiskCustomerDisposeComponent;
import com.brilliance.isc.common.monmod.vo.MonmodVo;
import com.brilliance.isc.common.setgll.vo.SetgllVo;
import com.brilliance.isc.common.sysmod.SysmodService;
import com.brilliance.isc.common.transaction.newcheck.AbstractModuleValidator;
import com.brilliance.isc.common.transaction.newcheck.Warning;
import com.brilliance.isc.common.transaction.newcheck.WarningResult;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.common.vo.PtsptaVo;
import com.brilliance.isc.esb.model.inner.InnerReq;
import com.brilliance.isc.esb.model.inner.InnerReqDU01;
import com.brilliance.isc.esb.model.inner.InnerRes;
import com.brilliance.isc.esb.model.inner.InnerResDU01;
import com.brilliance.isc.mda.dao.PtyMapper;
import com.brilliance.isc.vo.lg.GcdBizInfoVo;
import com.brilliance.isc.vo.lg.GidBizInfoVo;
import com.brilliance.isc.vo.lg.NcdBizInfoVo;
import com.brilliance.isc.vo.lg.NidBizInfoVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

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

@Component
public class MonmodValidator extends AbstractModuleValidator<MonmodVo> {

    private static final String RISK_LEVEL_4_MSG = "请去柜台办理相关业务!";
    private static final String WARNING_SUBID = "EXTKEY_BANK";
    private static final String DOWNGRADE_SUBID = "DOWNGRADE_EXTKEY";

    @Autowired(required = false)
    private ITymdFeign iTymdFeign;

    @Resource
    private RiskCustomerDisposeComponent riskCustomerDisposeComponent;

    @Resource
    private ThreadPoolTaskExecutor taskDistAsyncExecutor;

    @Resource
    private PtyMapper ptyMapper;

    @Resource
    private SysmodService sysmodService;

    @Override
    @PostConstruct
    public void register() {
        super.register();
    }

    @Warning(path = "warncustomer", level = "1")
    public WarningResult checkCustom(MonmodVo vo) {
        String msg = dovalidate(vo, true);
        if (StringUtils.isNotEmpty(msg)) {
            return WarningResult.build(WARNING_SUBID, msg);
        }
        return WarningResult.buildEmpty(WARNING_SUBID);
    }

    @Warning(path = "warncustomer")
    public WarningResult checkCustomLevel2(MonmodVo vo) {
        String msg = dovalidate(vo, false);
        if (StringUtils.isNotEmpty(msg)) {
            return WarningResult.build(DOWNGRADE_SUBID, msg);
        }
        return WarningResult.buildEmpty(DOWNGRADE_SUBID);
    }

    public String dovalidate(MonmodVo vo, boolean interdiction) {
        //先判断有没有重写方法获取  AbstractTransactionService#getPtyinr AbstractTransactionService#downgradeMsg
        if (StringUtils.isNotEmpty(vo.getPtyinr())) {
            Pty pty = ptyMapper.selectByPtyinr(vo.getPtyinr());
            if (pty != null) {
//                return RISK_LEVEL_4_MSG;
                String extkey = pty.getExtkey();
                String level = callDU01(extkey);
                if (interdiction) {
                    return null; // TODO 现需求主要求保函阻断
                } else {
                    return getDowngradeWarningMsg(level, extkey, vo);
                }
            }
        }
        String tranName = SettleContext.getDirectTransName();
        switch (tranName) {
            case "GITSET":
            case "GITPSE":
            case "GITOPN":
            case "GITPOP":
//                if ("4".equals(callDU01(getExtkey(vo)))) {
//                    return WarningResult.build(WARNING_SUBID,  RISK_LEVEL_4_MSG);
//                }
                String extkey = getExtkey(vo);
                String level = callDU01(extkey);
                if (interdiction) {
                    if ("4".equals(level)) {
                        return RISK_LEVEL_4_MSG;
                    } else {
                        return null;
                    }
                } else {
                    return getDowngradeWarningMsg(level, extkey, vo);
                }
            case "GITAME":
            case "GITPAM":
            case "GETOPN":
            case "GETAME":
            case "NETOPN":
            case "NETAME":
                if (userInterfaceNotSnd(getExtkey(vo))) {
                    return RISK_LEVEL_4_MSG;
                }
                break;
            case "NITPOP":
            case "NITOPN":
                if (vo.getRec() != null && vo.getRec() instanceof NidBizInfoVo) {
                    if (!"CHN".equalsIgnoreCase(((NidBizInfoVo) vo.getRec()).getPayeecountcode())) {
                        if (userInterfaceNotSnd(getExtkey(vo))) {
                            return RISK_LEVEL_4_MSG;
                        }
                    }
                }
                break;
            case "NITAME":
            case "NITPAM":
                if (vo.getRec() != null && vo.getRec() instanceof NidBizInfoVo) {
                    if (!"CHN".equalsIgnoreCase(((NidBizInfoVo) vo.getRec()).getCountrycode())) {
                        if (userInterfaceNotSnd(getExtkey(vo))) {
                            return RISK_LEVEL_4_MSG;
                        }
                    }
                }
                break;
            case "NITSET":
            case "NITPSE":
                if (vo.getSetglg() != null && CollectionUtils.isNotEmpty(vo.getSetglg().getSetgll())) {
                    for (SetgllVo setgllVo : vo.getSetglg().getSetgll()) {
                        if ("CIV".equalsIgnoreCase(setgllVo.getSftmt()) || "756".equalsIgnoreCase(setgllVo.getSftmt())) {
                            if (userInterfaceNotSnd(getExtkey(vo))) {
                                return RISK_LEVEL_4_MSG;
                            }
                        }
                    }
                }
                break;
            default:
                break;
        }
        return null;
    }

    public String getExtkey(MonmodVo vo) {
        String extkey = "";
        List<PtsptaVo> list = vo.getPtsList();
        if (vo.getRec() instanceof NidBizInfoVo) {
            String hndtyp = ((NidBizInfoVo) vo.getRec()).getHndtyp();
            extkey = dealSameMethod(hndtyp, list);
        }
        if (vo.getRec() instanceof NcdBizInfoVo) {
            String hndtyp = ((NcdBizInfoVo) vo.getRec()).getHndtyp();
            extkey = dealSameMethod(hndtyp, list);
        }
        if (vo.getRec() instanceof GidBizInfoVo) {
            String hndtyp = ((GidBizInfoVo) vo.getRec()).getHndtyp();
            extkey = dealSameMethod(hndtyp, list);
        }
        if (vo.getRec() instanceof GcdBizInfoVo) {
            String hndtyp = ((GcdBizInfoVo) vo.getRec()).getHndtyp();
            extkey = dealSameMethod(hndtyp, list);
        }
        return extkey;
    }

    public String getExtkeyDataByHndtyp(List<PtsptaVo> list, String rol) {
        String extkey = "";
        if (CollectionUtils.isNotEmpty(list)) {
            PtsptaVo ptsptaVo = list.stream().filter(e -> rol.equalsIgnoreCase(e.getRol())).findFirst().orElse(null);
            if (ptsptaVo != null) {
                extkey = ptsptaVo.getExtkey();
            }
        }
        if (StringUtils.isNotEmpty(extkey) && extkey.contains("-")) {
            extkey = extkey.split("-")[0];
        }
        return extkey;
    }

    public String dealSameMethod(String hndtyp, List<PtsptaVo> list) {
        String extkey = "";
        if ("OT".equalsIgnoreCase(hndtyp) || "F".equalsIgnoreCase(hndtyp.substring(0, 1))) {
            extkey = getExtkeyDataByHndtyp(list, "BEN");
        } else {
            extkey = getExtkeyDataByHndtyp(list, "APL");
        }
        return extkey;
    }

    private String getDowngradeWarningMsg(String level, String extkey, MonmodVo vo) {
//        String level = callDU01(extkey);
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotEmpty(vo.getDowngradeMsg())) {
            sb.append(vo.getDowngradeMsg());
        }
        if ("3".equalsIgnoreCase(level) || "4".equalsIgnoreCase(level)) {
            sb.append("洗钱风险等级为".concat(level));
        }
        if (sb.length() > 0) {
            if (vo != null && vo.getForexmod() != null && ("01".equals(vo.getForexmod().getRiskLevel()) || "02".equals(vo.getForexmod().getRiskLevel()))) {
                callOC52(extkey, sb.toString(), vo);
                return "客户风险等级降级原因:".concat(sb.toString());
            }
        }
        return null;
    }

    private Boolean userInterfaceNotSnd(String extkey) {
        return "4".equals(callDU01(extkey));
    }

    public String callDU01(String extkey) {
        if (sysmodService.isInterfaceOpen("DU01")) {
            InnerReqDU01 innerReqDU01 = new InnerReqDU01();
            // 需要查询的客户号
            innerReqDU01.ECIF_CUST_NO = extkey;
            InnerReq<InnerReqDU01> innerReqDU01InnerReq = new InnerReq<>(innerReqDU01);
            InnerRes<InnerResDU01> innerResDU01InnerRes = this.iTymdFeign.callDU01(innerReqDU01InnerReq);
            //调用成功
            if ("AAAAAAA".equals(innerResDU01InnerRes.header.code)) {
                // 判断是否是高风险客户号
                if (innerResDU01InnerRes.DATA != null) {
                    return innerResDU01InnerRes.DATA.getRISK_RATING();
                }
            }
        }
        return null;
    }

    private void callOC52(String extkey, String reason, MonmodVo vo) {
        if (vo != null && vo.getForexmod() != null && ("01".equals(vo.getForexmod().getRiskLevel()) || "02".equals(vo.getForexmod().getRiskLevel()))) {
            String usr = SettleContext.getSessionUserVo().getLogName();
            taskDistAsyncExecutor.execute(() -> {
                riskCustomerDisposeComponent.OC52(extkey, reason, usr);
            });
        }
    }

}
