package com.muchinfo.mtp3century.service.impl;

import com.alibaba.fastjson2.JSONObject;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muchinfo.mtp.proto.AkernelMI1;
import com.muchinfo.mtp.proto.Common;
import com.muchinfo.mtp.proto.ShortMessageMtp1;
import com.muchinfo.mtp.proto.convert.ServiceMemoryCache;
import com.muchinfo.mtp3century.exception.GlobalException;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.ISendMsgService;
import com.muchinfo.mtp3century.service.ISystemmanagerService;
import com.muchinfo.mtp3century.service.IUseraccountService;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3common.enumtype.*;
import com.muchinfo.mtp3common.utils.*;
import com.muchinfo.mtp3common.vo.*;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.ProtoErrorCodes;
import com.muchinfo.mtp3pojos.vo.investor.*;
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.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author XKF
 * @since 2024-04-16
 */
@Service
public class UseraccountServiceImpl extends ServiceImpl<IUseraccountMapper, Useraccount> implements IUseraccountService {

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

    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ISystemmanagerService iSystemmanagerService;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private IArearoleMapper iArearoleMapper;
    @Resource
    private IUserinfoMapper iUserinfoMapper;
    @Resource
    private IUseresignrecordMapper iUseresignrecordMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private IGoodsMapper iGoodsMapper;
    @Resource
    private IMarketMapper iMarketMapper;
    @Resource
    private ITodayAccountmarginMapper iTodayAccountmarginMapper;
    @Resource
    private ITodayAccounttraderuleMapper iTodayAccounttraderuleMapper;
    @Resource
    private ITodayAccounttradefeeMapper iTodayAccounttradefeeMapper;
    @Resource
    private ITraderuledescriptionMapper iTraderuledescriptionMapper;
    @Resource
    private ITradefeedescriptionMapper iTradefeedescriptionMapper;
    @Resource
    private IDraftUserinfoMapper iDraftUserinfoMapper;
    @Resource
    private IDraftUseraccountNewMapper iDraftUseraccountNewMapper;
    @Resource
    private ISendMsgService iSendMsgService;
    @Resource
    private IUserauthinfoMapper iUserauthinfoMapper;
    @Resource
    private SystemmanagerServiceImpl systemmanagerService;
    @Resource
    private ITaaccountMapper iTaaccountMapper;
    @Resource
    private IRiskratiotypeMapper iRiskratiotypeMapper;
    @Resource
    private IUsergroupMapper iUsergroupMapper;
    @Resource
    private IUsergroupdetailMapper iUsergroupdetailMapper;
    @Resource
    private IUsergrouptradeconfigMapper iUsergrouptradeconfigMapper;
    @Resource
    private IAccountriskconfigMapper iAccountriskconfigMapper;
    @Resource
    private IEnumdicitemMapper iEnumdicitemMapper;
    @Resource
    private IAccounttradeconfigMapper iAccounttradeconfigMapper;
    @Resource
    private IUsercancelapplyMapper iUsercancelapplyMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private IBankAccountsignMapper iBankAccountsignMapper;


    @Override
    public PageResult<DealerQueryResult> queryOrganPage(DealerQueryParam dealerQueryParam, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //如果不是平台管理员
        if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {
            dealerQueryParam.setParentUserId(systemmanager.getAreauserid());
        }
        IPage<DealerQueryResult> page = new Page<>(dealerQueryParam.getPageNum(), dealerQueryParam.getPageSize());
        IPage<DealerQueryResult> dealerQueryResults = iUseraccountMapper.queryInvestorPage(page, dealerQueryParam);
        return getDealerQueryResultPageResult(dealerQueryResults, request);
    }

    private PageResult<DealerQueryResult> getDealerQueryResultPageResult(IPage<DealerQueryResult> dealerQueryResults, HttpServletRequest request) {
        PageResult<DealerQueryResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(dealerQueryResults.getPages());
        pageResult.setCurrent(dealerQueryResults.getCurrent());
        pageResult.setTotal(dealerQueryResults.getTotal());
        pageResult.setPageSize(dealerQueryResults.getSize());
        pageResult.setData(dealerQueryResults.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<DealerQueryDetailResult> initQueryDetail(DealerQueryDetailParam dealerQueryDetailParam, HttpServletRequest request) {
        //营销中心  经纪会员 平台 都可以查看
        Systemmanager sm = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (sm.getReletype() != 1) {
            //机构登录
            if (sm.getReletype() == 2) {
                //是否有经纪会员角色有则判断数据权限
                Arearole areaRoleJj = iArearoleMapper.selectOne(new QueryWrapper<Arearole>()
                        .eq("userid", sm.getAreauserid())
                        .eq("roletype", 7)
                );
                if (Objects.nonNull(areaRoleJj)) {
                    if (!iCommonService.checkUserAccountRole(sm, dealerQueryDetailParam.getUserid())) {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
                    }
                } else {
                    //没有经纪会员角色 再判断是否有营销中心角色
                    Arearole areaRoleYx = iArearoleMapper.selectOne(new QueryWrapper<Arearole>()
                            .eq("userid", sm.getAreauserid())
                            .eq("roletype", 7)
                    );
                    if (Objects.nonNull(areaRoleYx)) {
                        //有营销中心角色判断数据权限
                        Useraccount userAccount = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", dealerQueryDetailParam.getUserid()));
                        Useraccount userAccountOther = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", userAccount.getMemberuserid()));
                        if (userAccountOther.getParentuserid().compareTo(sm.getAreauserid()) != 0) {
                            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
                        }
                    } else {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
                    }
                }
            } else if (sm.getReletype() == 3) {
                //子机构
                if (!iCommonService.checkUserAccountRole(sm, dealerQueryDetailParam.getUserid())) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
                }
            } else {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
            }
        }
        //异步插入操作记录
        new Thread(new Runnable() {
            @Override
            public void run() {
                iSystemmanagerService.saveMGLog(sm, SysConstants.PART_INVESTOR_MANAGE, dealerQueryDetailParam.getUserid());
            }
        }).start();
        DealerQueryDetailResult detailResult = new DealerQueryDetailResult();
        //整理返回数据
        if (dealerQueryDetailParam.getModifyFlag() != null && dealerQueryDetailParam.getModifyFlag() >= 2 && dealerQueryDetailParam.getModifyFlag() < 5) {
            detailResult.setOldResult(getUserAccountDetail(dealerQueryDetailParam.getUserid()));
            detailResult.setNewResult(getModifyInvestorDetail(dealerQueryDetailParam.getUserid()));
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), detailResult);
        } else {
            detailResult.setOldResult(getUserAccountDetail(dealerQueryDetailParam.getUserid()));
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), detailResult);
        }
    }

    private DetailAfterResult getModifyInvestorDetail(Long userid) {
        DetailAfterResult detailResult = new DetailAfterResult();
        UserAccountDetailVo userAccountDetailVo = iUseraccountMapper.selectNewDetail(userid);
        // 从draft表NewContent取内容
        DraftUseraccountNew dua = JsonUtils.json2Object(userAccountDetailVo.getNewcontent(), DraftUseraccountNew.class);
        if (dua == null) {
            userAccountDetailVo.setHasAuth(0);
        } else {
            userAccountDetailVo.setHasAuth(dua.getHasauth());
        }

        detailResult.setUserAccountDetailVo(userAccountDetailVo);
        UserinfoDetailVo userinfoDetailVo = iUserinfoMapper.getUserinfoNewDetail(userid);
        userinfoDetailVo.setPathName(userinfoDetailVo.getCountryName() + userinfoDetailVo.getPathName());
        detailResult.setUserinfoDetailVo(userinfoDetailVo);
        return detailResult;
    }

    private DetailBeforeResult getUserAccountDetail(Long userid) {
        DetailBeforeResult detailResult = new DetailBeforeResult();
        UserAccountDetailVo userAccountDetailVo = iUseraccountMapper.selectDetail(userid);
        detailResult.setUserAccountDetailVo(userAccountDetailVo);
        UserinfoDetailVo userinfoDetailVo = iUserinfoMapper.getUserinfoDetail(userid);
        userinfoDetailVo.setPathName(userinfoDetailVo.getCountryName() + userinfoDetailVo.getPathName());
        detailResult.setUserinfoDetailVo(userinfoDetailVo);
        return detailResult;
    }

    @Override
    public AjaxResult export(HttpServletRequest request) {
        try {
            String fileName = "交易商管理_" + DateTimeUtils.getDateTime("yyyyMMdd");
            DealerQueryParam dealerQueryParam = new DealerQueryParam();
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            //如果不是平台管理员
            if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {
                dealerQueryParam.setParentUserId(systemmanager.getAreauserid());
            }
            List<DealerQueryResult> dealerQueryResults = iUseraccountMapper.queryInvestorPage(dealerQueryParam);
            if (CollectionUtils.isEmpty(dealerQueryResults)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, DealerQueryResult.class, dealerQueryResults);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("交易商管理_导出失败，失败原因：" + e);
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public void addUserESignInfo(Long userid, Long memberuserid) {
        // 有三方实名认证配置，且无记录 则生成相应的表记录; -- gzys 爱签 \ tjmd 腾讯电子签
        Integer count = getUserESignRecordCount(userid, memberuserid);
        Map<String, Object> map = new HashMap<>();
        if (count.equals(0)) {
            // 不存在则插入
            map.put("userid", userid);
            map.put("areauserid", memberuserid);
            // 根据”ESignTemplateConfig“表生成”UserESignRecord“表记录
            iUseresignrecordMapper.insertUserESignRecordFromConfig(map);
        }

        // 天津麦顿，添加“MD_UserWwapProtocol”表记录, 默认1：未签署 -- tjmd
        map.clear();
        map.put("userid", userid);
        map.put("areauserid", memberuserid);

        // 1008 掉期是否签署电子合同 默认为0，麦顿为1
        String mid = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "1008");
        if (StringUtils.isNotEmpty(mid) && mid.equals("1")) {
            //需要电子签的状态为1：未签署
            map.put("protocolstatus", 1);
        } else {
            //不需要电子签的状态为4：已审核
            map.put("protocolstatus", 4);
        }

        // 不存在则插入
        iUseresignrecordMapper.insertMD_UserWwapProtocol(map);
    }

    @Override
    public PageResult<InvestorModifyResult> queryModifyPage(InvestorModifyParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype().intValue() != SysConstants.SYS_TYPE_MANAGE.intValue()) {
            param.setMemberuserid(systemmanager.getAreauserid());
        }
        IPage<InvestorModifyResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<InvestorModifyResult> modifyPage = iUseraccountMapper.queryModifyPage(page, param);
        PageResult<InvestorModifyResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(modifyPage.getPages());
        pageResult.setCurrent(modifyPage.getCurrent());
        pageResult.setTotal(modifyPage.getTotal());
        pageResult.setPageSize(modifyPage.getSize());
        pageResult.setData(modifyPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<InvestorPersonalizationResult> accountQuery(Long goodsid, Long accountid, HttpServletRequest request) {
        InvestorPersonalizationResult result = new InvestorPersonalizationResult();
        try {
            TodayAccountmargin mr = iTodayAccountmarginMapper.selectOne(new QueryWrapper<TodayAccountmargin>()
                    .eq("accountid", accountid)
                    .eq("goodsid", goodsid));
            TodayAccounttraderule tr = iTodayAccounttraderuleMapper.selectOne(new QueryWrapper<TodayAccounttraderule>()
                    .eq("accountid", accountid)
                    .eq("goodsid", goodsid)
                    .eq("tradetype", 1));
            TodayAccounttradefee tf = iTodayAccounttradefeeMapper.selectOne(new QueryWrapper<TodayAccounttradefee>()
                    .eq("accountid", accountid)
                    .eq("goodsid", goodsid)
                    .eq("tradetype", 1));
            //当没有个性化，查询账户id=0的即商品默认的配置
            if (Objects.isNull(mr)) {
                mr = iTodayAccountmarginMapper.selectOne(new QueryWrapper<TodayAccountmargin>()
                        .eq("accountid", 0L)
                        .eq("goodsid", goodsid));
            }
            if (Objects.isNull(tr)) {
                tr = iTodayAccounttraderuleMapper.selectOne(new QueryWrapper<TodayAccounttraderule>()
                        .eq("accountid", 0L)
                        .eq("goodsid", goodsid)
                        .eq("tradetype", 1));
            }
            if (Objects.isNull(tf)) {
                tf = iTodayAccounttradefeeMapper.selectOne(new QueryWrapper<TodayAccounttradefee>()
                        .eq("accountid", 0L)
                        .eq("goodsid", goodsid)
                        .eq("tradetype", 1));
            }
            List<Long> id_list = new ArrayList<Long>();
            if (mr != null) {
                ServiceMemoryCache.MarginInfoStruct marginInfo = ServiceMemoryCache.MarginInfoStruct.newBuilder().
                        mergeFrom(mr.getInfocontent()).build();
                result.setMarginalgorithm(marginInfo.getMarginAlgorithm());
                result.setLockmarginvalue(marginInfo.getLockMarginValue());
                result.setMarketmarginvalue(marginInfo.getMarketMarginValue());
                result.setReckonmarginvalue(marginInfo.getReckonMarginValue());
            }
            if (tr != null) {
                ServiceMemoryCache.TradeRuleInfoStruct traderuleinfo = ServiceMemoryCache.TradeRuleInfoStruct.newBuilder().
                        mergeFrom(tr.getInfocontent()).build();

                List<ServiceMemoryCache.TradeRule> ruleList = traderuleinfo.getTradeRulesList();
                Map<Integer, Object> temp = new HashMap<Integer, Object>();

                ruleList.forEach(p -> {
                    id_list.add(Long.valueOf(p.getRuleID()));
                    temp.put(p.getRuleID(), p.getParamValue());
                });

                List<Traderuledescription> rds = iTraderuledescriptionMapper.selectList(new QueryWrapper<Traderuledescription>()
                        .in("ruleid", id_list));
                List<InvestorExtendRule> rules = new ArrayList<>();
                rds.forEach(p -> {
                    InvestorExtendRule investorExtendRule = new InvestorExtendRule();
                    investorExtendRule.setRuleid(p.getRuleid());
                    investorExtendRule.setRulename(p.getRulename());
                    investorExtendRule.setParamvalue(temp.get(p.getRuleid()));
                    rules.add(investorExtendRule);
                });
                result.setExtendRule(rules);
            }
            if (tf != null) {
                ServiceMemoryCache.TradeFeeInfoStruct tradefeeinfo = ServiceMemoryCache.TradeFeeInfoStruct.newBuilder().
                        mergeFrom(tf.getInfocontent()).build();
                List<InvestorExtendFee> feeStruct = new ArrayList<>();

                Map<Integer, ServiceMemoryCache.TradeFee> ftemp = new HashMap<Integer, ServiceMemoryCache.TradeFee>();

                List<ServiceMemoryCache.TradeFee> feeList = tradefeeinfo.getTradeFeesList();
                id_list.clear();
                feeList.forEach(p -> {
                    id_list.add(Long.valueOf(p.getFeeID()));
                    ftemp.put(p.getFeeID(), p);
                });
                Goods goods = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", goodsid));
                Market mar = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("MARKETID", goods.getMarketid()));
                result.setTradeProperty(mar.getTradeproperty());
                result.setMarginformula(mar.getMarginformula());

                List<Tradefeedescription> fds = iTradefeedescriptionMapper.query(id_list, mar.getTradeproperty());
                fds.forEach(p -> {
                    InvestorExtendFee extendFee = new InvestorExtendFee();
                    extendFee.setFeeid(p.getTradefeeid());
                    extendFee.setFeename(p.getTradefeename());
                    extendFee.setFeealgorithm(ftemp.get(p.getTradefeeid()).getFeeAlgorithm());
                    if (extendFee.getFeealgorithm() == 1) {
                        extendFee.setMemberdefaultvalue(ftemp.get(p.getTradefeeid()).getMemberDefaultValue() * 10000);
                        extendFee.setExchangevalue(ftemp.get(p.getTradefeeid()).getExchangeValue() * 10000);
                    } else {
                        extendFee.setMemberdefaultvalue(ftemp.get(p.getTradefeeid()).getMemberDefaultValue());
                        extendFee.setExchangevalue(ftemp.get(p.getTradefeeid()).getExchangeValue());
                    }

                    feeStruct.add(extendFee);
                });
                result.setExtendFee(feeStruct);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询个性化设置信息失败，失败原因：" + e);
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM002.getCode(), request.getHeader("Accept-Language"));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult modifyAudit(InvestorModifyAuditParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkUserAccountRole(systemmanager, param.getUserid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }

        DraftUseraccountNew dua = iDraftUseraccountNewMapper.selectOne(new QueryWrapper<DraftUseraccountNew>().eq("userid", param.getUserid()));
        if (dua == null) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_018.getCode(), request.getHeader("Accept-Language"));
        }

        Integer usertype = 0;
        if (Objects.equals(systemmanager.getReletype(), SysConstants.SYS_TYPE_MANAGE)) {
            //交易所审核
            if (dua.getModifystatus() != 3 && dua.getModifystatus() != 4) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_018.getCode(), request.getHeader("Accept-Language"));
            }
            Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", param.getUserid()));
            boolean flag = 1 == ua.getHasauth();
            usertype = ua.getUsertype();
            if (param.getAuditflag() == 1) {
                //交易所审核通过
                DraftUserinfo dui = iDraftUserinfoMapper.selectOne(new QueryWrapper<DraftUserinfo>().eq("userid", param.getUserid()));
                // 机构或子机构
                if (dua.getUsertype().equals(2) || dua.getUsertype().equals(3)) {
                    // 机构开户证件号码是否唯一
                    String areacardflag = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, Constants.SYSPARAM_CARD_NO);
                    //验证证件号码是否存在
                    if (areacardflag != null && areacardflag.equals("1") && !iCommonService.checkOranCardNumOrMobile(3, 1, dui.getUserid(), dui.getCardnum())) {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
                    }
                }
                String newMobile = dui.getMobile();

                //验证手机号是否存在
                if (!iCommonService.checkOranCardNumOrMobile(2, 2, dua.getUserid(), newMobile)) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_016.getCode(), request.getHeader("Accept-Language"));
                }

                if (ua.getParentuserid().compareTo(dua.getParentuserid()) != 0) {
                    Useraccount pua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", dua.getParentuserid()));
                    dua.setSubarealevelpath(pua.getSubarealevelpath() + ua.getUserid() + ",");
                }

                Integer oldHasAuth = ua.getHasauth();

                BeanUtils.copyProperties(dua, ua);
                ua.setModifystatus(1);
                ua.setAudittime(new Date());
                ua.setAudituserid(systemmanager.getAutoid());
                ua.setModifytime(new Date());

                // 从draft表NewContent取内容
                DraftUseraccountNew newDua = JsonUtils.json2Object(dua.getNewcontent(), DraftUseraccountNew.class);
                if (newDua == null || newDua.getHasauth() == null) {
                    ua.setHasauth(1);
                } else {
                    ua.setHasauth(newDua.getHasauth());
                }

                iUseraccountMapper.update(ua, new QueryWrapper<Useraccount>().eq("userid", ua.getUserid()));
                iDraftUseraccountNewMapper.deleteById(dua);

                Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", param.getUserid()));
                Integer needinvoice = ui.getNeedinvoice();
                String oldMobile = ui.getMobile();

                BeanUtils.copyProperties(dui, ui, new String[]{"userid", "halfbodyphotourl",
                        "cardfrontphotourl", "cardbackphotourl", "mobile", "bankid", "bankaccount", "bankcardfrontphotourl"});
                if (dui.getHalfbodyphotourl() != null && !dui.getHalfbodyphotourl().trim().isEmpty()) {
                    ui.setHalfbodyphotourl(dui.getHalfbodyphotourl());
                }
                if (dui.getCardfrontphotourl() != null && !dui.getCardfrontphotourl().trim().isEmpty()) {
                    ui.setCardfrontphotourl(dui.getCardfrontphotourl());
                }
                if (dui.getCardbackphotourl() != null && !dui.getCardbackphotourl().trim().isEmpty()) {
                    ui.setCardbackphotourl(dui.getCardbackphotourl());
                }
                if (dui.getMobile() != null && StringUtils.isNotBlank(dui.getMobile())) {
                    ui.setMobile(dui.getMobile());
                }

                // wskh_openaccountconfig:45=1 时显示的银行卡字段特殊处理,在上面“copyProperties”时忽略
                if (dui.getBankid() != null && StringUtils.isNotBlank(dui.getBankid())) {
                    ui.setBankid(dui.getBankid());
                }
                if (dui.getBankaccount() != null && StringUtils.isNotBlank(dui.getBankaccount())) {
                    ui.setBankaccount(dui.getBankaccount());
                }
                if (dui.getBankcardfrontphotourl() != null && StringUtils.isNotBlank(dui.getBankcardfrontphotourl())) {
                    ui.setBankcardfrontphotourl(dui.getBankcardfrontphotourl());
                }
                ui.setOtherurl(ui.getOtherurl() == null ? "" : ui.getOtherurl());
                ui.setNeedinvoice(needinvoice);
                iUserinfoMapper.update(ui, new QueryWrapper<Userinfo>().eq("userid", ui.getUserid()));
                iDraftUserinfoMapper.delete(new QueryWrapper<DraftUserinfo>().eq("userid", dui.getUserid()));

                //发送用户变更通知
                try {
                    List<Taaccount> list = iTaaccountMapper.selectList(new QueryWrapper<Taaccount>()
                            .eq("userid", ui.getUserid())
                            .eq("ismain", 1)
                    );
                    if (list != null && !list.isEmpty()) {
                        list.forEach(p -> {
                            iSendMsgService.sendCustomerInfo(ui, p.getAccountid(), "2", 0);

                            //发给账户服务的，用户变更通知
                            iSendMsgService.sendUserChangeMsg(p.getAccountid(), ui.getUserid(),
                                    SysEnums.UserOperateTypeEnum.UPDATE.getType(),
                                    SysEnums.NotifyModeEnum.UNICAST.getType());
                        });
                    }
                } catch (Exception e) {
                    log.error("发送用户变更通知失败，失败原因：" + e);
                }

                Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "075");
                if (!flag && o != null && o.toString().startsWith("1")) {
                    try {
                        List<String> params = new ArrayList<>();
                        String p[] = o.toString().split(",");
                        params.add(ua.getAccountname().replaceAll("\\*", ""));
                        params.add(p[1]);
                        iSendMsgService.sendSMSConnetion(30, EncryptionUtils.decryptForAES(ui.getMobile()), params);
                    } catch (Exception e) {
                        log.error("error  systemparam----------------------");
                    }
                }

                //todo THJ - 994=1时交易所实名认证审核通过时，如果用户为投资者，给推荐人添加积分 - 20221229  #4455
                /*if (ua.getUsertype() == 5 && oldHasAuth != 1 && ua.getRefereeuserid() != null) {
                    this.THJBuildRefUserScore(user.getAreauserid(), ua.getUserid());
                }*/

                // 交易商时，处理逻辑
                if (dua.getUsertype().equals(5)) {
                    // 有三方实名认证配置，且无记录 则生成相应的表记录; -- gzys 爱签 \ tjmd 腾讯电子签
                    addUserESignInfo(ua.getUserid(), ua.getMemberuserid());

                    // 若手机号有修改，更新“userauthinfo”表，否则无法开户
                    if (newMobile != null && !oldMobile.equals(newMobile)) {
                        // 获取原手机号三方登录表记录
                        Userauthinfo userAuthInfo = iUserauthinfoMapper.selectOne(new QueryWrapper<Userauthinfo>()
                                .eq("authid", oldMobile)
                                .eq("authtype", 3));

                        if (userAuthInfo != null) {
                            // 删除原记录
                            iUserauthinfoMapper.delete(new QueryWrapper<Userauthinfo>()
                                    .eq("authid", oldMobile)
                                    .eq("authtype", 3));
                            // 新增记录
                            Userauthinfo newUserAuthinfo = new Userauthinfo();
                            newUserAuthinfo.setAuthid(newMobile);
                            newUserAuthinfo.setAuthtype(3);
                            newUserAuthinfo.setLoginid(userAuthInfo.getLoginid());
                            newUserAuthinfo.setUserid(userAuthInfo.getUserid());
                            newUserAuthinfo.setIsvalid(1);
                            iUserauthinfoMapper.insert(newUserAuthinfo);
                        }
                    }
                }

                //31	审核拒绝的，尊敬的：XXXx，您提交的实名认证信息未通过，原因：xxxxx，请登录{尚志贸易通}重新提交认证信息，详情请咨询{4007-444-555}
                //30	审核通过的，尊敬的：XXXx，您在{尚志贸易通}提交的实名认证信息已通过，详情请咨询{4007-444-555}
                //sendMsgService.sendSMSConnetion(templateId, recPhone, params);
            } else {
                boolean isSend = false;
                iDraftUseraccountNewMapper.deleteById(dua);
                iDraftUserinfoMapper.delete(new QueryWrapper<DraftUserinfo>().eq("USERID", dua.getUserid()));

                ua.setModifystatus(6);
                ua.setAudittime(new Date());
                ua.setAudituserid(systemmanager.getAutoid());
                ua.setModifyremark(param.getMsg());
                if (ua.getHasauth() != 1) {
                    ua.setHasauth(3);
                    isSend = true;
                }
                iUseraccountMapper.update(ua, new QueryWrapper<Useraccount>().eq("userid", ua.getUserid()));
                //发送
                if (isSend) {
                    Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "075");
                    if (o != null && o.toString().startsWith("1")) {
                        Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", ua.getUserid()));
                        try {
                            List<String> params = new ArrayList<>();
                            String[] p = o.toString().split(",");
                            params.add(ua.getAccountname().replaceAll("\\*", ""));
                            params.add(param.getMsg().replaceAll("\\*", ""));
                            params.add(p[1]);
                            iSendMsgService.sendSMSConnetion(31, EncryptionUtils.decryptForAES(ui.getMobile()), params);
                        } catch (Exception e) {
                            log.error("error  systemparam----------------------" + Arrays.toString(e.getStackTrace()));
                        }
                    }
                }
            }
        } else {
            //经纪会员审核
            if (dua.getModifystatus() != 3) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_018.getCode(), request.getHeader("Accept-Language"));
            }
            Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", param.getUserid()));
            usertype = ua.getUsertype();
            if (param.getAuditflag() == 1) {
                DraftUserinfo dui = iDraftUserinfoMapper.selectOne(new QueryWrapper<DraftUserinfo>().eq("userid", param.getUserid()));
                // 机构或子机构
                if (dua.getUsertype().equals(2) || dua.getUsertype().equals(3)) {
                    // 机构开户证件号码是否唯一
                    String areacardflag = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, Constants.SYSPARAM_CARD_NO);
                    //验证证件号码是否存在
                    if (areacardflag != null && areacardflag.equals("1") && !iCommonService.checkOranCardNumOrMobile(3, 1, null, dui.getCardnum())) {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
                    }
                }

                //经纪会员审核通过
                ua.setModifystatus(4);
                iUseraccountMapper.update(ua, new QueryWrapper<Useraccount>().eq("userid", ua.getUserid()));

                dua.setModifystatus(4);
                iDraftUseraccountNewMapper.updateById(dua);
            } else {
                boolean isSend = false;
                iDraftUseraccountNewMapper.deleteById(dua);
                iDraftUserinfoMapper.delete(new QueryWrapper<DraftUserinfo>().eq("USERID", dua.getUserid()));

                ua.setModifystatus(5);
                ua.setAudittime(new Date());
                ua.setAudituserid(systemmanager.getAutoid());
                ua.setModifyremark(param.getMsg());
                if (ua.getHasauth() != 1) {
                    ua.setHasauth(3);
                    isSend = true;
                }

                iUseraccountMapper.update(ua, new QueryWrapper<Useraccount>().eq("userid", ua.getUserid()));

                if (isSend) {
                    Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "075");
                    if (o != null && o.toString().startsWith("1")) {
                        Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", ua.getUserid()));
                        try {
                            List<String> params = new ArrayList<>();
                            String p[] = o.toString().split(",");
                            params.add(ua.getAccountname().replaceAll("\\*", ""));
                            params.add(param.getMsg().replaceAll("\\*", ""));
                            params.add(p[1]);
                            iSendMsgService.sendSMSConnetion(31, EncryptionUtils.decryptForAES(ui.getMobile()), params);
                        } catch (Exception e) {
                            log.error("error  systemparam----------------------%s" + Arrays.toString(e.getStackTrace()));
                        }
                    }
                }
            }
        }

        if (usertype == 3 || usertype == 4)
            systemmanagerService.writeOperateLog(SysConstants.PART_CODE_ORGZ_ZJG, "审核确认id={\"auditid\":" + param.getUserid() + "}", systemmanager, null, null, null);
        else
            systemmanagerService.writeOperateLog(SysConstants.PART_INVESTOR_MODIFY, "审核确认id={\"auditid\":" + param.getUserid() + "}", systemmanager, null, null, null);

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult investorEdit(DetailBeforeResult param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkUserAccountRole(systemmanager, param.getUserAccountDetailVo().getUserId())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }

        DraftUseraccountNew dua = new DraftUseraccountNew();
        Useraccount useraccount = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", param.getUserAccountDetailVo().getUserId()));
        BeanUtils.copyProperties(useraccount, dua);

        String card = param.getUserinfoDetailVo().getCardNum();
        String mobile = param.getUserinfoDetailVo().getMobile();
        if (StringUtils.isNotBlank(card) || StringUtils.isNotBlank(mobile)) {
            card = EncryptionUtils.encryptByAES(param.getUserinfoDetailVo().getCardNum());
            List<Userinfo> uiList = iUserinfoMapper.selectList(new QueryWrapper<Userinfo>()
                    .eq(StringUtils.isNotBlank(card), "cardnum", card)
                    .eq(StringUtils.isNotBlank(mobile), "mobile", mobile)
                    .eq("userid", param.getUserAccountDetailVo().getUserId())
                    .eq("usertype", 5));
            if (CollectionUtils.isNotEmpty(uiList)) {
                String sysparam = iCommonService.getSysparmById(Constants.SYSPARAM_CARD_NOTWO);
                if ((sysparam == null) || ("1".equals(sysparam))) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_019.getCode(), request.getHeader("Accept-Language"));
                }
            }
        }

        dua.setAccountname(param.getUserAccountDetailVo().getAccountName());
        dua.setModifierid(systemmanager.getAutoid());
        dua.setModifytime(new Date());
        dua.setModifystatus(param.getUserAccountDetailVo().getModifyStatus());

        if (param.getUserAccountDetailVo().getParentuserid() != null) {
            dua.setParentuserid(param.getUserAccountDetailVo().getParentuserid());
        }

        // 更新是否实名、newContent字段 -- dyp
        dua.setHasauth(param.getUserAccountDetailVo().getHasAuth());
        dua.setNewcontent(JsonUtils.object2Json(dua));

        dua.setOldcontent(JsonUtils.object2Json(useraccount));
        iDraftUseraccountNewMapper.insert(dua);

        useraccount.setModifystatus(param.getUserAccountDetailVo().getModifyStatus());
        useraccount.setModifierid(systemmanager.getAutoid());
        useraccount.setModifytime(new Date());
        iUseraccountMapper.update(useraccount, new QueryWrapper<Useraccount>().eq("userid", useraccount.getUserid()));

        Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", param.getUserAccountDetailVo().getUserId()));
        DraftUserinfo dui = new DraftUserinfo();
        BeanUtils.copyProperties(ui, dui);
        dui.setAddress(param.getUserinfoDetailVo().getAddress());
        dui.setBiznature(param.getUserinfoDetailVo().getBizNature());
        dui.setCardbackphotourl(param.getUserinfoDetailVo().getCardBackPhotoUrl());
        dui.setCardfrontphotourl(param.getUserinfoDetailVo().getCardFrontPhotoUrl());
        dui.setCardnum(param.getUserinfoDetailVo().getCardNum());
        dui.setCardtypeid(param.getUserinfoDetailVo().getCardTypeId());
        dui.setCityid(param.getUserinfoDetailVo().getCityid());
        dui.setCompany(param.getUserinfoDetailVo().getCompany());
        if (StringUtils.isBlank(param.getUserinfoDetailVo().getCustomerName())) {
            //取useraccount里的accountname
            dui.setCustomername(param.getUserAccountDetailVo().getAccountName());
        } else {
            dui.setCustomername(param.getUserinfoDetailVo().getCustomerName());
        }
        dui.setDistrictid(param.getUserinfoDetailVo().getDistrictid());
        dui.setEmail(param.getUserinfoDetailVo().getEmail());
        dui.setCountryid(param.getUserinfoDetailVo().getCountryid());
        dui.setHalfbodyphotourl(param.getUserinfoDetailVo().getHalfBodyPhotoUrl());
        dui.setMobile(param.getUserinfoDetailVo().getMobile());
        dui.setModifierid(systemmanager.getAutoid());
        dui.setModifiertime(new Date());
        dui.setContactname(param.getUserinfoDetailVo().getContactName());
        dui.setPostalcode(param.getUserinfoDetailVo().getPostalCode());
        dui.setProvinceid(param.getUserinfoDetailVo().getProvinceid());
        dui.setRemark(param.getUserinfoDetailVo().getRemark());
        dui.setSex(param.getUserinfoDetailVo().getSex());
        dui.setTelphone(param.getUserinfoDetailVo().getTelPhone());
        dui.setWechat(param.getUserinfoDetailVo().getWechat());
        dui.setBankid(param.getUserinfoDetailVo().getBankid());
        dui.setBankaccount(param.getUserinfoDetailVo().getBankAccount());
        dui.setBankname(param.getUserinfoDetailVo().getBankName());
        dui.setBankcardfrontphotourl(param.getUserinfoDetailVo().getBankCardFrontPhotoUrl());
        dui.setLegalpersonname(param.getUserinfoDetailVo().getLegalPersonName());
        dui.setLegalcardbackphotourl(param.getUserinfoDetailVo().getLegalCardBackPhotoUrl());
        dui.setLegalcardfrontphotourl(param.getUserinfoDetailVo().getLegalCardFrontPhotoUrl());
        dui.setOtherurl(param.getUserinfoDetailVo().getOtherUrl());
        dui = (DraftUserinfo) SensitiveEncryptUtil.sensitiveEncrypt(dui, null);
        iDraftUserinfoMapper.insert(dui);

        //资金账户配置变更  配置业务
        /*if (param.getConfig() != null && param.getConfig().getAccountid() != null) {
            //子账户为  投资者机构所有  关联给投资者使用，，
            //此处变更时，记为投资者变更  ，变更表userid填入投资者的userid
            DraftTaAccountConfig config = new DraftTaAccountConfig();
            config.setAccountid(param.getConfig().getAccountid());
            config.setUserid(organ.getUserid());
            config.setNewcontent(JSonHelp.object2Json(param.getConfig()));
            commonDao.merge(config);
        }*/
        JSONObject jsonObj = JSONObject.parseObject(JSONObject.toJSONString(dui));
        JSONObject jsonObjUi = JSONObject.parseObject(JSONObject.toJSONString(ui));
        if (useraccount.getUsertype() == 3 || useraccount.getUsertype() == 4) {
            if (systemmanager.getReletype() == 1) {
                if (useraccount.getUsertype() == 3)
                    systemmanagerService.writeOperateLog(SysConstants.PART_CODE_ORGZ_ZJG, "修改子机构id=" + useraccount.getUserid() + "并提交审核", systemmanager, null, jsonObjUi.toString(), jsonObj.toString());
                else
                    systemmanagerService.writeOperateLog(SysConstants.PART_CODE_ORGZ, "修改经纪人id=" + useraccount.getUserid() + "并提交审核", systemmanager, null, jsonObjUi.toString(), jsonObj.toString());
            } else {
                if (useraccount.getUsertype() == 3)
                    systemmanagerService.writeOperateLog(SysConstants.PART_CODE_ORGZ_ZJG, "修改子机构id=" + useraccount.getUserid() + "并提交审核", systemmanager, null, jsonObjUi.toString(), jsonObj.toString());
                else
                    systemmanagerService.writeOperateLog(SysConstants.PART_CODE_ORGZ, "修改经纪人id=" + useraccount.getUserid() + "并提交审核", systemmanager, null, jsonObjUi.toString(), jsonObj.toString());
            }
        } else if (useraccount.getUsertype() == 5) {
            systemmanagerService.writeOperateLog(SysConstants.PART_INVESTOR_MANAGE, "修改交易商id=" + useraccount.getUserid() + "并提交审核", systemmanager, null, jsonObjUi.toString(), jsonObj.toString());
        }

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

    @Override
    public PageResult<InvestorPersonalizedResult> queryPersonalized(String groupname, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Long userid = null;
        if (systemmanager.getReletype().intValue() == SysConstants.SYS_TYPE_CLIENT) {
            userid = systemmanager.getAreauserid();
        }
        IPage<InvestorPersonalizedResult> page = new Page<>(pageNum, pageSize);
        IPage<InvestorPersonalizedResult> modifyPage = iUseraccountMapper.queryPersonalized(page, groupname, userid);
        PageResult<InvestorPersonalizedResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(modifyPage.getPages());
        pageResult.setCurrent(modifyPage.getCurrent());
        pageResult.setTotal(modifyPage.getTotal());
        pageResult.setPageSize(modifyPage.getSize());
        pageResult.setData(modifyPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<Riskratiotype> getRiskRatioTypeForMarketer(Integer customertype, Integer riskcontrolmode, HttpServletRequest request) {
        Riskratiotype riskRatioType = iRiskratiotypeMapper.selectOne(new QueryWrapper<Riskratiotype>()
                .eq("customertype", customertype)
                .eq("riskcontrolmode", riskcontrolmode));

        if (Objects.nonNull(riskRatioType)) {
            BigDecimal cNum = new BigDecimal(100);
            if (riskRatioType.getRecovertraderiskratio() != null) {
                riskRatioType.setRecovertraderiskratio(riskRatioType.getRecovertraderiskratio()
                        .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
            }
            if (riskRatioType.getNotemarginriskratio() != null) {
                riskRatioType.setNotemarginriskratio(riskRatioType.getNotemarginriskratio()
                        .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
            }
            if (riskRatioType.getAddmarginriskratio() != null) {
                riskRatioType.setAddmarginriskratio(riskRatioType.getAddmarginriskratio()
                        .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
            }
            if (riskRatioType.getCutriskratio() != null) {
                riskRatioType.setCutriskratio(riskRatioType.getCutriskratio().multiply(cNum)
                        .setScale(2, RoundingMode.HALF_UP));
            }
            if (riskRatioType.getCutbackriskratio() != null) {
                riskRatioType.setCutbackriskratio(riskRatioType.getCutbackriskratio()
                        .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
            }

            //安全度
            if (riskRatioType.getNotesaferatio() != null) {
                riskRatioType.setNotesaferatio(riskRatioType.getNotesaferatio().multiply(cNum)
                        .setScale(2, RoundingMode.HALF_UP));
            }
            if (riskRatioType.getAddsaferatio() != null) {
                riskRatioType.setAddsaferatio(riskRatioType.getAddsaferatio().multiply(cNum)
                        .setScale(2, RoundingMode.HALF_UP));
            }
            if (riskRatioType.getRecoversaferatio() != null) {
                riskRatioType.setRecoversaferatio(riskRatioType.getRecoversaferatio()
                        .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
            }
            if (riskRatioType.getCutsaferatio() != null) {
                riskRatioType.setCutsaferatio(riskRatioType.getCutsaferatio()
                        .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
            }

            if (StringUtils.isNotBlank(riskRatioType.getCutmarginseq())) {
                List<Market> marketList = iMarketMapper.selectList(new QueryWrapper<Market>().in("marketid",
                        Arrays.stream(riskRatioType.getCutmarginseq().split(",")).filter(s -> !s.trim().isEmpty()).map(Long::valueOf).collect(Collectors.toList())));
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < marketList.size(); i++) {
                    if (i == marketList.size() - 1) {
                        stringBuilder.append(marketList.get(i).getMarketname());
                    } else {
                        stringBuilder.append(marketList.get(i).getMarketname()).append(",");
                    }
                }
                riskRatioType.setMarkets(stringBuilder.toString());
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), riskRatioType);
    }

    @Override
    public AjaxResult addPersonalized(InvestorPersonalizedAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getAutoid() == null) {
            if (param.getAreauserid() == null) {
                param.setAreauserid(systemmanager.getAreauserid());
            }
            List<Usergroup> usergroups = iUsergroupMapper.selectList(new QueryWrapper<Usergroup>()
                    .eq("groupname", param.getGroupname())
                    .eq("areauserid", param.getAreauserid()));
            if (CollectionUtils.isNotEmpty(usergroups)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.INVESTOR_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
            }
            Usergroup ug = new Usergroup();
            BeanUtils.copyProperties(param, ug);
            ug.setCreatorid(systemmanager.getAutoid());
            ug.setCreatetime(new Date());
            iUsergroupMapper.insert(ug);
        } else {
            Usergroup ug = iUsergroupMapper.selectOne(new QueryWrapper<Usergroup>().eq("AUTOID", param.getAutoid()));
            if (!iCommonService.checkUserAccountRole(systemmanager, ug.getAreauserid())) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
            }

            if (!param.getGroupname().equals(ug.getGroupname())) {
                List<Usergroup> usergroups = iUsergroupMapper.selectList(new QueryWrapper<Usergroup>()
                        .eq("groupname", param.getGroupname())
                        .eq("areauserid", param.getAreauserid()));
                if (CollectionUtils.isNotEmpty(usergroups)) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.INVESTOR_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
                }
            }
            ug.setCustomertype(param.getCustomertype());
            ug.setGroupname(param.getGroupname());
            iUsergroupMapper.updateById(ug);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<InvestorPerDetailQueryResult> queryPersonalizedDetail(InvestorPerDetailQueryParam param, HttpServletRequest request) {
        if (StringUtils.isNotBlank(param.getCardnum()))
            param.setCardnum(EncryptionUtils.encryptByAES(param.getCardnum()));
        if (StringUtils.isNotBlank(param.getMobilephone()))
            param.setMobilephone(EncryptionUtils.encryptByAES(param.getMobilephone()));
        IPage<InvestorPerDetailQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<InvestorPerDetailQueryResult> modifyPage = iUseraccountMapper.queryPersonalizedDetail(page, param);
        PageResult<InvestorPerDetailQueryResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(modifyPage.getPages());
        pageResult.setCurrent(modifyPage.getCurrent());
        pageResult.setTotal(modifyPage.getTotal());
        pageResult.setPageSize(modifyPage.getSize());
        pageResult.setData(modifyPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<Useraccount> queryInvestorForPer(Long usergroupid, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Long userid;
        Usergroup ug = iUsergroupMapper.selectOne(new QueryWrapper<Usergroup>().eq("AUTOID", usergroupid));
        if (systemmanager.getReletype().intValue() == SysConstants.SYS_TYPE_MANAGE) {
            userid = ug.getAreauserid();
        } else {
            userid = systemmanager.getAreauserid();
        }
        QueryWrapper<Useraccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("usertype", 5);
        queryWrapper.eq("memberuserid", userid);
        String notExistsSql = "NOT EXISTS (SELECT 1 FROM usergroupdetail u WHERE u.userid = useraccount.userid)";
        queryWrapper.apply(notExistsSql);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), iUseraccountMapper.selectList(queryWrapper));
    }

    @Override
    public AjaxResult addInvestorForPer(InvestorForPerAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (StringUtils.isEmpty(param.getAdduserids())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.INVESTOR_ERROR_CODE_007.getCode(), request.getHeader("Accept-Language"));
        }
        String[] ids = param.getAdduserids().split(",");
        for (String id : ids) {
            if (!iCommonService.checkUserAccountRole(systemmanager, Long.valueOf(id))) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
            }
        }
        //确定勾选的交易商是否分了组
        List<Usergroupdetail> list = iUsergroupdetailMapper.selectList(new QueryWrapper<Usergroupdetail>()
                .in("userid", Arrays.stream(ids).filter(s -> !s.trim().isEmpty())
                        .map(Long::valueOf).collect(Collectors.toList())));
        if (CollectionUtils.isNotEmpty(list)) {
            Object[] res = {list.get(0)};
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.INVESTOR_ERROR_CODE_008.getCode(), res, request.getHeader("Accept-Language"));
        }

        for (String id : ids) {
            Usergroupdetail ug = new Usergroupdetail();
            ug.setUserid(Long.valueOf(id));
            ug.setUsergroupid(param.getUsergroupid());
            ug.setCreatetime(new Date());
            ug.setCreatorid(systemmanager.getAutoid());
            iUsergroupdetailMapper.insert(ug);
            iSendMsgService.sendAccountConfigChangeNtf(2, 1, Long.valueOf(id), null, null, param.getUsergroupid(), null);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult delInvestorForPer(Long userid, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkUserAccountRole(systemmanager, userid)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        Usergroupdetail us = iUsergroupdetailMapper.selectOne(new QueryWrapper<Usergroupdetail>().eq("userid", userid));
        iUsergroupdetailMapper.delete(new QueryWrapper<Usergroupdetail>().eq("userid", userid));

        iSendMsgService.sendAccountConfigChangeNtf(2, 1, userid, null, null, us.getUsergroupid(), null);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult delInvest(Long autoid, HttpServletRequest request) {
        Usergroup ug = iUsergroupMapper.selectOne(new QueryWrapper<Usergroup>().eq("AUTOID", autoid));
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkUserAccountRole(systemmanager, ug.getAreauserid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }

        List<Usergrouptradeconfig> tc = iUsergrouptradeconfigMapper.selectList(new QueryWrapper<Usergrouptradeconfig>().eq("usergroupid", autoid));
        if (CollectionUtils.isNotEmpty(tc)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.INVESTOR_ERROR_CODE_010.getCode(), request.getHeader("Accept-Language"));
        }
        List<Usergroupdetail> usergroupid = iUsergroupdetailMapper.selectList(new QueryWrapper<Usergroupdetail>().eq("usergroupid", autoid));
        if (CollectionUtils.isNotEmpty(usergroupid)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.INVESTOR_ERROR_CODE_009.getCode(), request.getHeader("Accept-Language"));
        }

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

    @Override
    public PageResult<AccountRiskConfigResult> queryAccountRiskConfig(AccountRiskConfigParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype().intValue() == SysConstants.SYS_TYPE_CLIENT) {
            param.setMemberuserid(systemmanager.getAreauserid());
        }
        IPage<AccountRiskConfigResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<AccountRiskConfigResult> modifyPage = iUseraccountMapper.queryAccountRiskConfigPage(page, param);
        PageResult<AccountRiskConfigResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(modifyPage.getPages());
        pageResult.setCurrent(modifyPage.getCurrent());
        pageResult.setTotal(modifyPage.getTotal());
        pageResult.setPageSize(modifyPage.getSize());
        pageResult.setData(modifyPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult getTaaccountList(Long userid, HttpServletRequest request) {
        QueryWrapper<Taaccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", userid);
        String notExistsSql = "NOT EXISTS (select 1 from AccountRiskConfig a where a.accountid = TAACCOUNT.accountid)";
        queryWrapper.apply(notExistsSql);
        List<Taaccount> taaccounts = iTaaccountMapper.selectList(queryWrapper);
        List<Long> collect = taaccounts.stream().map(Taaccount::getAccountid).collect(Collectors.toList());
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), collect);
    }

    @Override
    public AjaxResult addAccountRiskConfig(AccountRiskConfigAddParam param, HttpServletRequest request) {
        Accountriskconfig config = iAccountriskconfigMapper.selectOne(new QueryWrapper<Accountriskconfig>()
                .eq("accountid", param.getAccountid())
                .eq("userid", param.getUserid()));

        if (Objects.isNull(config)) {
            Accountriskconfig accountriskconfig = new Accountriskconfig();
            accountriskconfig.setUserid(param.getUserid());
            accountriskconfig.setCustomertype(param.getCustomertype());
            accountriskconfig.setAccountid(param.getAccountid());
            iAccountriskconfigMapper.insert(accountriskconfig);
            iSendMsgService.sendAccountConfigChangeNtf(1, 1, param.getUserid(), param.getAccountid(), null, null, null);
        } else {
            config.setCustomertype(param.getCustomertype());
            iAccountriskconfigMapper.update(config, new QueryWrapper<Accountriskconfig>()
                    .eq("accountid", param.getAccountid())
                    .eq("userid", param.getUserid()));
            iSendMsgService.sendAccountConfigChangeNtf(1, 2, param.getUserid(), param.getAccountid(), null, null, null);
        }

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

    @Override
    public AjaxResult<Accountriskconfig> view(Long accountid, HttpServletRequest request) {
        Accountriskconfig config = iAccountriskconfigMapper.selectOne(new QueryWrapper<Accountriskconfig>().eq("accountid", accountid));
        Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", config.getUserid()));
        if (ua.getUsertype() == 2) {
            Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("accountid", config.getAccountid()));
            config.setIsmarketacc(ta.getIsmarketaccount());
        }
        config.setUsertype(ua.getUsertype());
        config.setAccountname(ua.getAccountname());
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), config);
    }

    @Override
    public AjaxResult deleteConfig(Long accountid, HttpServletRequest request) {
        Accountriskconfig config = iAccountriskconfigMapper.selectOne(new QueryWrapper<Accountriskconfig>().eq("accountid", accountid));
        iAccountriskconfigMapper.delete(new QueryWrapper<Accountriskconfig>().eq("accountid", accountid));

        iSendMsgService.sendAccountConfigChangeNtf(1, 3, config.getUserid(), config.getAccountid(), null, null, null);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<UserGroupTreeResult> getTree(HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        List<Usergroup> groupList = iUsergroupMapper.selectList(new QueryWrapper<>());
        List<UserGroupTradeConfigTreeVo> result = new ArrayList<>();
        List<Usergrouptradeconfig> list = iUsergrouptradeconfigMapper.selectList(new QueryWrapper<Usergrouptradeconfig>().eq("memberuserid", systemmanager.getAreauserid()));
        if (CollectionUtils.isNotEmpty(list)) {
            Map<Long, List<Usergrouptradeconfig>> group = new HashMap<>();
            for (Usergrouptradeconfig fig : list) {
                Market marketid = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", fig.getMarketid()));
                fig.setMarketname(marketid.getMarketname());
                Goods goods = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", fig.getGoodsid()));
                fig.setGoodsname(goods.getGoodsname());
                Long key = fig.getUsergroupid();
                if (group.containsKey(key)) {
                    group.get(key).add(fig);
                } else {
                    List<Usergrouptradeconfig> temp = new ArrayList<>();
                    temp.add(fig);
                    group.put(key, temp);
                }
            }

            Map<Long, Map<Long, List<Usergrouptradeconfig>>> groups = new HashMap<>();
            for (Map.Entry<Long, List<Usergrouptradeconfig>> entry : group.entrySet()) {
                Map<Long, List<Usergrouptradeconfig>> market = new HashMap<>();
                List<Usergrouptradeconfig> temp = entry.getValue();
                for (Usergrouptradeconfig fig : temp) {
                    Long key = fig.getMarketid();
                    if (market.containsKey(key)) {
                        market.get(key).add(fig);
                    } else {
                        List<Usergrouptradeconfig> _temp = new ArrayList<>();
                        _temp.add(fig);
                        market.put(key, _temp);
                    }
                }
                groups.put(entry.getKey(), market);
            }
            Set<String> set = new HashSet<>();

            for (Map.Entry<Long, Map<Long, List<Usergrouptradeconfig>>> entry : groups.entrySet()) {
                Usergrouptradeconfig base = null;
                for (Map.Entry<Long, List<Usergrouptradeconfig>> _entry : entry.getValue().entrySet()) {
                    List<Usergrouptradeconfig> temp = _entry.getValue();
                    for (int i = 0; i < temp.size(); i++) {
                        Usergrouptradeconfig fig = temp.get(i);
                        if (i == 0) {
                            base = fig;
                        }
                        String setKey = fig.getUsergroupid() + "" + fig.getMarketid() + "" + fig.getGoodsid();
                        if (!set.contains(setKey)) {
                            set.add(setKey);
                            //商品级
                            UserGroupTradeConfigTreeVo vo2 = new UserGroupTradeConfigTreeVo();
                            vo2.setId(fig.getGoodsid().toString());
                            vo2.setPid(fig.getUsergroupid() + "" + fig.getMarketid());
                            vo2.setLevel(3);
                            //商品名称
                            vo2.setName(fig.getGoodsname());
                            vo2.setUsergroupid(fig.getUsergroupid());
                            vo2.setMarketid(fig.getMarketid());
                            vo2.setGoodsid(fig.getGoodsid());
                            result.add(vo2);
                        }
                    }
                    //市场级
                    UserGroupTradeConfigTreeVo vo1 = new UserGroupTradeConfigTreeVo();
                    vo1.setId(base.getUsergroupid() + "" + base.getMarketid());
                    vo1.setPid("z" + base.getUsergroupid().toString());
                    vo1.setLevel(2);
                    //市场名称
                    vo1.setName(base.getMarketname());
                    vo1.setUsergroupid(base.getUsergroupid());
                    vo1.setMarketid(base.getMarketid());
                    result.add(vo1);
                }
            }
        }
        //默认分组
        UserGroupTradeConfigTreeVo defaultVO = new UserGroupTradeConfigTreeVo();
        defaultVO.setId("z0");
        defaultVO.setPid("-1");
        defaultVO.setLevel(1);
        defaultVO.setName(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM030.getCode(), request.getHeader("Accept-Language")));
        defaultVO.setUsergroupid(0L);
        result.add(defaultVO);

        //分组级
        int len = groupList.size();
        for (int i = 0; i < len; i++) {
            Usergroup ug = groupList.get(i);
            UserGroupTradeConfigTreeVo temp = new UserGroupTradeConfigTreeVo();
            temp.setId("z" + ug.getAutoid().toString());
            temp.setPid("-1");
            temp.setLevel(1);
            //分组名称
            temp.setName(ug.getGroupname());
            temp.setUsergroupid(ug.getAutoid());
            result.add(temp);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult<InvestorInitPerAddResult> initGoodsAndBZ(Long usergroupid, Long marketid, Long goodsid, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        InvestorInitPerAddResult result = new InvestorInitPerAddResult();
        Long memberuserid = null;
        if (systemmanager.getReletype() != 1) {
            memberuserid = systemmanager.getAreauserid();
        }
        if (usergroupid == null) {
            result.setUserGroups(iMarketMapper.getNoTradeConfigGroups(memberuserid));
            result.setMarkets(iMarketMapper.getNoTradeConfigMarkets(memberuserid, usergroupid));
        } else {
            if (marketid == null) {
                result.setMarkets(iMarketMapper.getNoTradeConfigMarkets(memberuserid, usergroupid));
            } else {
                if (goodsid == null) {
                    result.setGoods(iGoodsMapper.getNoTradeConfigGoods(memberuserid, usergroupid, marketid));
                } else {
                    PersonalizationDelParam param = new PersonalizationDelParam();
                    param.setMarketid(marketid);
                    param.setGoodsid(goodsid);
                    param.setMemberuserid(systemmanager.getAreauserid());
                    result.setFeesConfigVos(getTradeFeeDescriptions(param));
                    result.setRulesConfigVos(getTradeRuleDescriptions(param));
                    //客户类别
                    result.setResults(iUseraccountMapper.getCustomerTypeByGoodsid(goodsid, null));
                }
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult traderPersonAdd(InvestorPersonAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getFlag() == 0) {
            addTrader(param, request);
            iSendMsgService.sendAccountConfigChangeNtf(3, 1, null, null, param.getGoodsid(), param.getUsergroupid(), null);
        } else {
            QueryWrapper<Usergrouptradeconfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goodsid", param.getGoodsid());
            queryWrapper.eq("marketid", param.getMarketid());
            queryWrapper.eq("memberuserid", systemmanager.getAreauserid());
            queryWrapper.eq("usergroupid", param.getUsergroupid());
            iUsergrouptradeconfigMapper.delete(queryWrapper);

            addTrader(param, request);
            iSendMsgService.sendAccountConfigChangeNtf(3, 2, null, null, param.getGoodsid(), param.getUsergroupid(), null);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private void addTrader(InvestorPersonAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getParamid() != null) {
            Usergrouptradeconfig config = getUsergrouptradeconfig(param, systemmanager);
            iUsergrouptradeconfigMapper.insert(config);
        }

        Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "007");
        //币种小数位
        BigDecimal Cude = null;
        //成交量小数位
        BigDecimal qtyde = null;
        if (o != null && "1".equals(o.toString())) {
            Goods goods = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", param.getGoodsid()));
            Enumdicitem item = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                    .eq("enumdiccode", "currency")
                    .eq("enumitemname", goods.getCurrencyid()));
            if (item != null && StringUtils.isNotBlank(item.getParam1())) {
                Cude = BigDecimal.valueOf(Math.pow(10, Integer.parseInt(item.getParam1())));
            }
            qtyde = BigDecimal.valueOf(Math.pow(10, goods.getQtydecimalplace()));
        }

        List<Usergrouptradeconfig> ruleList = param.getRuleList();
        if (ruleList != null && !ruleList.isEmpty()) {
            for (Usergrouptradeconfig fig : ruleList) {
                if (fig.getParamid() == null || fig.getParamid() == 0
                        || fig.getParamvalue() == null) {
                    continue;
                }

                //小数位放大
                if (qtyde != null && fig.getParamid() >= 101 && fig.getParamid() <= 104) {
                    fig.setParamvalue(fig.getParamvalue().multiply(qtyde));
                }

                fig.setFeealgorithm(2);
                fig.setUsergroupid(param.getUsergroupid());
                fig.setMemberuserid(systemmanager.getAreauserid());
                fig.setMarketid(param.getMarketid());
                fig.setGoodsid(param.getGoodsid());
                fig.setRuletype(2);
                fig.setCreatetime(new Date());
                fig.setCreatorid(systemmanager.getAutoid());
                iUsergrouptradeconfigMapper.insert(fig);
            }
        }

        List<Usergrouptradeconfig> feeList = param.getFeeList();
        if (feeList != null && !feeList.isEmpty()) {
            for (Usergrouptradeconfig fig : feeList) {
                if (fig.getParamid() == null || fig.getParamid() == 0
                        || fig.getFeealgorithm() == null || fig.getParamvalue() == null) {
                    continue;
                }
                if (fig.getFeealgorithm() == 1) {
                    if (fig.getParamvalue().compareTo(new BigDecimal(10000)) > 0) {
                        throw new GlobalException(Constants.Error_Code_Design, MessageType.INVESTOR_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
                    }
                    fig.setParamvalue(fig.getParamvalue().divide(new BigDecimal(10000)));
                } else if (Cude != null) {
                    fig.setParamvalue(fig.getParamvalue().multiply(Cude));
                }
                fig.setUsergroupid(param.getUsergroupid());
                fig.setMemberuserid(systemmanager.getAreauserid());
                fig.setMarketid(param.getMarketid());
                fig.setGoodsid(param.getGoodsid());
                fig.setRuletype(3);
                fig.setCreatetime(new Date());
                fig.setCreatorid(systemmanager.getAutoid());
                iUsergrouptradeconfigMapper.insert(fig);
            }
        }
    }

    private Usergrouptradeconfig getUsergrouptradeconfig(InvestorPersonAddParam param, Systemmanager systemmanager) {
        Usergrouptradeconfig config = new Usergrouptradeconfig();
        config.setUsergroupid(param.getUsergroupid());
        config.setMemberuserid(systemmanager.getAreauserid());
        config.setMarketid(param.getMarketid());
        config.setGoodsid(param.getGoodsid());
        config.setRuletype(1);
        config.setParamid(param.getParamid());
        config.setCreatetime(new Date());
        config.setCreatorid(systemmanager.getAutoid());
        config.setFeealgorithm(param.getFeealgorithm());
        return config;
    }

    @Override
    public AjaxResult deleteTraderConfig(InvestorPersonDeleteParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        QueryWrapper<Usergrouptradeconfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goodsid", param.getGoodsid());
        queryWrapper.eq("marketid", param.getMarketid());
        queryWrapper.eq("memberuserid", systemmanager.getAreauserid());
        queryWrapper.eq("usergroupid", param.getUsergroupid());
        iUsergrouptradeconfigMapper.delete(queryWrapper);

        iSendMsgService.sendAccountConfigChangeNtf(3, 3, null, null, param.getGoodsid(), param.getUsergroupid(), null);

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

    @Override
    public AjaxResult<UserGroupTradeConfigVo> tradeConfigView(PersonalizationDelParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

        param.setMemberuserid(systemmanager.getAreauserid());
        List<RulesConfigVo> ruleList = iUseraccountMapper.getTradeRuleDescriptions(param);
        List<FeesConfigVo> feeList = iUseraccountMapper.getTradeFeeDescriptions(param);

        Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "007");
        if (o != null && "1".equals(o.toString())) {
            //成交量小数位
            Goods goods = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", param.getGoodsid()));
            if (ruleList != null && !ruleList.isEmpty()) {
                //成交量小数位
                if (goods.getQtydecimalplace() != null && goods.getQtydecimalplace() != 0) {
                    BigDecimal qtyde = new BigDecimal(Math.pow(10, goods.getQtydecimalplace()));
                    for (int i = 0; i < ruleList.size(); i++) {
                        //小数位放大
                        if (ruleList.get(i).getRuleid() >= 101 && ruleList.get(i).getRuleid() <= 104) {
                            if (ruleList.get(i).getParamvalue() != null &&
                                    ruleList.get(i).getParamvalue().compareTo(BigDecimal.ZERO) != 0) {
                                ruleList.get(i).setParamvalue(ruleList.get(i).getParamvalue().
                                        divide(new BigDecimal(Math.pow(10, ruleList.get(i).getQtydecimalplace()))));
                            }
                            if (ruleList.get(i).getGvalue() != null &&
                                    ruleList.get(i).getGvalue().compareTo(BigDecimal.ZERO) != 0) {
                                ruleList.get(i).setGvalue(ruleList.get(i).getGvalue().divide(qtyde));
                            }
                            if (ruleList.get(i).getDvalue() != null &&
                                    ruleList.get(i).getDvalue().compareTo(BigDecimal.ZERO) != 0) {
                                ruleList.get(i).setDvalue(ruleList.get(i).getDvalue().divide(qtyde));
                            }
                            if (ruleList.get(i).getCvalue() != null &&
                                    ruleList.get(i).getCvalue().compareTo(BigDecimal.ZERO) != 0) {
                                ruleList.get(i).setCvalue(ruleList.get(i).getCvalue().divide(qtyde));
                            }
                        }
                    }
                }
            }

            if (feeList != null && !feeList.isEmpty()) {
                //币种小数位
                Enumdicitem item = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                        .eq("enumdiccode", "currency")
                        .eq("enumitemname", goods.getCurrencyid()));
                if (item != null && StringUtils.isNotBlank(item.getParam1()) && !"0".equals(item.getParam1())) {
                    BigDecimal Cude = BigDecimal.valueOf(Math.pow(10, Integer.parseInt(item.getParam1())));
                    for (FeesConfigVo feesConfigVo : feeList) {
                        //小数位放大
                        if (feesConfigVo.getFeealgorithm() == 2) {
                            if (feesConfigVo.getExchangevalue() != null
                                    && feesConfigVo.getExchangevalue().compareTo(BigDecimal.ZERO) != 0) {
                                feesConfigVo.setExchangevalue(feesConfigVo.getExchangevalue().divide(Cude));
                            }
                            if (feesConfigVo.getDvalue() != null
                                    && feesConfigVo.getDvalue().compareTo(BigDecimal.ZERO) != 0) {
                                feesConfigVo.setDvalue(feesConfigVo.getDvalue().divide(Cude));
                            }
                            if (feesConfigVo.getGvalue() != null
                                    && feesConfigVo.getGvalue().compareTo(BigDecimal.ZERO) != 0) {
                                feesConfigVo.setGvalue(feesConfigVo.getGvalue().divide(Cude));
                            }
                            if (feesConfigVo.getCvalue() != null
                                    && feesConfigVo.getCvalue().compareTo(BigDecimal.ZERO) != 0) {
                                feesConfigVo.setCvalue(feesConfigVo.getCvalue().divide(Cude));
                            }
                        }
                    }
                }
            }
        }

        if (feeList != null && !feeList.isEmpty()) {
            for (FeesConfigVo feesConfigVo : feeList) {
                if (feesConfigVo.getFeealgorithm() == 1) {
                    if (feesConfigVo.getExchangevalue() != null
                            && feesConfigVo.getExchangevalue().compareTo(BigDecimal.ZERO) != 0) {
                        feesConfigVo.setExchangevalue(feesConfigVo.getExchangevalue().multiply(new BigDecimal("10000")));
                    }
                    if (feesConfigVo.getDvalue() != null
                            && feesConfigVo.getDvalue().compareTo(BigDecimal.ZERO) != 0) {
                        feesConfigVo.setDvalue(feesConfigVo.getDvalue().multiply(new BigDecimal("10000")));
                    }
                    if (feesConfigVo.getGvalue() != null
                            && feesConfigVo.getGvalue().compareTo(BigDecimal.ZERO) != 0) {
                        feesConfigVo.setGvalue(feesConfigVo.getGvalue().multiply(new BigDecimal("10000")));
                    }
                    if (feesConfigVo.getCvalue() != null
                            && feesConfigVo.getCvalue().compareTo(BigDecimal.ZERO) != 0) {
                        feesConfigVo.setCvalue(feesConfigVo.getCvalue().multiply(new BigDecimal("10000")));
                    }
                    if (feesConfigVo.getMembermaxvalue() != null
                            && feesConfigVo.getMembermaxvalue().compareTo(BigDecimal.ZERO) != 0) {
                        feesConfigVo.setMembermaxvalue(feesConfigVo.getMembermaxvalue().multiply(new BigDecimal("10000")));
                    }
                    if (feesConfigVo.getMemberminvalue() != null
                            && feesConfigVo.getMemberminvalue().compareTo(BigDecimal.ZERO) != 0) {
                        feesConfigVo.setMemberminvalue(feesConfigVo.getMemberminvalue().multiply(new BigDecimal("10000")));
                    }
                }
            }
        }

        UserGroupTradeConfigVo detail = new UserGroupTradeConfigVo();

        detail.setDruleList(ruleList);
        detail.setDfeeList(feeList);
        QueryWrapper<Usergrouptradeconfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goodsid", param.getGoodsid());
        queryWrapper.eq("marketid", param.getMarketid());
        queryWrapper.eq("memberuserid", systemmanager.getAreauserid());
        queryWrapper.eq("usergroupid", param.getUsergroupid());
        queryWrapper.eq("ruletype", 1);
        Usergrouptradeconfig config = iUsergrouptradeconfigMapper.selectOne(queryWrapper);
        detail.setGoodsid(param.getGoodsid());
        detail.setMemberuserid(systemmanager.getAreauserid());
        detail.setMarketid(param.getMarketid());
        detail.setUsergroupid(param.getUsergroupid());
        if (config != null) {
            detail.setParamid(config.getParamid());

            // 查询商品保证金设置值
            List<InvestorInitBZResult> results = iUseraccountMapper.getCustomerTypeByGoodsid(param.getGoodsid(), config.getParamid());
            if (CollectionUtils.isNotEmpty(results)) {
                detail.setMarginalgorithm(Integer.parseInt(results.get(0).getMarginalgorithm().toString()));
                detail.setMarketmarginvalue(new BigDecimal(results.get(0).getMarketmarginvalue().toString()));
                if (detail.getMarginalgorithm().equals(1)) {
                    detail.setMarketmarginvaluedisplay(detail.getMarketmarginvalue().multiply(new BigDecimal(100)).setScale(2).toString() + "%");
                } else {
                    detail.setMarketmarginvaluedisplay(detail.getMarketmarginvalue().toString());
                }
            }
        }

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

    @Override
    public AjaxResult<AccountTradeConfigTreeVo> getAccTradeTree(HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        List<Accounttradeconfig> list = iAccounttradeconfigMapper.getListForTree(systemmanager.getAreauserid());

        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), new ArrayList<AccountTradeConfigTreeVo>());
        }

        //先按类型
        Map<Integer, List<Accounttradeconfig>> type = new HashMap<>();
        for (Accounttradeconfig fig : list) {
            fig.setAccountname(iUseraccountMapper.selectOrganName(fig.getUserid()));
            Integer key = fig.getTradetype();
            if (type.containsKey(key)) {
                type.get(key).add(fig);
            } else {
                List<Accounttradeconfig> temp = new ArrayList<>();
                temp.add(fig);
                type.put(key, temp);
            }
        }

        //用户userid
        Map<Integer, Map<Long, List<Accounttradeconfig>>> users = new HashMap<>();
        for (Map.Entry<Integer, List<Accounttradeconfig>> entry : type.entrySet()) {
            Map<Long, List<Accounttradeconfig>> market = new HashMap<>();
            List<Accounttradeconfig> temp = entry.getValue();
            for (Accounttradeconfig fig : temp) {
                Long key = fig.getUserid();
                if (market.containsKey(key)) {
                    market.get(key).add(fig);
                } else {
                    List<Accounttradeconfig> _temp = new ArrayList<>();
                    _temp.add(fig);
                    market.put(key, _temp);
                }
            }
            users.put(entry.getKey(), market);
        }

        //资金账户
        Map<Integer, Map<Long, Map<Long, List<Accounttradeconfig>>>> user = new HashMap<>();
        for (Map.Entry<Integer, Map<Long, List<Accounttradeconfig>>> entry : users.entrySet()) {
            Map<Long, Map<Long, List<Accounttradeconfig>>> u = new HashMap<>();

            Map<Long, List<Accounttradeconfig>> temp = entry.getValue();//userid
            for (Map.Entry<Long, List<Accounttradeconfig>> entry_ : temp.entrySet()) {
                Map<Long, List<Accounttradeconfig>> market = new HashMap<>();
                List<Accounttradeconfig> ul = entry_.getValue();//用户下所有的资金
                for (Accounttradeconfig fig : ul) {
                    Long key = fig.getAccountid();
                    if (market.containsKey(key)) {
                        market.get(key).add(fig);
                    } else {
                        List<Accounttradeconfig> _temp = new ArrayList<>();
                        _temp.add(fig);
                        market.put(key, _temp);
                    }
                }
                u.put(entry_.getKey(), market);
            }
            user.put(entry.getKey(), u);
        }

        Set<String> set = new HashSet<>();
        List<AccountTradeConfigTreeVo> result = new ArrayList<>();

        for (Map.Entry<Integer, Map<Long, Map<Long, List<Accounttradeconfig>>>> entry_ : user.entrySet()) {
            for (Map.Entry<Long, Map<Long, List<Accounttradeconfig>>> entry : entry_.getValue().entrySet()) {
                Accounttradeconfig base = null;
                for (Map.Entry<Long, List<Accounttradeconfig>> _entry : entry.getValue().entrySet()) {
                    List<Accounttradeconfig> temp = _entry.getValue();
                    for (int i = 0; i < temp.size(); i++) {
                        Accounttradeconfig fig = temp.get(i);
                        if (fig.getTradetype() == null) {
                            fig.setTradetype(1);
                        }
                        if (i == 0) {
                            base = fig;
                        }
                        String setKey = fig.getTradetype() + "" + fig.getUserid() + "" + fig.getAccountid() + "" + fig.getGoodsid();
                        if (!set.contains(setKey)) {
                            set.add(setKey);
                            //商品级
                            AccountTradeConfigTreeVo vo2 = new AccountTradeConfigTreeVo();
                            vo2.setId(fig.getTradetype() + fig.getGoodsid().toString());
                            vo2.setPid(fig.getTradetype() + fig.getUserid() + "" + fig.getAccountid());
                            vo2.setLevel(3);
                            vo2.setName(fig.getGoodsname());//商品名称
                            vo2.setUserid(fig.getUserid());
                            vo2.setAccountid(fig.getAccountid());
                            vo2.setMarketid(fig.getMarketid());
                            vo2.setGoodsid(fig.getGoodsid());
                            vo2.setTradetype(fig.getTradetype());
                            result.add(vo2);
                        }
                    }
                    //资金账户级
                    AccountTradeConfigTreeVo vo1 = new AccountTradeConfigTreeVo();
                    vo1.setId(base.getTradetype() + base.getUserid() + "" + base.getAccountid());
                    vo1.setPid(base.getTradetype() + "u" + base.getUserid().toString());
                    vo1.setLevel(2);
                    vo1.setName(base.getAccountid().toString());//市场名称
                    vo1.setUserid(base.getUserid());
                    vo1.setAccountid(base.getAccountid());
                    vo1.setTradetype(base.getTradetype());
                    result.add(vo1);
                }
                //用户级
                AccountTradeConfigTreeVo vo = new AccountTradeConfigTreeVo();
                vo.setId(base.getTradetype() + "u" + base.getUserid().toString());
                if (base.getTradetype() == null || base.getTradetype() == 0 || base.getTradetype() == 1) {
                    vo.setPid("-1");
                } else {
                    vo.setPid("-2");
                }
                vo.setLevel(1);
                vo.setName(StringUtils.isBlank(base.getAccountname()) ? AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM030.getCode(), request.getHeader("Accept-Language")) : base.getAccountname());//分组名称
                vo.setUserid(base.getUserid());
                vo.setTradetype(base.getTradetype());
                result.add(vo);
            }
        }

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

    @Override
    public AjaxResult<InvestorInitBZResult> initBZList(Long goodsid, HttpServletRequest request) {
        List<InvestorInitBZResult> result = iUseraccountMapper.getCustomerTypeByGoodsid(goodsid, null);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public PageResult<InvestorCancelApplyResult> usercancelapply(InvestorCancelApplyParam param, HttpServletRequest request) {
        IPage<InvestorCancelApplyResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<InvestorCancelApplyResult> dealerQueryResults = iUseraccountMapper.usercancelapply(page, param);
        PageResult<InvestorCancelApplyResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(dealerQueryResults.getPages());
        pageResult.setCurrent(dealerQueryResults.getCurrent());
        pageResult.setTotal(dealerQueryResults.getTotal());
        pageResult.setPageSize(dealerQueryResults.getSize());
        pageResult.setData(dealerQueryResults.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<Usercancelapply> cancelview(Long autoid, HttpServletRequest request) {
        Usercancelapply result = iUsercancelapplyMapper.selectOne(new QueryWrapper<Usercancelapply>().eq("autoid", autoid));
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkUserAccountRole(systemmanager, result.getUserid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        result.setAccountname(iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", result.getUserid())).getAccountname());
        if(result.getAuditid() != null){
            result.setAuditusername(iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", result.getAuditid())).getUsername());
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult cancelaudit(Long autoid, Integer auditflag, String msg, HttpServletRequest request) {
        Usercancelapply temp = iUsercancelapplyMapper.selectOne(new QueryWrapper<Usercancelapply>().eq("autoid", autoid));
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkUserAccountRole(systemmanager, temp.getUserid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        if (!Objects.equals(temp.getHandlestatus(), SysEnums.AccountOffStatusEnum.PENDING.getType())) {
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM022.getCode(), request.getHeader("Accept-Language"));
        }

        //判断资金账户
        Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("userid", temp.getUserid()));
        if (ta == null) {
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM023.getCode(), request.getHeader("Accept-Language"));
        }

        Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", temp.getUserid()));

        //审核拒绝
        if (auditflag == 2) {
            temp.setHandlestatus(SysEnums.AccountOffStatusEnum.REFUSED.getType());
            temp.setApplystatus(SysEnums.AccountOffApplyEnum.FINISH.getType());
            temp.setAuditid(systemmanager.getAutoid());
            temp.setAudittime(new Date());
            temp.setAuditremark(msg);
            iUsercancelapplyMapper.update(temp, new QueryWrapper<Usercancelapply>().eq("autoid", temp.getAutoid()));

            sendSMS(ua.getAccountname(), temp.getUserid());
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM024.getCode(), request.getHeader("Accept-Language"));
        }

        //校验账户类型
        if (ua.getUsertype() != 5) {
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM025.getCode(), request.getHeader("Accept-Language"));
        }

        //判断资金账户签约信息
        BankAccountsign sign = iBankAccountsignMapper.selectOne(new QueryWrapper<BankAccountsign>().eq("accountcode", ta.getAccountid().toString()));
        if (sign != null && sign.getSignstatus() != 1 && sign.getSignstatus() != 7) {
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM026.getCode(), request.getHeader("Accept-Language"));
        }

        //审核通过
        //判断是否是干净账户
        if (ta.getTradestatus() != 7) {
            Long accountuuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_account);
            AkernelMI1.AccountFundInfoReq.Builder accountbuilder = AkernelMI1.AccountFundInfoReq.newBuilder();
            Common.MessageHead.Builder accounthd = Common.MessageHead.newBuilder();
            accounthd.setAccountID(ta.getAccountid());
            accounthd.setClientTime(System.currentTimeMillis());
            accounthd.setResponseTopic(SysConstants.RabbitMoneyReqKey);
            accounthd.setFunCode(FunCodeConstants.FunCode_Trade_AccountFundInfoReq);
            accountbuilder.setOrderId(accountuuid);
            accountbuilder.setAccountId(ta.getAccountid());
            accountbuilder.setQueryBitMask(4);
            byte[] accountbody = ProtoHelper.getNTAS(accountbuilder.build().toByteArray(),
                    FunCodeConstants.FunCode_Trade_AccountFundInfoReq);
            //卡住
            Calculator accountca = new Calculator(accountuuid);
            SerialNumberUtils.lockMap.put(accountuuid, accountca);
            rabbitTemplate.send(SysConstants.RabbitMoneyReqKey, new Message(accountbody, new MessageProperties()));

            synchronized (accountca) {
                try {
                    accountca.wait(6000);
                    Object o = accountca.obj;
                    if (o != null) {
                        AkernelMI1.AccountFundInfoRsp accountrsp = (AkernelMI1.AccountFundInfoRsp) o;
                        if (accountrsp.getRetCode() == 0) {
                            if (accountrsp.getIsCleanAccount() == 1) {
                                //干净账户
                            } else {
                                return AjaxResult.error(Constants.Error_Code_Design, MessageType.INVESTOR_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
                            }
                        } else {
                            return AjaxResult.error(Constants.Error_Code_Design, "[" + accountrsp.getRetCode() + "]" + ProtoErrorCodes.resultMsg(accountrsp.getRetCode()), "");
                        }
                    } else {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.INVESTOR_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
                    }
                } catch (InterruptedException e) {
                    log.error("mq接收出入金返回信息失败，失败信息：" + e);
                } finally {
                    SerialNumberUtils.lockMap.remove(accountuuid);
                }
            }
        }
        temp.setApplystatus(SysEnums.AccountOffApplyEnum.HANDLING.getType());
        temp.setAuditremark(msg);
        iUsercancelapplyMapper.update(temp, new QueryWrapper<Usercancelapply>().eq("autoid", temp.getAutoid()));

        //判断并发送积分
        //result = sendClearScore(temp, ta, user);

        // 发送用户注销消息给中心\银行接口
        List<Taaccount> tas = iTaaccountMapper.selectList(new QueryWrapper<Taaccount>()
                .eq("userid", temp.getUserid())
                .eq("ismain", 1));
        iSendMsgService.sendM2BUnregistCustomerInfo(tas);

        /*if(auditflag == 1){
            if(result.get("userid") != null && result.get("accountid") != null){
                sendMsgService.sendUserChangeMsg(
                        Long.parseLong(result.get("accountid").toString()),
                        Long.parseLong(result.get("userid").toString()),
                        SysEnums.UserOperateTypeEnum.DEL.getType(),
                        SysEnums.AccountOperateTypeEnum.DEL.getType(),
                        SysEnums.NotifyModeEnum.UNICAST.getType());

                List<Long> loginids = userCancelApplyService.queryLoginidByUserid(Long.parseLong(result.get("userid").toString()));
                if(loginids != null && loginids.size() > 0){
                    Set<Long> set_logid = new HashSet<>();
                    set_logid.addAll(loginids);
                    sendMsgService.sendLoginMsg(set_logid, SysEnums.UserOperateTypeEnum.DEL.getType(), SysEnums.NotifyModeEnum.UNICAST.getType());
                }
            }
        }*/
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private void sendSMS(String accountname, Long userid) {
        Userinfo info = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", userid));
        if (info == null || info.getMobile() == null)
            return;
        ShortMessageMtp1.ShortMsgSendReq.Builder builder = ShortMessageMtp1.ShortMsgSendReq.newBuilder();
        builder.setMsgType(2);
        builder.setTemplateID(15);
        builder.setPriority(2);
        builder.setScheduledTime("");
        builder.addRecvPhone(EncryptionUtils.decryptForAES(info.getMobile()));
        builder.addParamValues(accountname);

        Common.MessageHead.Builder headBuil = Common.MessageHead.newBuilder();
        headBuil.setFunCode(FunCodeConstants.FunCode_Trade_ShortMsgSendReq);
        builder.setHeader(headBuil.build());
        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(), FunCodeConstants.FunCode_Trade_ShortMsgSendReq);
        MessageProperties msgProperties = new MessageProperties();
        msgProperties.setHeader("messageType", "protoBuf");
        rabbitTemplate.send(SysConstants.RabbitShortMessage, new Message(body, msgProperties));
    }

    @Override
    public AjaxResult<UserAccountDetailVo> getUserAccountDetail(Long userid, HttpServletRequest request) {
        UserAccountDetailVo userAccountDetailVo = iUseraccountMapper.selectDetail(userid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), userAccountDetailVo);
    }

    private List<RulesConfigVo> getTradeRuleDescriptions(PersonalizationDelParam param) {
        List<RulesConfigVo> list = iUseraccountMapper.getTradeRuleDescriptions(param);

        if (list != null && !list.isEmpty()) {
            Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "007");
            if (o != null && "1".equals(o.toString())) {
                //成交量小数位
                Goods goods = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", param.getGoodsid()));
                if (goods.getQtydecimalplace() != null && goods.getQtydecimalplace() != 0) {
                    BigDecimal qtyde = BigDecimal.valueOf(Math.pow(10, goods.getQtydecimalplace()));
                    for (RulesConfigVo rulesConfigVo : list) {
                        //小数位放大
                        if (rulesConfigVo.getRuleid() >= 101 && rulesConfigVo.getRuleid() <= 104) {
                            //平台 为商品本身的 小数位可能是商品的也可能是商品组的
                            if (rulesConfigVo.getParamvalue() != null &&
                                    rulesConfigVo.getParamvalue().compareTo(BigDecimal.ZERO) != 0) {
                                rulesConfigVo.setParamvalue(rulesConfigVo.getParamvalue().divide(BigDecimal.valueOf(Math.pow(10, rulesConfigVo.getQtydecimalplace()))));
                            }
                            if (rulesConfigVo.getGvalue() != null &&
                                    rulesConfigVo.getGvalue().compareTo(BigDecimal.ZERO) != 0) {
                                rulesConfigVo.setGvalue(rulesConfigVo.getGvalue().divide(qtyde));
                            }
                            if (rulesConfigVo.getDvalue() != null &&
                                    rulesConfigVo.getDvalue().compareTo(BigDecimal.ZERO) != 0) {
                                rulesConfigVo.setDvalue(rulesConfigVo.getDvalue().divide(qtyde));
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    private List<FeesConfigVo> getTradeFeeDescriptions(PersonalizationDelParam param) {
        List<FeesConfigVo> list = iUseraccountMapper.getTradeFeeDescriptions(param);
        if (CollectionUtils.isNotEmpty(list)) {
            Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "007");
            if (o != null && "1".equals(o.toString())) {
                //币种小数位
                Goods goods = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", param.getGoodsid()));
                Enumdicitem item = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                        .eq("enumdiccode", "currency")
                        .eq("enumitemname", goods.getCurrencyid()));
                if (item != null && StringUtils.isNotBlank(item.getParam1()) && !"0".equals(item.getParam1())) {
                    BigDecimal Cude = BigDecimal.valueOf(Math.pow(10, Integer.parseInt(item.getParam1())));
                    for (FeesConfigVo feesConfigVo : list) {
                        //小数位放大
                        if (feesConfigVo.getFeealgorithm() == 2) {
                            if (feesConfigVo.getExchangevalue() != null
                                    && feesConfigVo.getExchangevalue().compareTo(BigDecimal.ZERO) != 0) {
                                feesConfigVo.setExchangevalue(feesConfigVo.getExchangevalue().divide(Cude));
                            }
                            if (feesConfigVo.getDvalue() != null
                                    && feesConfigVo.getDvalue().compareTo(BigDecimal.ZERO) != 0) {
                                feesConfigVo.setDvalue(feesConfigVo.getDvalue().divide(Cude));
                            }
                            if (feesConfigVo.getGvalue() != null
                                    && feesConfigVo.getGvalue().compareTo(BigDecimal.ZERO) != 0) {
                                feesConfigVo.setGvalue(feesConfigVo.getGvalue().divide(Cude));
                            }

                            if (feesConfigVo.getMembermaxvalue() != null
                                    && feesConfigVo.getMembermaxvalue().compareTo(BigDecimal.ZERO) != 0) {
                                feesConfigVo.setMembermaxvalue(feesConfigVo.getMembermaxvalue().divide(Cude));
                            }
                            if (feesConfigVo.getMemberminvalue() != null
                                    && feesConfigVo.getMemberminvalue().compareTo(BigDecimal.ZERO) != 0) {
                                feesConfigVo.setMemberminvalue(feesConfigVo.getMemberminvalue().divide(Cude));
                            }
                        }
                    }
                }
            } else {
                for (FeesConfigVo feesConfigVo : list) {
                    if (feesConfigVo.getFeealgorithm() == 1) {
                        if (feesConfigVo.getExchangevalue() != null
                                && feesConfigVo.getExchangevalue().compareTo(BigDecimal.ZERO) != 0) {
                            feesConfigVo.setExchangevalue(feesConfigVo.getExchangevalue().multiply(new BigDecimal("10000")));
                        }
                        if (feesConfigVo.getDvalue() != null
                                && feesConfigVo.getDvalue().compareTo(BigDecimal.ZERO) != 0) {
                            feesConfigVo.setDvalue(feesConfigVo.getDvalue().multiply(new BigDecimal("10000")));
                        }
                        if (feesConfigVo.getGvalue() != null
                                && feesConfigVo.getGvalue().compareTo(BigDecimal.ZERO) != 0) {
                            feesConfigVo.setGvalue(feesConfigVo.getGvalue().multiply(new BigDecimal("10000")));
                        }

                        if (feesConfigVo.getMembermaxvalue() != null
                                && feesConfigVo.getMembermaxvalue().compareTo(BigDecimal.ZERO) != 0) {
                            feesConfigVo.setMembermaxvalue(feesConfigVo.getMembermaxvalue().multiply(new BigDecimal("10000")));
                        }
                        if (feesConfigVo.getMemberminvalue() != null
                                && feesConfigVo.getMemberminvalue().compareTo(BigDecimal.ZERO) != 0) {
                            feesConfigVo.setMemberminvalue(feesConfigVo.getMemberminvalue().multiply(new BigDecimal("10000")));
                        }
                    }
                }
            }
        }
        return list;
    }

    private Integer getUserESignRecordCount(Long userid, Long areauserid) {
        // 根据ESignTemplateConfig表生成UserESignRecord表记录
        List<Useresignrecord> records = iUseresignrecordMapper.selectList(new QueryWrapper<Useresignrecord>()
                .eq("userid", userid)
                .eq("areauserid", areauserid));
        if (CollectionUtils.isNotEmpty(records)) {
            return records.size();
        }
        return 0;
    }


}
