package com.muchinfo.mtp3century.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muchinfo.mtp.proto.BankMI1;
import com.muchinfo.mtp.proto.Common;
import com.muchinfo.mtp3century.exception.GlobalException;
import com.muchinfo.mtp3century.service.IBankBusinessService;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.enumtype.Constants;
import com.muchinfo.mtp3common.enumtype.FunCodeConstants;
import com.muchinfo.mtp3common.enumtype.MessageType;
import com.muchinfo.mtp3common.enumtype.SysConstants;
import com.muchinfo.mtp3common.utils.DateTimeUtils;
import com.muchinfo.mtp3common.utils.EncryptionUtils;
import com.muchinfo.mtp3common.utils.ExportUtil;
import com.muchinfo.mtp3common.utils.SerialNumberUtils;
import com.muchinfo.mtp3common.vo.Calculator;
import com.muchinfo.mtp3common.vo.ExportResult;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3common.vo.ProtoHelper;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.bankbusiness.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Service
public class BankBusinessServiceImpl implements IBankBusinessService {

    private final String BANK_TYPE_JDJS = "jdjs";
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private IBankSystemconfigMapper iBankSystemconfigMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ISystemmanagerlogMapper iSystemmanagerlogMapper;
    @Resource
    private IBankCusbankinfoMapper iBankCusbankinfoMapper;
    @Resource
    private IBankCusbankchargeMapper iBankCusbankchargeMapper;
    @Resource
    private IBankCusbankchargedetailMapper iBankCusbankchargedetailMapper;
    @Resource
    private IBankBankinfoMapper iBankBankinfoMapper;
    @Resource
    private IBankAccountsignMapper iBankAccountsignMapper;
    @Resource
    private IBankCusbanksignbankMapper iBankCusbanksignbankMapper;
    @Resource
    private IBankCusbankstatusMapper iBankCusbankstatusMapper;
    @Resource
    private IBankCusbankextendconfigMapper iBankCusbankextendconfigMapper;
    @Resource
    private IBankExtendfieldMapper iBankExtendfieldMapper;
    @Resource
    private IEnumdicitemMapper iEnumdicitemMapper;
    @Resource
    private IBankAccountsignlogMapper iBankAccountsignlogMapper;
    @Resource
    private IHybridChannelConfigMapper iHybridChannelConfigMapper;
    @Resource
    private IHybridBankinfoMapper iHybridBankinfoMapper;
    @Resource
    private ITaaccountMapper iTaaccountMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private IBankAmounttransferMapper iBankAmounttransferMapper;
    @Resource
    private IMarketrunMapper iMarketrunMapper;
    @Override
    public AjaxResult<BankSystemconfig> banksystemconfig(HttpServletRequest request) {
        List<BankSystemconfig> bankSystemconfigs = iBankSystemconfigMapper.selectList(new QueryWrapper<>());
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), bankSystemconfigs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveSystemDetail(BankSystemConfigParam param, HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Systemmanagerlog log = new Systemmanagerlog();
        BankSystemconfig bConfig = null;
        StringBuilder builder = new StringBuilder("{");
        for (BankSystemconfig bankSystem : param.getBankSystemConfigs()) {
            bConfig = iBankSystemconfigMapper.selectOne(new QueryWrapper<BankSystemconfig>().eq("CONFIGID", bankSystem.getConfigid()));
            if (bConfig == null) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM029.getCode(), request.getHeader("Accept-Language"));
            }
            bConfig.setConfigvalue(bankSystem.getConfigvalue());
            iBankSystemconfigMapper.update(bConfig, new QueryWrapper<BankSystemconfig>().eq("CONFIGID", bankSystem.getConfigid()));
            builder.append("\"" + bConfig.getRemark() + "\":\"" + bankSystem.getConfigvalue() + "\"");
            builder.append(",");
        }
        log.setUserid(user.getAutoid());
        log.setReletype(user.getReletype());
        log.setLogincode(user.getLogincode());
        log.setUsername(user.getUsername());
        log.setParentuserid(user.getAreauserid());
        log.setOperatetime(new Date());
        log.setIp(user.getLoginip());
        log.setResourcecode(SysConstants.BANK_SYSTEMCONFIG);
        log.setNewvalue(builder.toString().substring(0, builder.toString().length() - 1) + "}");
        log.setContent("修改银行系统配置{\"marketId\":" + bConfig.getConfigid() + "}成功");
        log.setOldvalue("{\"marketId\":" + bConfig.getConfigid() + "}");
        log.setRemark("[{\"bankSystemConfigs\":" + bConfig.getConfigid() + "," + bConfig.getConfigcode() + "}]");
        log.setResourcename("银行系统配置");

        iSystemmanagerlogMapper.insert(log);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<BankCusbankinfo> bankcusquery(HttpServletRequest request) {
        List<BankCusbankinfo> bankCusbankinfos = iBankCusbankinfoMapper.selectList(new QueryWrapper<>());
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), bankCusbankinfos);
    }

    @Override
    public AjaxResult<BankCusbankinfoDetailResult> bankcusdetail(String cusbankid, HttpServletRequest request) {
        BankCusbankinfoDetailResult result = new BankCusbankinfoDetailResult();
        BankCusbankinfo bankCusbankinfo = iBankCusbankinfoMapper.selectOne(new QueryWrapper<BankCusbankinfo>().eq("cusbankid", cusbankid));
        result.setBankCusbankinfo(bankCusbankinfo);

        List<BankCusbankcharge> charges = iBankCusbankchargeMapper.selectList(new QueryWrapper<BankCusbankcharge>().eq("cusbankid", cusbankid));
        if (!charges.isEmpty()) {
            for (BankCusbankcharge charge : charges) {
                if (null != charge.getChargealgorithm() && charge.getChargealgorithm() == 1) { //手续费收取方式 - 1:比率  2:固定  [统一 ]
                    charge.setChargevalue(charge.getChargevalue().multiply(new BigDecimal("100")).setScale(4, BigDecimal.ROUND_DOWN).stripTrailingZeros());
                }
                List<BankCusbankchargedetail> chargedetails;
                //这里分别查一下，页面出来起来清晰
                if (charge.getOutorin() == 2) {//1.入金手续费
                    if (charge.getUsertype() == 2) { //1.1 对公
                        result.setCharge(charge);
                        result.setIscheckin(1);
                        if (charge.getChargetype() == 2) {
                            chargedetails = iBankCusbankchargedetailMapper.selectList(new QueryWrapper<BankCusbankchargedetail>()
                                    .eq("outorin", 2)
                                    .eq("usertype", 2));
                            for (BankCusbankchargedetail chargeDetail : chargedetails) {
                                if (null != chargeDetail.getChargealgorithm() && chargeDetail.getChargealgorithm() == 1) {
                                    chargeDetail.setChargevalue(chargeDetail.getChargevalue().multiply(new BigDecimal("100")).setScale(4, BigDecimal.ROUND_HALF_UP).stripTrailingZeros());
                                }
                            }
                            result.setRange(chargedetails);
                        }
                    } else { //1.2 对私
                        result.setCharge(charge);
                        result.setIscheckin(1);
                        if (charge.getChargetype() == 2) {
                            chargedetails = iBankCusbankchargedetailMapper.selectList(new QueryWrapper<BankCusbankchargedetail>()
                                    .eq("outorin", 2)
                                    .eq("usertype", 1));
                            for (BankCusbankchargedetail chargeDetail : chargedetails) {
                                if (null != chargeDetail.getChargealgorithm() && chargeDetail.getChargealgorithm() == 1) {
                                    chargeDetail.setChargevalue(chargeDetail.getChargevalue().multiply(new BigDecimal("100")).setScale(4, BigDecimal.ROUND_HALF_UP).stripTrailingZeros());
                                }
                            }
                            result.setRange(chargedetails);
                        }
                    }
                } else {//2.出金手续费
                    if (charge.getUsertype() == 2) { //2.1 对公
                        result.setCharge(charge);
                        result.setIscheckout(1);
                        if (charge.getChargetype() == 2) {
                            chargedetails = iBankCusbankchargedetailMapper.selectList(new QueryWrapper<BankCusbankchargedetail>()
                                    .eq("outorin", 1)
                                    .eq("usertype", 2));
                            for (BankCusbankchargedetail chargeDetail : chargedetails) {
                                if (null != chargeDetail.getChargealgorithm() && chargeDetail.getChargealgorithm() == 1) {
                                    chargeDetail.setChargevalue(chargeDetail.getChargevalue().multiply(new BigDecimal("100")).setScale(4, BigDecimal.ROUND_HALF_UP).stripTrailingZeros());
                                }
                            }
                            result.setRange(chargedetails);
                        }
                    } else { //2.2 对私
                        result.setCharge(charge);
                        result.setIscheckout(1);
                        if (charge.getChargetype() == 2) {
                            chargedetails = iBankCusbankchargedetailMapper.selectList(new QueryWrapper<BankCusbankchargedetail>()
                                    .eq("outorin", 1)
                                    .eq("usertype", 1));
                            for (BankCusbankchargedetail chargeDetail : chargedetails) {
                                if (null != chargeDetail.getChargealgorithm() && chargeDetail.getChargealgorithm() == 1) {
                                    chargeDetail.setChargevalue(chargeDetail.getChargevalue().multiply(new BigDecimal("100")).setScale(4, BigDecimal.ROUND_HALF_UP).stripTrailingZeros());
                                }
                            }
                            result.setRange(chargedetails);
                        }
                    }
                }
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult<BankBankinfo> queryBankInfoSelect(String searchcode, HttpServletRequest request) {
        List<BankBankinfo> bankBankinfos = iBankBankinfoMapper.selectList(new QueryWrapper<BankBankinfo>()
                .like("bankname", searchcode)
                .last("rownum &lt;= 10"));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), bankBankinfos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult dealBankInfo(BankCusBankInfoParam param, HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getCusbankinfo() != null && !param.getCusbankinfo().isEmpty()) {
            return updateBankInfo(param, param.getCusbankinfo(), request);
        } else {
            return saveBankInfo(param, request);
        }
    }

    private AjaxResult updateBankInfo(BankCusBankInfoParam param, String cusbankinfo, HttpServletRequest request) {
        if (cusbankinfo != null && !cusbankinfo.isEmpty()) {
            if (!cusbankinfo.equals(param.getCusbankid())) {
                BankCusbankinfo bankCus = iBankCusbankinfoMapper.selectOne(new QueryWrapper<BankCusbankinfo>().eq("cusbankid", param.getCusbankid()));
                if (bankCus != null) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM031.getCode(), request.getHeader("Accept-Language"));
                }

                BankCusbankstatus bankCusbankstatus = iBankCusbankstatusMapper.selectOne(new QueryWrapper<BankCusbankstatus>()
                        .eq("cusbankid", param.getCusbankid()));
                bankCusbankstatus.setCusbankid(param.getCusbankid());
                iBankCusbankstatusMapper.update(bankCusbankstatus, new QueryWrapper<BankCusbankstatus>()
                        .eq("cusbankid", param.getCusbankid()));
            }
        }

        if (cusbankinfo != null && !cusbankinfo.isEmpty()) {
            iBankCusbankinfoMapper.delete(new QueryWrapper<BankCusbankinfo>().eq("cusbankid", cusbankinfo));
        }
        BankCusbankinfo bankCusBankInfo = insertBankInfo(param);
        iBankCusbankinfoMapper.insert(bankCusBankInfo);

        //托管银行手续费
        //出入金手续费区间配置
        iBankCusbankchargedetailMapper.delete(new QueryWrapper<BankCusbankchargedetail>().eq("cusbankid", param.getCusbankid()));
        //出入金手续费配置先删除再添加
        iBankCusbankchargeMapper.delete(new QueryWrapper<BankCusbankcharge>().eq("cusbankid", param.getCusbankid()));

        dealCharge(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private AjaxResult saveBankInfo(BankCusBankInfoParam param, HttpServletRequest request) {
        BankCusbankinfo bankCus = iBankCusbankinfoMapper.selectOne(new QueryWrapper<BankCusbankinfo>().eq("cusbankid", param.getCusbankid()));
        if (bankCus != null) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM031.getCode(), request.getHeader("Accept-Language"));
        }
        BankCusbankinfo bankCusBankInfo = insertBankInfo(param);
        iBankCusbankinfoMapper.insert(bankCusBankInfo);

        //状态表
        BankCusbankstatus status = new BankCusbankstatus();
        status.setCusbankid(param.getCusbankid());
        status.setTradedate(DateTimeUtils.format(new Date(), DateTimeUtils.DATE_CHAR_PATTERN));
        status.setSignstatus(2);
        iBankCusbankstatusMapper.insert(status);

        //新增托管银行时   默认将所有银行插入支持银行表中
        //查询所有银行
        List<BankBankinfo> bankInfos = iBankBankinfoMapper.selectList(new QueryWrapper<BankBankinfo>().eq("status", 0));
        for (BankBankinfo bInfo : bankInfos) {
            BankCusbanksignbank bankSignbank = new BankCusbanksignbank();
            bankSignbank.setCusbankid(param.getCusbankid());
            bankSignbank.setBankid(bInfo.getBankid());
            iBankCusbanksignbankMapper.insert(bankSignbank);
        }

        //托管银行手续费
        dealCharge(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private void dealCharge(BankCusBankInfoParam param) {
        if (null != param.getCharge()) {
            for (BankCusbankcharge bankChaConfig : param.getCharge()) {
                BankCusbankcharge bankCharge = new BankCusbankcharge();
                if (bankChaConfig != null) {
                    BeanUtils.copyProperties(bankChaConfig, bankCharge);
                    if (bankChaConfig.getChargetype() == 1) {
                        bankCharge.setChargealgorithm(bankChaConfig.getChargealgorithm());
                        if (null != bankChaConfig.getChargealgorithm() && bankChaConfig.getChargealgorithm() == 1) {
                            //比率  /100
                            bankCharge.setChargevalue(bankChaConfig.getChargevalue().divide(new BigDecimal(100)));
                        } else if (bankChaConfig.getChargealgorithm() == 2) {
                            //固定
                            bankCharge.setChargevalue(bankChaConfig.getChargevalue());
                        }
                        bankCharge.setSinglemin(bankChaConfig.getSinglemin());
                        bankCharge.setSinglemax(bankChaConfig.getSinglemax());
                    }
                    iBankCusbankchargeMapper.insert(bankCharge);
                }
            }
        }
        if (null != param.getChargeDetail()) {
            for (BankCusbankchargedetail bRConfig : param.getChargeDetail()) {
                BankCusbankchargedetail bRangeConfig = new BankCusbankchargedetail();
                if (bRConfig != null) {
                    BeanUtils.copyProperties(bRConfig, bRangeConfig);
                    if (null != bRConfig.getChargealgorithm() && bRConfig.getChargealgorithm() == 1) {
                        bRangeConfig.setChargevalue(bRConfig.getChargevalue().divide(new BigDecimal(100)));
                    } else {
                        bRangeConfig.setChargevalue(bRConfig.getChargevalue());
                    }
                    iBankCusbankchargedetailMapper.insert(bRangeConfig);
                }
            }
        }
    }

    private static BankCusbankinfo insertBankInfo(BankCusBankInfoParam param) {
        BankCusbankinfo bankCusBankInfo = new BankCusbankinfo();
        bankCusBankInfo.setCusbankid(param.getCusbankid());
        bankCusBankInfo.setCusbankname(param.getCusbankname());
        bankCusBankInfo.setCusbankshortname(param.getCusbankshortname());
        bankCusBankInfo.setExchbankid(param.getExchbankid());
        bankCusBankInfo.setExchpaybankaccno(param.getExchpaybankaccno());
        bankCusBankInfo.setExchpaybankaccname(param.getExchpaybankaccname());
        bankCusBankInfo.setCurrency(param.getCurrency());
        bankCusBankInfo.setCansign(param.getCansign());
        bankCusBankInfo.setCanrelease(param.getCanrelease());
        bankCusBankInfo.setCaninamount(param.getCaninamount());
        bankCusBankInfo.setCanoutamount(param.getCanoutamount());
        bankCusBankInfo.setCansign2(param.getCansign2());
        bankCusBankInfo.setCanrelease2(param.getCanrelease2());
        bankCusBankInfo.setCaninamount2(param.getCaninamount2());
        bankCusBankInfo.setCanoutamount2(param.getCanoutamount2());
        bankCusBankInfo.setRiskinfo(param.getRiskinfo());
        bankCusBankInfo.setCanbindcard(param.getCanbindcard());
        bankCusBankInfo.setIsneedclear(param.getIsneedclear());
        bankCusBankInfo.setCanmodifyphone(param.getCanmodifyphone());
        bankCusBankInfo.setCanmodifysigninfo(param.getCanmodifysigninfo());
        bankCusBankInfo.setExputbankid(param.getExputbankid());
        bankCusBankInfo.setExputpaybankaccno(param.getExputpaybankaccno());
        bankCusBankInfo.setExputpaybankaccsubno(param.getExputpaybankaccsubno());
        bankCusBankInfo.setExputpaybankaccname(param.getExputpaybankaccname());
        bankCusBankInfo.setIsmix(param.getIsmix());
        bankCusBankInfo.setAreainauditflag(param.getAreainauditflag());
        bankCusBankInfo.setInvestorinauditflag(param.getInvestorinauditflag());
        bankCusBankInfo.setAreaoutauditflag(param.getAreaoutauditflag());
        bankCusBankInfo.setAreaoutauditamount(param.getAreaoutauditamount());
        bankCusBankInfo.setAreaoutauditflag2(param.getAreaoutauditflag2());
        bankCusBankInfo.setInvestoroutauditflag(param.getInvestoroutauditflag());
        bankCusBankInfo.setInvestoroutauditamount(param.getInvestoroutauditamount());
        bankCusBankInfo.setInvestoroutauditflag2(param.getInvestoroutauditflag2());
        return bankCusBankInfo;
    }

    @Override
    public AjaxResult deleteBankInfo(String cusbankid, HttpServletRequest request) {
        //查询是否已用此渠道签约  状态为1 未签约  7 已解约  时可以删除  其他不能删除
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cusbankid", cusbankid);
        //查询签约  状态 不为  1,7 的数据
        List<BankAccountsign> accountSign = iBankAccountsignMapper.selectList(new QueryWrapper<BankAccountsign>()
                .eq("cusbankid", cusbankid)
                .in("signstatus", 2, 3, 4, 5, 6, 8, 9, 10));
        if (!accountSign.isEmpty()) {
            //已用此渠道签约  并且状态不为 1,7 不能删除
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM030.getCode(), request.getHeader("Accept-Language"));
        } else {
            //未用此渠道签约   或者  已用此渠道签约 ，并且状态为 1,7
            //删除关联支持银行
            iBankCusbanksignbankMapper.delete(new QueryWrapper<BankCusbanksignbank>().eq("cusbankid", cusbankid));
            //删除扩展设置
            iBankCusbankextendconfigMapper.delete(new QueryWrapper<BankCusbankextendconfig>().eq("cusbankid", cusbankid));
            //删除托管银行状态表Bank_CusBankStatus
            iBankCusbankstatusMapper.delete(new QueryWrapper<BankCusbankstatus>().eq("cusbankid", cusbankid));
            //删除托管银行信息
            iBankCusbankinfoMapper.delete(new QueryWrapper<BankCusbankinfo>().eq("cusbankid", cusbankid));
            //删除托管银行手续费相关
            iBankCusbankchargeMapper.delete(new QueryWrapper<BankCusbankcharge>().eq("cusbankid", cusbankid));
            iBankCusbankchargedetailMapper.delete(new QueryWrapper<BankCusbankchargedetail>().eq("cusbankid", cusbankid));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<BankCusbankextendconfig> queryExtendset(String cusbankid, HttpServletRequest request) {
        List<BankCusbankextendconfig> config = iBankCusbankextendconfigMapper.queryExtendset(cusbankid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), config);
    }

    @Override
    public AjaxResult<BankExtendBizTypeResult> extendBizTypeInit(String cusbankid, HttpServletRequest request) {
        BankExtendBizTypeResult result = new BankExtendBizTypeResult();
        List<BankExtendfield> bankExtendFields = iBankExtendfieldMapper.selectList(new QueryWrapper<>());
        result.setExtendfields(bankExtendFields);

        List<Enumdicitem> enumdicitemList = iEnumdicitemMapper.querybiztypeList(cusbankid);
        result.setEnumdicitemList(enumdicitemList);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult<BankCusbankextendconfig> extendDetail(String cusbankid, Integer extendbiztype, HttpServletRequest request) {
        BankCusbankextendconfig config = iBankCusbankextendconfigMapper.selectOne(new QueryWrapper<BankCusbankextendconfig>()
                .eq("cusbankid", cusbankid)
                .eq("extendbiztype", extendbiztype));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), config);
    }

    @Override
    public AjaxResult dealBankExtend(BankExtendAddParam param, HttpServletRequest request) {
        //先删除 再新增
        iBankCusbankextendconfigMapper.delete(new QueryWrapper<BankCusbankextendconfig>()
                .eq("cusbankid", param.getCusbankid())
                .eq("extendbiztype", param.getExtendbiztype()));

        String[] extendList = param.getFieldids().split(",");
        for (String cusbankExtend : extendList) {
            BankCusbankextendconfig bankConfig = new BankCusbankextendconfig();
            bankConfig.setCusbankid(param.getCusbankid());
            bankConfig.setExtendbiztype(param.getExtendbiztype());
            bankConfig.setFieldid(Long.valueOf(cusbankExtend));
            //勾选的都默认必填
            bankConfig.setIsmandatory(1);
            iBankCusbankextendconfigMapper.insert(bankConfig);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult delExtend(String cusbankid, Integer extendbiztype, HttpServletRequest request) {
        iBankCusbankextendconfigMapper.delete(new QueryWrapper<BankCusbankextendconfig>()
                .eq("cusbankid", cusbankid)
                .eq("extendbiztype", extendbiztype));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<BankCusbanksignbank> queryBankSignList(String cusbankid, HttpServletRequest request) {
        List<BankCusbanksignbank> list = iBankCusbanksignbankMapper.queryBankSignList(cusbankid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), list);
    }

    @Override
    public AjaxResult<BankBankinfo> queryBankInfoNotExist(String cusbankid, HttpServletRequest request) {
        List<BankBankinfo> list = iBankCusbanksignbankMapper.queryBankInfoNotExist(cusbankid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), list);
    }

    @Override
    public AjaxResult delBankInfo(String cusbankid, Integer bankid, HttpServletRequest request) {
        iBankCusbanksignbankMapper.delete(new QueryWrapper<BankCusbanksignbank>()
                .eq("cusbankid", cusbankid)
                .eq("bankid", bankid));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult dealBankCusBankSign(BankCusBankSignAddParam param, HttpServletRequest request) {
        BankCusbanksignbank bankSignbank = new BankCusbanksignbank();
        bankSignbank.setCusbankid(param.getCusbankid());
        bankSignbank.setBankid(param.getBankid());
        iBankCusbanksignbankMapper.insert(bankSignbank);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<BankAccountSignLogQueryResult> signLogQuery(BankAccountSignLogQueryParam param, HttpServletRequest request) {
        if (param.getStartdate() != null && !param.getStartdate().isEmpty()) {
            param.setStartdate(param.getStartdate() + " 00:00:00");
        }
        if (param.getEnddate() != null && !param.getEnddate().isEmpty()) {
            param.setEnddate(param.getEnddate() + " 23:59:59");
        }
        param.setAccountcode(param.getAccountcode() == null ?
                null : param.getAccountcode().trim());
        if (param.getUsertype() != null) {
            if (param.getUsertype() == 2) {
                param.setUsertypes("2,3");
            } else {
                param.setUsertypes(param.getUsertype().toString());
            }
        }

        IPage<BankAccountSignLogQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<BankAccountSignLogQueryResult> resultPage = iBankAccountsignlogMapper.signLogQuery(page, param);
        //返回列表
        PageResult<BankAccountSignLogQueryResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultPage.getPages());
        pageResult.setCurrent(resultPage.getCurrent());
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setPageSize(resultPage.getSize());
        pageResult.setData(resultPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<BankAccountsignlog> signLogDetail(String cusbankid, Integer exchticket, HttpServletRequest request) {
        BankAccountsignlog sign = iBankAccountsignlogMapper.selectOne(new QueryWrapper<BankAccountsignlog>()
                .eq("cusbankid", cusbankid)
                .eq("exchticket", exchticket));

        //出入金查询
        sign.setBankaccountname(EncryptionUtils.decryptForAES(sign.getBankaccountname()));
        sign.setAccountname(EncryptionUtils.decryptForAES(sign.getAccountname()));
        sign.setMobilephone(EncryptionUtils.decryptForAES(sign.getMobilephone()));
        sign.setCardno(EncryptionUtils.decryptForAES(sign.getCardno()));
        sign.setBankaccountno(EncryptionUtils.decryptForAES(sign.getBankaccountno()));

        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), sign);
    }

    @Override
    public AjaxResult signLogExport(BankAccountSignLogQueryParam param, HttpServletRequest request) {
        if (param.getStartdate() != null && !param.getStartdate().isEmpty()) {
            param.setStartdate(param.getStartdate() + " 00:00:00");
        }
        if (param.getEnddate() != null && !param.getEnddate().isEmpty()) {
            param.setEnddate(param.getEnddate() + " 23:59:59");
        }
        param.setAccountcode(param.getAccountcode() == null ?
                null : param.getAccountcode().trim());
        if (param.getUsertype() != null) {
            if (param.getUsertype() == 2) {
                param.setUsertypes("2,3");
            } else {
                param.setUsertypes(param.getUsertype().toString());
            }
        }
        try {
            String fileName = "签解约查询_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<BankAccountSignLogQueryResult> resultIPage = iBankAccountsignlogMapper.signLogQuery(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, BankAccountSignLogQueryResult.class, resultIPage);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("签解约查询导出失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult<HybridChannelConfig> querymixbanklist(HttpServletRequest request) {
        List<HybridChannelConfig> configs = iHybridChannelConfigMapper.selectList(new QueryWrapper<>());
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), configs);
    }

    @Override
    public AjaxResult mixbankeditsubmit(BankMixBankUpdateParam param, HttpServletRequest request) {
        HybridChannelConfig vo = iHybridChannelConfigMapper.selectOne(new QueryWrapper<HybridChannelConfig>().eq("channelCode", param.getChannelCode()));
        if (vo != null) {
            vo.setChannelName(param.getChannelName());
            vo.setCanAmtIn(param.getCanAmtIn());
            vo.setCanAmtOut(param.getCanAmtOut());
            iHybridChannelConfigMapper.update(vo, new QueryWrapper<HybridChannelConfig>().eq("channelCode", param.getChannelCode()));

        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult deletemixbankedit(String channelCode, HttpServletRequest request) {
        iHybridChannelConfigMapper.delete(new QueryWrapper<HybridChannelConfig>().eq("channelCode", channelCode));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<HybridBankinfo> querychannelbanklist(BankChannleBankParam param, HttpServletRequest request) {
        IPage<HybridBankinfo> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<HybridBankinfo> resultPage = iHybridBankinfoMapper.selectPage(page, new QueryWrapper<HybridBankinfo>()
                .eq(StringUtils.isNotBlank(param.getChannelCode()), "channel_code", param.getChannelCode())
                .eq(param.getOutInFlag() != null, "out_in_flag", param.getOutInFlag())
                .and(a -> a.like(StringUtils.isNotBlank(param.getBankCodeName()), "bank_code", param.getChannelCode())
                        .or().like(StringUtils.isNotBlank(param.getBankCodeName()), "bank_name", param.getChannelCode())
                ));
        //返回列表
        PageResult<HybridBankinfo> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultPage.getPages());
        pageResult.setCurrent(resultPage.getCurrent());
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setPageSize(resultPage.getSize());
        pageResult.setData(resultPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<BankQueryAccInfoResult> bankQueryAccInfo(Integer accountid, HttpServletRequest request) {
        BankQueryAccInfoResult result = iTaaccountMapper.bankQueryAccInfo(accountid);
        if (!Objects.isNull(result)) {
            double canUserAccount;
            BankAccountsign bankAccSign = iBankAccountsignMapper.selectOne(new QueryWrapper<BankAccountsign>()
                    .eq("accountcode", String.valueOf(accountid)));
            Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_bank);

            Calculator ca = new Calculator(uuid);
            SerialNumberUtils.lockMap.put(uuid, ca);
            BankMI1.t2bQueryAccInfosReq.Builder builder = BankMI1.t2bQueryAccInfosReq.newBuilder();
            Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
            hd.setUUID(uuid.toString());
            hd.setFunCode(FunCodeConstants.FunCode_Trade_t2bQueryAccInfosReq);

            builder.setExtOperatorID(uuid);
            if (bankAccSign != null) {
                hd.setAccountID(Long.parseLong(bankAccSign.getAccountcode()));
                builder.setHeader(hd);
                builder.setCusBankID(bankAccSign.getCusbankid());
                builder.setAccountCode(bankAccSign.getAccountcode());
                if (StringUtils.isNotBlank(bankAccSign.getAccountname())) {
                    builder.setBankChildAccountName(bankAccSign.getAccountname());
                }
                if (StringUtils.isNotBlank(bankAccSign.getBankchildaccount())) {
                    builder.setBankChildAccount(bankAccSign.getBankchildaccount());
                }
                // 查询类别[1-查询所有信息;2-查询余额;3-查询银行卡]
                builder.setQueryType("2");
            } else {
                builder.setHeader(hd);
                builder.setCusBankID("");
                builder.setAccountCode("");
                builder.setBankChildAccountName("");
                builder.setBankChildAccount("");
                builder.setQueryType("2");
            }
            log.debug(builder.build().toString());
            byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(),
                    FunCodeConstants.FunCode_Trade_t2bQueryAccInfosReq);
            rabbitTemplate.send(SysConstants.RabbitBankNtfKey,
                    new Message(body, new MessageProperties()));
            synchronized (ca) {
                try {
                    ca.wait(10000);
                    Object rsp = ca.obj;
                    if (rsp != null) {
                        BankMI1.t2bQueryAccInfosRsp rsp_ = (BankMI1.t2bQueryAccInfosRsp) rsp;
                        canUserAccount = rsp_.getCanUseAmount();
                        result.setCanUserAccount(BigDecimal.valueOf(canUserAccount));
                    } else {
                        result.setCanUserAccount(BigDecimal.ZERO);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    SerialNumberUtils.lockMap.remove(uuid);
                }
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public PageResult<BankAmounttransfer> queryCommission(BankCommissionParam param, HttpServletRequest request) {
        IPage<BankAmounttransfer> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<BankAmounttransfer> resultIPage = iBankAmounttransferMapper.selectPage(page, new QueryWrapper<BankAmounttransfer>()
                .eq(StringUtils.isNotBlank(param.getCusbankid()), "cusbankid", param.getCusbankid())
                .eq(param.getApplystatus() != null, "applystatus", param.getApplystatus()));
        PageResult<BankAmounttransfer> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<BigDecimal> queryMoneyjdjs(String cusbankid, String acctype, HttpServletRequest request) {
        String bankNo;
        Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_bank);
        BankMI1.t2bQueryAccInfosReq.Builder builder = BankMI1.t2bQueryAccInfosReq.newBuilder();
        BankCusbankinfo info = iBankCusbankinfoMapper.selectOne(new QueryWrapper<BankCusbankinfo>()
                .eq("CUSBANKID", cusbankid));
        //数据检查
        if (StringUtils.isBlank(info.getExputbankid()) || StringUtils.isBlank(info.getExputpaybankaccname()) || StringUtils.isBlank(info.getExputpaybankaccno())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM032.getCode(), request.getHeader("Accept-Language"));
        }
        if (BANK_TYPE_JDJS.equals(info.getCusbankid())) {
            bankNo = info.getExputpaybankaccsubno();
        } else {
            bankNo = info.getExchpaybankaccno();
        }
        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        hd.setFunCode(FunCodeConstants.FunCode_Trade_t2bQueryAccInfosReq);
        builder.setHeader(hd);
        builder.setCusBankID(cusbankid);
        builder.setExtOperatorID(uuid);
        builder.setTradeDate(DateTimeUtils.format(new Date(), DateTimeUtils.DATE_CHAR_PATTERN));
        //光大没有查询账户要求，特殊处理，金登需要配置查询账户
        builder.setAccountCode(bankNo);
        builder.setQueryType(acctype.toString());

        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(),
                FunCodeConstants.FunCode_Trade_t2bQueryAccInfosReq);
        log.debug(builder.build().toString());
        Calculator ca = new Calculator(uuid);
        SerialNumberUtils.lockMap.put(uuid, ca);

        rabbitTemplate.send(SysConstants.RabbitBankNtfKey, new Message(body, new MessageProperties()));

        synchronized (ca) {
            try {
                ca.wait(10000);
                Object rsp = ca.obj;
                if (rsp != null) {
                    BankMI1.t2bQueryAccInfosRsp rsp_ = (BankMI1.t2bQueryAccInfosRsp) rsp;
                    return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), rsp_.getCanUseAmount());

                } else {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM006.getCode(), request.getHeader("Accept-Language"));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                SerialNumberUtils.lockMap.remove(uuid);
            }
        }
        return null;
    }

    @Override
    public AjaxResult addjdjs(BankAmounttransfer transfer, HttpServletRequest request) {
        BankCusbankinfo info = iBankCusbankinfoMapper.selectOne(new QueryWrapper<BankCusbankinfo>()
                .eq("CUSBANKID", transfer.getCusbankid()));
        Marketrun marketRun = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid",6L));
        if(transfer.getAmount().compareTo(BigDecimal.ZERO) == 0){
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM033.getCode(), request.getHeader("Accept-Language"));
        }
        if (StringUtils.isBlank(info.getExputbankid()) || StringUtils.isBlank(info.getExputpaybankaccname()) || StringUtils.isBlank(info.getExputpaybankaccno())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM032.getCode(), request.getHeader("Accept-Language"));
        }
        if(41 != marketRun.getRunstatus()){
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM034.getCode(), request.getHeader("Accept-Language"));
        }
        //金登查询时间特殊处理
        int time = 10000;
        if(BANK_TYPE_JDJS.equals(info.getCusbankid())){
            time = 60000;
        }

        Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_bank);

        BankMI1.t2bExchOutInBankReq.Builder builder = BankMI1.t2bExchOutInBankReq.newBuilder();

        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        hd.setFunCode(FunCodeConstants.FunCode_Trade_t2bExchOutInBankReq);
        builder.setHeader(hd);

        builder.setCusBankID(transfer.getCusbankid());
        builder.setExtOperatorID(uuid);
        builder.setTradeDate(DateTimeUtils.format(new Date(), DateTimeUtils.DATE_CHAR_PATTERN));
        builder.setTransferType(transfer.getTransfertype());
        builder.setAmount(transfer.getAmount().doubleValue());
        builder.setCurrency(info.getCurrency());
        builder.setBankAccNo(info.getExchpaybankaccno());
        builder.setBankAccName(info.getExchpaybankaccname());
        builder.setTargetBankId(info.getExputbankid());
        builder.setTargetBankAccNo(info.getExputpaybankaccno());
        builder.setTargetBankAccName(info.getExputpaybankaccname());

        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(),
                FunCodeConstants.FunCode_Trade_t2bExchOutInBankReq);

        Calculator ca = new Calculator(uuid);
        SerialNumberUtils.lockMap.put(uuid, ca);
        log.debug(builder.build().toString());
        rabbitTemplate.send(SysConstants.RabbitBankNtfKey, new Message(body, new MessageProperties()));

        synchronized (ca) {
            try {
                ca.wait(time);
                Object rsp = ca.obj;
                if (rsp != null) {
                    BankMI1.t2bExchOutInBankRsp rsp_ = (BankMI1.t2bExchOutInBankRsp) rsp;
                    if (rsp_.getStatus() == 0) {
                        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
                    } else {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM002.getCode(), request.getHeader("Accept-Language"),rsp_.getBankRetMsg());
                    }
                } else {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM006.getCode(), request.getHeader("Accept-Language"));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                SerialNumberUtils.lockMap.remove(uuid);
            }
        }
        return null;
    }
}
