package com.muchinfo.mtp3century.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.muchinfo.mtp.proto.Common;
import com.muchinfo.mtp.proto.ShortMessageMtp1;
import com.muchinfo.mtp3century.exception.GlobalException;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.ISendMsgService;
import com.muchinfo.mtp3century.service.IUseraccountService;
import com.muchinfo.mtp3century.service.IWskhUserinfoService;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3century.utils.SequenceIDGeneratorUtils;
import com.muchinfo.mtp3common.enumtype.*;
import com.muchinfo.mtp3common.utils.*;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3common.vo.ProtoHelper;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.investor.InvestorProcessParam;
import com.muchinfo.mtp3pojos.vo.investor.InvestorQueryParam;
import com.muchinfo.mtp3pojos.vo.investor.InvestorQueryResult;
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.util.*;

/**
 * <p>
 * 网上开户用户表 (开户成功删除记录) 服务实现类
 * </p>
 *
 * @author XKF
 * @since 2024-05-30
 */
@Service
public class WskhUserinfoServiceImpl extends ServiceImpl<IWskhUserinfoMapper, WskhUserinfo> implements IWskhUserinfoService {

    @Resource
    private IWskhUserinfoMapper iWskhUserinfoMapper;
    @Resource
    private IUserinfoMapper iUserinfoMapper;
    @Resource
    private IBankBankinfoMapper iBankBankinfoMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private IWskhBlacklistMapper iWskhBlacklistMapper;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private IWskhOpenaccountconfigMapper iWskhOpenaccountconfigMapper;
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private IEnumdicitemMapper iEnumdicitemMapper;
    @Resource
    private IBankSystemconfigMapper iBankSystemconfigMapper;
    @Resource
    private ITaaccountMapper iTaaccountMapper;
    @Resource
    private IUserreckonaccountMapper iUserreckonaccountMapper;
    @Resource
    private IMarketrunMapper iMarketrunMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private IRoleuserMapper iRoleuserMapper;
    @Resource
    private ISystemparamMapper iSystemparamMapper;
    @Resource
    private ISendMsgService iSendMsgService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ILoginaccountMapper iLoginaccountMapper;
    @Resource
    private ICertificatetypeconfigMapper iCertificatetypeconfigMapper;
    @Resource
    private IUserreceiveinfoMapper iUserreceiveinfoMapper;
    @Resource
    private IUserauthinfoMapper iUserauthinfoMapper;
    @Resource
    private IWskhUserauthinfoMapper iWskhUserauthinfoMapper;
    @Resource
    private IUseraccountService iUseraccountService;
    @Resource
    private SequenceIDGeneratorUtils idGeneratorUtils;
    @Resource
    private IDivisionMapper iDivisionMapper;

    @Override
    public PageResult<WskhUserinfo> queryByPage(String username, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        WskhUserinfo wskhUserinfoVo = new WskhUserinfo();
        wskhUserinfoVo.setUsername(username);
        wskhUserinfoVo.setUsertype(2);
        //列表返回
        IPage<WskhUserinfo> page = new Page<>(pageNum, pageSize);
        IPage<WskhUserinfo> wskhUserinfoVos = iWskhUserinfoMapper.selectByPage(page, wskhUserinfoVo);
        PageResult<WskhUserinfo> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(wskhUserinfoVos.getPages());
        pageResult.setCurrent(wskhUserinfoVos.getCurrent());
        pageResult.setTotal(wskhUserinfoVos.getTotal());
        pageResult.setPageSize(wskhUserinfoVos.getSize());
        pageResult.setData(wskhUserinfoVos.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<WskhUserinfo> queryDetail(Long userId, HttpServletRequest request) {
        //获取解密的key
        WskhUserinfo wskhUserinfo = iWskhUserinfoMapper.selectOne(new QueryWrapper<WskhUserinfo>().eq("USERID", userId));
        if (StringUtils.isNotBlank(wskhUserinfo.getBankid())) {
            BankBankinfo bi = iBankBankinfoMapper.selectOne(new QueryWrapper<BankBankinfo>().eq("BANKID", wskhUserinfo.getBankid()));
            if (bi != null) {
                wskhUserinfo.setBankname(bi.getBankname());
            }
        }
        WskhOpenaccountconfig configtype = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("CONFIGTYPE", 45));
        if (Objects.nonNull(configtype)) {
            wskhUserinfo.setIsBank(configtype.getConfigvalue());
        }
        wskhUserinfo.setModifiedtime(new Date());
        //推荐人
        if (wskhUserinfo.getReferral() != null && !wskhUserinfo.getReferral().isEmpty()) {
            Useraccount referral = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("USERID", wskhUserinfo.getReferral()));
            if (Objects.nonNull(referral)) {
                wskhUserinfo.setReferralname(referral.getAccountname());
            }
        }
        String countryName = "";
        if (wskhUserinfo.getBrokerid() != null) {
            wskhUserinfo.setBrokername(iUseraccountMapper.selectOrganName(Long.valueOf(wskhUserinfo.getBrokerid())));
        }
        if (wskhUserinfo.getAreaid() != null) {
            wskhUserinfo.setAreaname(iUseraccountMapper.selectOrganName(wskhUserinfo.getAreaid()));
        }
        if (wskhUserinfo.getMemberareaid() != null) {
            wskhUserinfo.setMemberusername(iUseraccountMapper.selectOrganName(wskhUserinfo.getMemberareaid()));
        }
        if (wskhUserinfo.getCountryid() != null) {
            countryName = iDivisionMapper.selectAreaPathName(wskhUserinfo.getCountryid());
        }
        if (wskhUserinfo.getDistrictid() != null) {
            wskhUserinfo.setPathname(countryName + iDivisionMapper.selectAreaPathName(wskhUserinfo.getDistrictid()) + wskhUserinfo.getCardaddress());
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), wskhUserinfo);
    }

    @Override
    public AjaxResult addAreainfo(WskhUserinfo vo, Systemmanager systemmanager, HttpServletRequest request) {
        // #6597 管理端】不管是后台注册还是客户端注册，身份证号填写的那一栏，如果涉及到输入字母X，需要固定只能输入大写字母
        if (vo != null && StringUtils.isNotBlank(vo.getCardnum())) {
            vo.setCardnum(vo.getCardnum().toUpperCase());
        }

        List<WskhBlacklist> wskhBlacklists = iWskhBlacklistMapper.selectList(new QueryWrapper<WskhBlacklist>().eq("CARDTYPE", vo.getCardtype()).eq("CARDNUM", vo.getCardnum()));
        if (!CollectionUtils.isEmpty(wskhBlacklists)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_012.getCode(), request.getHeader("Accept-Language"));
        }
        // 机构开户证件号码是否唯一
        String areaCardFlag = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, Constants.SYSPARAM_CARD_NO);
        // 验证证件号码是否存在
        if (areaCardFlag != null && areaCardFlag.equals("1") && !iCommonService.checkOranCardNumOrMobile(3, 1, null, EncryptionUtils.encryptByAES(vo.getCardnum()))) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
        }
        // 验证手机号是否存在
        if (StringUtils.isNotBlank(vo.getMobilephone()) && !iCommonService.checkOranCardNumOrMobile(3, 2, null, EncryptionUtils.encryptByAES(vo.getCardnum()))) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_016.getCode(), request.getHeader("Accept-Language"));
        }
        //入库重新加密
        encrypt(vo);
        try {
            if (vo.getUserstate() == null) {
                vo.setUserstate(1);
            }
            vo.setIsvalidate("1");
            vo.setCreatetime(new Date());
            //管理端开户
            vo.setOpenmode(1);
            if (vo.getUsertype() == null) {
                //1:投资者 2:机构
                vo.setUsertype(2);
            }
            vo = (WskhUserinfo) SensitiveEncryptUtil.sensitiveEncrypt(vo, null);
            vo.setModifiedtime(new Date());
            iWskhUserinfoMapper.insert(vo);
        } catch (Exception e) {
            log.error("添加开户信息失败，请检查！失败原因：" + Arrays.toString(e.getStackTrace()));
            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"));
    }

    @Override
    public AjaxResult updateAreainfo(WskhUserinfo vo, Systemmanager systemmanager, HttpServletRequest request) {

        // #6597 管理端】不管是后台注册还是客户端注册，身份证号填写的那一栏，如果涉及到输入字母X，需要固定只能输入大写字母
        if (vo != null && StringUtils.isNotBlank(vo.getCardnum())) {
            vo.setCardnum(vo.getCardnum().toUpperCase());
        }

        List<WskhBlacklist> wskhBlacklists = iWskhBlacklistMapper.selectList(new QueryWrapper<WskhBlacklist>()
                .eq("CARDTYPE", vo.getCardtype())
                .eq("CARDNUM", vo.getCardnum()));
        if (CollectionUtils.isNotEmpty(wskhBlacklists)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_012.getCode(), request.getHeader("Accept-Language"));
        }
        try {
            // 机构开户证件号码是否唯一
            String areacardflag = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, Constants.SYSPARAM_CARD_NO);
            List<WskhUserinfo> wskhUserinfoList = iWskhUserinfoMapper.selectList(new QueryWrapper<WskhUserinfo>()
                    .eq("CARDNUM", vo.getCardnum())
                    .eq("USERID", vo.getUserid()));
            if (areacardflag != null && areacardflag.equals("1") && CollectionUtils.isNotEmpty(wskhUserinfoList)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
            }
            WskhUserinfo base = iWskhUserinfoMapper.selectOne(new QueryWrapper<WskhUserinfo>().eq("USERID", vo.getUserid()));
            BeanUtils.copyProperties(vo, base);
            //入库重新加密
            encrypt(vo);
            base = (WskhUserinfo) SensitiveEncryptUtil.sensitiveEncrypt(base, null);
            iWskhUserinfoMapper.update(base, new QueryWrapper<WskhUserinfo>().eq("USERID", vo.getUserid()));
        } catch (Exception e) {
            log.error("修改开户信息失败，请检查！失败原因：" + Arrays.toString(e.getStackTrace()));
            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"));
    }

    @Override
    public AjaxResult reBack(Long userid, HttpServletRequest request) {
        WskhUserinfo wskhUserinfo = iWskhUserinfoMapper.selectOne(new QueryWrapper<WskhUserinfo>().eq("USERID", userid));
        if (wskhUserinfo != null) {
            if (wskhUserinfo.getUserstate() != 2 && wskhUserinfo.getUserstate() != 4) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_022.getCode(), request.getHeader("Accept-Language"));
            }
            wskhUserinfo.setUserstate(1);
            iWskhUserinfoMapper.update(wskhUserinfo, new QueryWrapper<WskhUserinfo>().eq("USERID", userid));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult delete(Long userid, HttpServletRequest request) {
        iWskhUserinfoMapper.delete(new QueryWrapper<WskhUserinfo>().eq("USERID", userid));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult approved(WskhUserinfo vo, HttpServletRequest request) {
        try {
            //获取当前登录用户
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            WskhUserinfo wui = iWskhUserinfoMapper.selectOne(new QueryWrapper<WskhUserinfo>().eq("USERID", vo.getUserid()));
            if (Objects.isNull(wui)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_018.getCode(), request.getHeader("Accept-Language"));
            }
            if (wui.getUserstate() != 2 && wui.getUserstate() != 4) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_018.getCode(), request.getHeader("Accept-Language"));
            }
            if (vo.getAuditflag() != 1) {
                //不通过
                wui.setUserstate(3);
                if (vo.getRemark().length() > 80) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_020.getCode(), request.getHeader("Accept-Language"));
                }
                wui.setRemark(vo.getRemark());
                iWskhUserinfoMapper.update(wui, new QueryWrapper<WskhUserinfo>().eq("USERID", vo.getUserid()));
            } else {
                Useraccount isUa = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("USERID", Long.valueOf(vo.getAreacode())));
                if (Objects.nonNull(isUa)) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_010.getCode(), request.getHeader("Accept-Language"));
                }
                //验证证件号码是否存在
                if (!iCommonService.checkOranCardNumOrMobile(2, 1, null, vo.getCardnum())) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
                }
                if (wui.getUserinfotype() == 2) {
                    //机构类型为企业需 名称唯一,1:个人,2:企业
                    List<Userinfo> userinfoList = iUserinfoMapper.selectList(new QueryWrapper<Userinfo>()
                            .eq("customername", wui.getCustomername().trim())
                            .eq("userinfotype", 2));
                    if (CollectionUtils.isNotEmpty(userinfoList)) {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_013.getCode(), request.getHeader("Accept-Language"));
                    }
                }
                List<Systemmanager> list = iSystemmanagerMapper.selectList(new QueryWrapper<Systemmanager>().eq("logincode", vo.getSmlogincode().trim()));
                if (CollectionUtils.isNotEmpty(list)) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_014.getCode(), request.getHeader("Accept-Language"));
                }
                //新增用户信息
                List<Taaccount> taaccountList = insertUserAccount(vo, wui, systemmanager);
                //新增管理员信息
                insertSystem(vo, wui, systemmanager);
                //新增机构用户信息
                Userinfo userinfo = insertUserInfo(vo, wui, systemmanager);
                //删除中间表信息
                iWskhUserinfoMapper.delete(new QueryWrapper<WskhUserinfo>().eq("USERID", wui.getUserid()));

                //proto传输信息给到其他服务
                try {
                    if (vo.getAuditflag() == 1) {
                        //审核通过
                        for (Taaccount taaccount : taaccountList) {
                            iSendMsgService.sendCustomerInfo(userinfo, taaccount.getAccountid(), "1", 3);
                            iSendMsgService.sendUserChangeMsg(taaccount.getAccountid(), taaccount.getUserid(),
                                    SysEnums.UserOperateTypeEnum.ADD.getType(),
                                    SysEnums.AccountOperateTypeEnum.ADD.getType(),
                                    SysEnums.NotifyModeEnum.UNICAST.getType());
                        }
                    }
                } catch (Exception e) {
                    log.error("网上开户审核发送消息失败，失败原因：" + Arrays.toString(e.getStackTrace()));
                }
            }
        } catch (Exception e) {
            log.error("审核提交失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_015.getCode(), request.getHeader("Accept-Language"));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<InvestorQueryResult> queryInvestorPage(InvestorQueryParam investorQueryParam, HttpServletRequest request) {
        //列表返回
        IPage<InvestorQueryResult> page = new Page<>(investorQueryParam.getPageNum(), investorQueryParam.getPageSize());
        IPage<InvestorQueryResult> investorQueryResults = iWskhUserinfoMapper.queryInvestorPage(page, investorQueryParam);
        PageResult<InvestorQueryResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(investorQueryResults.getPages());
        pageResult.setCurrent(investorQueryResults.getCurrent());
        pageResult.setTotal(investorQueryResults.getTotal());
        pageResult.setPageSize(investorQueryResults.getSize());
        pageResult.setData(investorQueryResults.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<WskhUserinfo> querySunDetail(Long userId, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!checkWskhAccountRole(systemmanager, userId)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        return queryDetail(userId, request);
    }

    @Override
    public AjaxResult editWskhUserinfo(WskhUserinfo currentVo, Systemmanager systemmanager, HttpServletRequest request) {
        // #6597 管理端】不管是后台注册还是客户端注册，身份证号填写的那一栏，如果涉及到输入字母X，需要固定只能输入大写字母
        if (currentVo != null && StringUtils.isNotBlank(currentVo.getCardnum())) {
            currentVo.setCardnum(currentVo.getCardnum().toUpperCase());
        }

        WskhUserinfo base = iWskhUserinfoMapper.selectOne(new QueryWrapper<WskhUserinfo>().eq("USERID", currentVo.getUserid()));
        if (!checkWskhAccountRole(systemmanager, currentVo.getUserid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        List<WskhBlacklist> wskhBlacklists = iWskhBlacklistMapper.selectList(new QueryWrapper<WskhBlacklist>()
                .eq("CARDTYPE", currentVo.getCardtype())
                .eq("CARDNUM", currentVo.getCardnum()));
        if (CollectionUtils.isNotEmpty(wskhBlacklists)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_012.getCode(), request.getHeader("Accept-Language"));
        }
        Systemparam sysParam = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_CARD_NOTWO));
        //验证证件号码是否唯一
        if (!base.getCardnum().equals(EncryptionUtils.encryptByAES(currentVo.getCardnum()))) {
            if (!iCommonService.checkOranCardNumOrMobile(3, 1, currentVo.getUserid(), EncryptionUtils.encryptByAES(currentVo.getCardnum())) && (sysParam == null) || "1".equals(sysParam.getParamvalue())) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
            }
        }
        // 验证手机号是否唯一
        if (!base.getMobilephone().equals(EncryptionUtils.encryptByAES(currentVo.getMobilephone()))) {
            if (!iCommonService.checkOranCardNumOrMobile(3, 2, currentVo.getUserid(), EncryptionUtils.encryptByAES(currentVo.getMobilephone()))) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_016.getCode(), request.getHeader("Accept-Language"));
            }
        }
        try {
            BeanUtils.copyProperties(currentVo, base);
            //入库重新加密
            encrypt(currentVo);
            base = (WskhUserinfo) SensitiveEncryptUtil.sensitiveEncrypt(base, null);
            iWskhUserinfoMapper.update(base, new QueryWrapper<WskhUserinfo>().eq("USERID", currentVo.getUserid()));
        } catch (Exception e) {
            log.error("修改开户信息失败，请检查！失败原因：" + Arrays.toString(e.getStackTrace()));
            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"));
    }

    @Override
    public AjaxResult addWskhUserinfo(WskhUserinfo currentVo, Systemmanager systemmanager, HttpServletRequest request) {
        // #6597 管理端】不管是后台注册还是客户端注册，身份证号填写的那一栏，如果涉及到输入字母X，需要固定只能输入大写字母
        if (currentVo != null && StringUtils.isNotBlank(currentVo.getCardnum())) {
            currentVo.setCardnum(currentVo.getCardnum().toUpperCase());
        }

        List<WskhBlacklist> wskhBlacklists = iWskhBlacklistMapper.selectList(new QueryWrapper<WskhBlacklist>()
                .eq("CARDTYPE", currentVo.getCardtype())
                .eq("CARDNUM", currentVo.getCardnum()));
        if (CollectionUtils.isNotEmpty(wskhBlacklists)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_012.getCode(), request.getHeader("Accept-Language"));
        }
        Systemparam sysParm = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_CARD_NOTWO));
        //校验唯一性
        List<Userinfo> userinfoList = iUserinfoMapper.selectList(new QueryWrapper<Userinfo>()
                .eq("cardnum", EncryptionUtils.encryptByAES(currentVo.getCardnum()))
                .or()
                .eq("mobile", EncryptionUtils.encryptByAES(currentVo.getMobilephone()))
                .and(a -> a.eq("userstatus", 1)));
        if (CollectionUtils.isNotEmpty(userinfoList)) {
            for (Userinfo userinfo : userinfoList) {
                if (sysParm == null || "1".equals(sysParm.getParamvalue())) {
                    if (StringUtils.isNotBlank(userinfo.getCardnum()) &&
                            userinfo.getCardnum().equals(EncryptionUtils.encryptByAES(currentVo.getCardnum()))) {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
                    }
                }

                if (StringUtils.isNotBlank(userinfo.getMobile()) &&
                        userinfo.getMobile().equals(
                                EncryptionUtils.encryptByAES(currentVo.getMobilephone()))) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_016.getCode(), request.getHeader("Accept-Language"));
                }
            }
        }
        List<WskhUserinfo> wskhUserinfoList = iWskhUserinfoMapper.selectList(new QueryWrapper<WskhUserinfo>()
                .eq("cardnum", EncryptionUtils.encryptByAES(currentVo.getCardnum()))
                .or()
                .eq("MOBILEPHONE", EncryptionUtils.encryptByAES(currentVo.getMobilephone()))
                .and(a -> a.in("userstate", 1, 2, 4)));
        if (CollectionUtils.isNotEmpty(wskhUserinfoList)) {
            for (WskhUserinfo wskhUserinfo : wskhUserinfoList) {
                if (sysParm == null || "1".equals(sysParm.getParamvalue())) {
                    if (StringUtils.isNotBlank(wskhUserinfo.getCardnum()) &&
                            wskhUserinfo.getCardnum().equals(EncryptionUtils.encryptByAES(currentVo.getCardnum()))) {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
                    }
                }

                if (StringUtils.isNotBlank(wskhUserinfo.getMobilephone()) &&
                        wskhUserinfo.getMobilephone().equals(
                                EncryptionUtils.encryptByAES(currentVo.getMobilephone()))) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_016.getCode(), request.getHeader("Accept-Language"));
                }
            }
        }
        //插入数据
        try {
            if (systemmanager.getReletype().intValue() == SysConstants.SYS_TYPE_MANAGE) {
                if (currentVo.getAreaid() == null) {
                    currentVo.setAreaid(currentVo.getMemberareaid());
                }
            } else {
                if (currentVo.getAreaid() == null) {
                    currentVo.setAreaid(systemmanager.getAreauserid());
                }
                if (currentVo.getMemberareaid() == null) {
                    Useraccount area = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", currentVo.getAreaid()));
                    currentVo.setMemberareaid(area.getMemberuserid());
                }
            }
            if (currentVo.getUserstate() == null) {
                currentVo.setUserstate(1);
            }
            currentVo.setIsvalidate("1");
            currentVo.setCreatetime(new Date());
            currentVo.setOpenmode(1);//管理端开户
            currentVo.setUsertype(1);//用户类型 - 1:投资者 2:机构

            currentVo = (WskhUserinfo) SensitiveEncryptUtil.sensitiveEncrypt(currentVo, null);
            iWskhUserinfoMapper.insert(currentVo);
        } catch (Exception e) {
            log.error("新增开户信息失败，请检查！失败原因：" + Arrays.toString(e.getStackTrace()));
            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"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult investorProcess(InvestorProcessParam param, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("msg", "审核成功");

        WskhUserinfo wui = iWskhUserinfoMapper.selectOne(new QueryWrapper<WskhUserinfo>().eq("userid", param.getAuditid()));
        if (wui == null) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_021.getCode(), request.getHeader("Accept-Language"));
        }

        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!checkWskhAccountRole(systemmanager, param.getAuditid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        //已实名认证
        param.setHasauth(1);
        String sp1006 = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "1006");
        if (!Strings.isNullOrEmpty(sp1006) && sp1006.equals("0")) {
            // 1006 管理端开交易商是否默认已实名 默认为1， 中融为0（接的爱签四要素实名）
            param.setHasauth(0);
        }
        boolean sysFlag = true;
        String sysparm999 = iCommonService.getSysparmById(Constants.SYSPARAM_OPEN_AUDIT_MARKET);
        //系统开市 或 闭市 时方可注册 -- 涉及开户送红包(THJ)等  20221114 - dyp
        //添加系统参数999控制， 当999为空 或 0 时不 需要开市时可审核
        if ("1".equals(sysparm999)) {
            sysFlag = false;
            Marketrun mr = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid", 0L));
            if (null != mr && (mr.getRunstatus() == 2 || mr.getRunstatus() == 5)) {
                sysFlag = true;
            }
        }
        if (!sysFlag) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM007.getCode(), request.getHeader("Accept-Language"));
        }

        //错误 #59041 投资者开户关联了推荐人，复审时，把推荐人注销，审核通过后，推荐人也得到了现金红包
        if (!"".equals(wui.getReferral()) && null != wui.getReferral()) {
            Userinfo userinfo = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", Long.parseLong(wui.getReferral())));
            if (userinfo != null && userinfo.getUserstatus() == 2) {
                //如果已经注销
                wui.setReferral("");
            }
        }

        if (param.getAuditflag() == 1) {
            Systemparam sysParm = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_CARD_NOTWO));
            //校验唯一性
            List<Userinfo> userinfoList = iUserinfoMapper.selectList(new QueryWrapper<Userinfo>()
                    .eq("cardnum", EncryptionUtils.encryptByAES(wui.getCardnum()))
                    .or()
                    .eq("mobile", EncryptionUtils.encryptByAES(wui.getMobilephone()))
                    .and(a -> a.eq("userstatus", 1)));
            if (CollectionUtils.isNotEmpty(userinfoList)) {
                for (Userinfo userinfo : userinfoList) {
                    if (sysParm == null || "1".equals(sysParm.getParamvalue())) {
                        if (StringUtils.isNotBlank(userinfo.getCardnum()) &&
                                userinfo.getCardnum().equals(EncryptionUtils.encryptByAES(wui.getCardnum()))) {
                            return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
                        }
                    }
                    if (StringUtils.isNotBlank(userinfo.getMobile()) &&
                            userinfo.getMobile().equals(
                                    EncryptionUtils.encryptByAES(wui.getMobilephone()))) {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_016.getCode(), request.getHeader("Accept-Language"));
                    }
                }
            }
        }

        if (systemmanager.getReletype() == 1) {
            if (wui.getUserstate() != 2 && wui.getUserstate() != 4) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_021.getCode(), request.getHeader("Accept-Language"));
            }
            //平台管理员审核
            if (param.getAuditflag() == 1) {
                AjaxResult result = checkOrgan(wui, request);
                if (result != null) {
                    return result;
                }
                //会员下投资者数量
                Long count = getOrganMaxinvestornum(wui.getMemberareaid());
                String countStr = CommonUtil.addZero(count.toString(), 5);//前补0,5位
                //投资者ID
                Long userid = Long.valueOf(wui.getMemberareaid() + countStr);
                passauto(wui, userid, countStr, systemmanager, param, resultMap);
                iUseraccountMapper.updateAccount(userid);
            } else {
                //不通过
                wui.setUserstate(5);
                if (param.getMsg().length() > 80) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_020.getCode(), request.getHeader("Accept-Language"));
                }
                //不通过原因
                wui.setRemark(param.getMsg());
                iWskhUserinfoMapper.updateById(wui);
                sendFailreMsg(wui);
            }
        } else {
            if (wui.getUserstate() != 2 && wui.getUserstate() != 4) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_021.getCode(), request.getHeader("Accept-Language"));
            }
            if (param.getAuditflag() == 1) {
                AjaxResult result = checkOrgan(wui, request);
                if (result != null) {
                    return result;
                }
                wui.setUserstate(4);
                iWskhUserinfoMapper.updateById(wui);
            } else {
                wui.setUserstate(3);
                if (param.getMsg().length() > 80) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_020.getCode(), request.getHeader("Accept-Language"));
                }
                //不通过原因
                wui.setRemark(param.getMsg());
                sendFailreMsg(wui);
                iWskhUserinfoMapper.updateById(wui);
            }
        }

        if (resultMap.get("code") != null && resultMap.get("code").toString().equals("0")) {
            //发送消息
            sendAuditMsg(resultMap);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private void sendAuditMsg(Map<String, Object> resultMap) {
        try {
            if (resultMap.containsKey("taaccount") && resultMap.get("taaccount") != null
                    && resultMap.containsKey("userinfo") && resultMap.get("userinfo") != null) {
                List<Taaccount> ta = (List<Taaccount>) resultMap.get("taaccount");
                Userinfo ui = (Userinfo) resultMap.get("userinfo");
                for (Taaccount taaccount : ta) {
                    iSendMsgService.sendCustomerInfo(ui, taaccount.getAccountid(), "1", 0);

                    //发给账户服务的，用户变更通知
                    iSendMsgService.sendUserChangeMsg(taaccount.getAccountid(), taaccount.getUserid(),
                            SysEnums.UserOperateTypeEnum.ADD.getType(),
                            SysEnums.NotifyModeEnum.UNICAST.getType());
                }
            }

            if (resultMap.containsKey("loginaccount") && resultMap.get("loginaccount") != null) {
                Loginaccount la = (Loginaccount) resultMap.get("loginaccount");

                // 登录账户变更通知 changetype = 0 新增
                sendLoginAccChangeNtf(la.getLoginid(), 0);
            }

        } catch (Exception e) {
            log.error("账户信息变更通知发送失败，失败原因：" + e.getMessage());
        }
    }

    public void sendLoginAccChangeNtf(Long loginid, int changeType) {
        if (loginid == null) return;
        Set<Long> logins = new HashSet<>();
        logins.add(loginid);
        iSendMsgService.sendLoginMsg(logins, changeType, 0);
    }

    public void passauto(WskhUserinfo wui, Long userid, String countStr, Systemmanager user, InvestorProcessParam param, Map<String, Object> resultMap) {
        //系统默认登录密码
        String lpwd = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "046");
        //系统默认资金密码
        String zpwd = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "047");

        if (StringUtils.isNotBlank(wui.getLoginpwd())) {
            // 开户信息有密码时w使用其密码
            lpwd = EncryptUtilForSearch.Base64ToString(wui.getLoginpwd());
        }

        Useraccount ua = new Useraccount();
        ua.setUserid(userid);
        ua.setUsertype(5);
        if (wui.getUsername() == null || wui.getUsername().equals("")) {
            ua.setAccountname(EncryptionUtils.decryptForAES(wui.getMobilephone()).substring(0, 3) + "****"
                    + EncryptionUtils.decryptForAES(wui.getMobilephone()).substring(7, 11));
        } else {
            ua.setAccountname(wui.getUsername());
        }
        if (StringUtils.isNotBlank(wui.getBrokerid())) {
            ua.setBroker(Long.valueOf(wui.getBrokerid()));
        }
        ua.setAccountstatus(4);
        ua.setModifystatus(1);
        ua.setCreatetime(new Date());
        ua.setCreatorid(user.getAutoid());
        ua.setParentuserid(wui.getAreaid());
        Useraccount parentUser = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", wui.getAreaid()));
        if (parentUser != null) {
            ua.setSubarealevelpath(parentUser.getSubarealevelpath() + userid.toString() + ",");
        }
        ua.setMemberuserid(wui.getMemberareaid());
        ua.setModifytime(new Date());
        ua.setModifierid(user.getAutoid());
        ua.setAudituserid(user.getAutoid());
        ua.setAudittime(ua.getModifytime());
        ua.setRefernum(generateReferNum());
        ua.setHasauth(param.getHasauth() != null ? param.getHasauth() : 0);
        if (!"".equals(wui.getReferral()) && null != wui.getReferral()) {
            ua.setRefereeuserid(Long.parseLong(wui.getReferral()));
        }

        ua.setCreatetradedate(iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid", 0L)).getTradedate());
        iUseraccountMapper.insert(ua);

        //登录账户生成规则
        String rules = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "049");
        StringBuffer loginidStr = new StringBuffer("2");
        if ("0".equals(rules)) {
            //不包含所属机构
            loginidStr = loginidStr.append(userid.toString());
        } else {
            //包含所属机构
            if (wui.getMemberareaid().compareTo(wui.getAreaid()) == 0) {
                //所属机构为会员
                loginidStr = loginidStr.append(wui.getAreaid()).append("0000").append(countStr);
            } else {
                //所属机构为子机构
                Long countP = getOrganMaxinvestornum(wui.getAreaid());
                loginidStr = loginidStr.append(wui.getAreaid()).append(CommonUtil.addZero(countP.toString(), 5));
            }
        }
        //是否允许多登录账户  允许 增加序号位 2位
        String flag = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "065");
        if ("1".equals(flag)) {
            loginidStr = loginidStr.append("01");
        }

        //登录账户ID
        Long loginid = Long.valueOf(loginidStr.toString());

        Userinfo ui = new Userinfo();

        //网上开户有类型选择 ，管理端没有 ，增加判断，
        if (wui.getUserinfotype() == null && wui.getCardtype() != null) {
            Enumdicitem item = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                    .eq("enumdiccode", "certificatetype")
                    .eq("enumitemname", Long.valueOf(wui.getCardtype())));
            Certificatetypeconfig config = iCertificatetypeconfigMapper.selectOne(new QueryWrapper<Certificatetypeconfig>().eq("enumdicitemid", item.getAutoid()));
            if (config != null) {
                ui.setUserinfotype(config.getIsperson() == 2 ? 2 : 1);
            } else {
                ui.setUserinfotype(1);
            }
        } else {
            ui.setUserinfotype(wui.getUserinfotype());
        }
        if (wui.getUserinfotype() == null) {
            ui.setUserinfotype(1);
        }
        ui.setUserid(userid);
        ui.setCustomername(ua.getAccountname());
        ui.setOpenmode(wui.getOpenmode());
        ui.setCardtypeid(wui.getCardtype());
        ui.setCardnum(wui.getCardnum());
        ui.setContactname(wui.getContactname());
        ui.setSex(wui.getSex());
        ui.setMobile(wui.getMobilephone());
        ui.setEmail(wui.getEmail());
        ui.setWechat(wui.getWechat());
        ui.setHalfbodyphotourl(wui.getHalfbodyphotourl());
        ui.setCardfrontphotourl(wui.getCardfrontphotourl());
        ui.setCardbackphotourl(wui.getCardbackphotourl());
        ui.setAddress(wui.getCardaddress());
        ui.setCreatetime(new Date());
        ui.setRemark(wui.getRemark());
        ui.setUserstatus(1);
        ui.setUsertype(5);
        ui.setCountryid(wui.getCountryid());
        ui.setSignpdfurl(wui.getSignpdfurl());
        ui.setProvinceid(wui.getProvinceid());
        ui.setCityid(wui.getCityid());
        ui.setDistrictid(wui.getDistrictid());
        ui.setLegalcardbackphotourl(wui.getLegalcardbackphotourl());
        ui.setLegalcardfrontphotourl(wui.getLegalcardfrontphotourl());
        ui.setLegalpersonname(wui.getLegalpersonname());
        ui.setOtherurl(wui.getOtherurl());
        ui.setTelphone(wui.getTelphone());
        ui.setCompany(wui.getCompany());
        if (StringUtils.isNotBlank(wui.getBankid())) {
            ui.setBankid(wui.getBankid());
        }
        ui.setBankaccount(wui.getBankaccount());
        ui.setBankname(wui.getBankname());
        ui.setBankcardfrontphotourl(wui.getBankcardfrontphotourl());
        ui.setPostalcode(wui.getPostalcode());
        ui.setNickname(wui.getNickname());

        // 任务 #87440  尚志大宗【网上开户接口】通过手机号+推荐码开户时，保存手机号明文到Mobile2字段 "UserInfo"表添加字段"Mobile2";
        WskhOpenaccountconfig woac = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("CONFIGTYPE", 77L));

        if (woac != null && "1".equals(woac.getConfigvalue())) {
            ui.setMobile2(EncryptionUtils.decryptForAES(wui.getMobilephone()));
        }

        iUserinfoMapper.insert(ui);

        if (!"".equals(wui.getCardaddress())) {
            //保存收货地址
            Userreceiveinfo urInfo = new Userreceiveinfo();
            urInfo.setAddress(wui.getCardaddress());
            urInfo.setCardnum(wui.getCardnum());
            urInfo.setCardtypeid(wui.getCardtype());
            urInfo.setCityid(null != wui.getCityid() ? wui.getCityid().intValue() : null);
            urInfo.setCountryid(null != wui.getCountryid() ? wui.getCountryid().intValue() : null);
            urInfo.setDistrictid(null != wui.getDistrictid() ? wui.getDistrictid().intValue() : null);
            urInfo.setProvinceid(null != wui.getProvinceid() ? wui.getProvinceid().intValue() : null);
            urInfo.setPhonenum(wui.getMobilephone());
            urInfo.setReceivername(wui.getUsername());
            urInfo.setUserid(userid);
            iUserreceiveinfoMapper.insert(urInfo);
        }

        Loginaccount la = new Loginaccount();
        la.setLoginfailnum(0);
        la.setLoginid(loginid);
        la.setUserid(userid);
        la.setLoginusertype(1);
        la.setLoginstatus(1);
        la.setPassword(EncryptionUtils.encryptSHA(loginid + lpwd));
        la.setModifierid(user.getAutoid());
        la.setModifytime(new Date());
        la.setHasupdatedpwd(0);
        iLoginaccountMapper.insert(la);
        resultMap.put("loginaccount", la);

        //默认保存手机登录关联关系
        if (StringUtils.isNotBlank(ui.getMobile())) {
            Userauthinfo uai = new Userauthinfo();
            uai.setAuthid(ui.getMobile());
            uai.setAuthtype(3);
            uai.setLoginid(loginid);
            uai.setUserid(userid);
            uai.setIsvalid(1);
            iUserauthinfoMapper.insert(uai);
        }

        //资金账户 多币种
        List<Enumdicitem> li = iEnumdicitemMapper.selectList(new QueryWrapper<Enumdicitem>()
                .eq("enumdiccode", "currency")
                .eq("enumitemstatus", 1));
        BankSystemconfig config = iBankSystemconfigMapper.selectOne(new QueryWrapper<BankSystemconfig>().eq("CONFIGID", SysConstants.BANK_CONFIG_ACTIVATION));

        List<Taaccount> taaList = new ArrayList<>();
        for (Enumdicitem enumdicitem : li) {
            String manageid = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "001");
            Long accountno = Long.valueOf(manageid + CommonUtil.addZero(String.valueOf(idGeneratorUtils.getGeneratorID(Taaccount.class)), 9));
            Taaccount ac = new Taaccount(accountno, ua.getUserid(), EncryptionUtils.encryptSHA(zpwd));
            ac.setIsreckonaccount(0);
            ac.setCurrencyid(enumdicitem.getEnumitemname().intValue());
            //资金账号是否需要激活
            if (config != null && config.getValidstatus() == 1 && config.getConfigvalue().equals("1") && ac.getIsmain() == 1) {
                ac.setTradestatus(SysEnums.TradeStatusEnum.TOBEACTIVATE.getType());
            } else {
                ac.setTradestatuschangetime(new Date()); //激活时间
            }
            //写入关联用户
            ac.setRelateduserid(ua.getUserid());
            taaList.add(ac);
            iTaaccountMapper.insert(ac);
        }
        resultMap.put("taaccount", taaList);
        resultMap.put("userinfo", ui);

        if (wui.getOpenmode() == 11 || wui.getOpenmode() == 12) {
            WskhUserauthinfo wuai = iWskhUserauthinfoMapper.selectOne(new QueryWrapper<WskhUserauthinfo>().eq("userid", wui.getUserid()));

            Userauthinfo uai = new Userauthinfo();
            uai.setAuthid(wuai.getAuthid());
            uai.setAuthtype(wuai.getAuthtype());
            uai.setLoginid(loginid);
            uai.setUserid(userid);
            uai.setIsvalid(1);
            iUserauthinfoMapper.insert(uai);
            iWskhUserauthinfoMapper.deleteById(wuai);
        }

        iWskhUserinfoMapper.deleteById(wui);

        //发送审核通过短信
        WskhOpenaccountconfig woconfig = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("CONFIGTYPE", 17L));

        if (woconfig != null && "0".equals(woconfig.getConfigvalue()) && null != wui.getMobilephone()) {
            ShortMessageMtp1.ShortMsgSendReq.Builder smsbuilder = ShortMessageMtp1.ShortMsgSendReq.newBuilder();
            smsbuilder.setMsgType(1);
            smsbuilder.setTemplateID(3);
            smsbuilder.setPriority(2);
            smsbuilder.setScheduledTime("");
            smsbuilder.addRecvPhone(EncryptionUtils.decryptForAES(wui.getMobilephone()));
            smsbuilder.addParamValues(wui.getUsername().replaceAll("\\*", "-"));
            smsbuilder.addParamValues(taaList.get(0).getAccountid().toString());
            smsbuilder.addParamValues(loginid.toString());
            smsbuilder.addParamValues(lpwd);
            smsbuilder.addParamValues(zpwd);
            smsbuilder.addParamValues(iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", ua.getParentuserid())).
                    getAccountname().replaceAll("\\*", "-"));

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

        // 有三方实名认证配置，且无记录 则生成相应的表记录; -- gzys 爱签 \ tjmd 腾讯电子签
        iUseraccountService.addUserESignInfo(ua.getUserid(), ua.getMemberuserid());
    }

    private Long getOrganMaxinvestornum(Long memberareaid) {
        Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", memberareaid));
        if (Objects.nonNull(ua)) {
            long num = ua.getMaxinvestornum() == null ? 0 : ua.getMaxinvestornum();
            ua.setMaxinvestornum(num + 1);
            iUseraccountMapper.update(ua, new QueryWrapper<Useraccount>().eq("userid", ua.getUserid()));
            return ua.getMaxinvestornum();
        }
        return 0L;
    }

    private void sendFailreMsg(WskhUserinfo wui) {
        WskhOpenaccountconfig woconfig = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("CONFIGTYPE", 17L));
        if (woconfig != null && "0".equals(woconfig.getConfigvalue()) && null != wui.getMobilephone()) {
            ShortMessageMtp1.ShortMsgSendReq.Builder smsbuilder = ShortMessageMtp1.ShortMsgSendReq.newBuilder();
            smsbuilder.setMsgType(1);
            smsbuilder.setTemplateID(5);
            smsbuilder.setPriority(2);
            smsbuilder.setScheduledTime("");
            smsbuilder.addRecvPhone(EncryptionUtils.decryptForAES(wui.getMobilephone()));
            smsbuilder.addParamValues(wui.getUsername().replaceAll("\\*", "-")); //用户名称
            smsbuilder.addParamValues(wui.getRemark().replaceAll("\\*", "-"));
            smsbuilder.addParamValues(iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", wui.getAreaid())).
                    getAccountname().replaceAll("\\*", "-"));

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


    public AjaxResult checkOrgan(WskhUserinfo wui, HttpServletRequest request) {
        Long[] ids = new Long[3];
        if (wui.getMemberareaid() != null) {
            ids[0] = wui.getMemberareaid();
        }
        if (wui.getAreaid() != null) {
            ids[1] = wui.getAreaid();
        }
        if (wui.getBrokerid() != null) {
            ids[2] = Long.valueOf(wui.getBrokerid());
        }
        List<Long> idList = new ArrayList<>();
        for (Long id : ids) {
            if (id != null) {
                idList.add(id);
            }
        }
        List<Useraccount> organ = iUseraccountMapper.selectList(new QueryWrapper<Useraccount>()
                .in(CollectionUtils.isNotEmpty(idList), "userid", idList));

        if (CollectionUtils.isNotEmpty(organ)) {
            for (Useraccount ua : organ) {
                if (ua.getAccountstatus() == 4) {
                    break;
                }
                if (ua.getUsertype() == 2) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_023.getCode(), request.getHeader("Accept-Language"));
                } else if (ua.getUsertype() == 3) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_024.getCode(), request.getHeader("Accept-Language"));
                } else {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_025.getCode(), request.getHeader("Accept-Language"));
                }
            }
        }
        return null;
    }


    protected boolean checkWskhAccountRole(Systemmanager systemmanager, Long userId) {
        if (systemmanager.getReletype() == 1) {
            return true;
        }
        WskhUserinfo ws = iWskhUserinfoMapper.selectOne(new QueryWrapper<WskhUserinfo>().eq("USERID", userId));
        if (Objects.isNull(ws)) {
            return false;
        }
        //会员
        if (systemmanager.getReletype() == 2) {
            return systemmanager.getAreauserid().equals(ws.getMemberareaid());
        }
        //子机构
        if (systemmanager.getReletype() == 3) {
            return systemmanager.getAreauserid().equals(ws.getAreaid());
        }
        return false;
    }

    private Userinfo insertUserInfo(WskhUserinfo vo, WskhUserinfo wui, Systemmanager systemmanager) {
        Userinfo ui = new Userinfo();
        ui.setUserid(Long.valueOf(vo.getAreacode()));
        ui.setUserinfotype(wui.getUserinfotype());
        ui.setCustomername(wui.getCustomername());
        ui.setCardtypeid(wui.getCardtype());
        ui.setCardnum(wui.getCardnum());
        ui.setBiznature(wui.getBiznature());
        ui.setCompany(wui.getCompany());
        ui.setContactname(wui.getContactname());
        ui.setSex(wui.getSex());
        ui.setMobile(wui.getMobilephone());
        ui.setTelphone(wui.getTelphone());
        ui.setEmail(wui.getEmail());
        ui.setQq(wui.getQq());
        ui.setWechat(wui.getWechat());
        ui.setPostalcode(wui.getPostalcode());
        ui.setProvinceid(wui.getProvinceid());
        ui.setCityid(wui.getCityid());
        ui.setDistrictid(wui.getDistrictid());
        ui.setAddress(wui.getCardaddress());
        ui.setRemark(wui.getRemark());
        ui.setUserstatus(1);
        ui.setUsertype(2);
        ui.setOpenmode(1);
        ui.setCreatorid(systemmanager.getAutoid());
        ui.setCreatetime(new Date());
        ui.setLegalpersonname(wui.getLegalpersonname());
        ui.setCardbackphotourl(wui.getCardbackphotourl());
        ui.setCardfrontphotourl(wui.getCardfrontphotourl());
        ui.setLegalcardbackphotourl(wui.getLegalcardbackphotourl());
        ui.setLegalcardfrontphotourl(wui.getLegalcardfrontphotourl());
        ui.setAttachment1(wui.getAttachment1());
        ui.setAttachment2(wui.getAttachment2());
        if (StringUtils.isNotBlank(wui.getBankid())) {
            ui.setBankid(wui.getBankid());
        }
        ui.setBankname(wui.getBankname());
        ui.setBankaccount(wui.getBankaccount());
        ui.setBankcardfrontphotourl(wui.getBankcardfrontphotourl());
        ui.setLogincode(StringUtils.isNotBlank(wui.getLogincode()) ? wui.getLogincode() : vo.getSmlogincode().trim());
        iUserinfoMapper.insert(ui);
        return ui;
    }

    public void insertSystem(WskhUserinfo vo, WskhUserinfo wui, Systemmanager systemmanager) {
        Systemmanager sm = new Systemmanager();
        sm.setReletype(2);
        sm.setLogincode(vo.getSmlogincode().trim());
        sm.setUsername(vo.getLoginname() != null ? vo.getLoginname() : wui.getUsername());
        sm.setPassword(EncryptionUtils.encryptSHA(vo.getSmlogincode().trim() + vo.getSmpassword()));
        sm.setAreauserid(Long.valueOf(vo.getAreacode()));
        sm.setPwdexpdate(new Date());
        sm.setManagerstatus(1);
        sm.setLoginstatus(1);
        sm.setIsdefault(1);
        sm.setLoginfailnum(0);
        sm.setUploginid(systemmanager.getAutoid());
        sm.setModifytime(new Date());
        sm.setManagertype(1);
        iSystemmanagerMapper.insert(sm);

        Object l = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "002");
        if (l == null || !"2".equals(l.toString())) {
            Roleuser ur = new Roleuser();
            ur.setRoleid(1L);
            ur.setManagerid(sm.getAutoid());
            ur.setRoletype(3);
            iRoleuserMapper.insert(ur);
        }
    }

    private List<Taaccount> insertUserAccount(WskhUserinfo vo, WskhUserinfo wui, Systemmanager systemmanager) {
        List<Taaccount> taaccountList = new ArrayList<>();
        Useraccount ua = new Useraccount();
        ua.setUserid(Long.valueOf(vo.getAreacode()));
        ua.setUsertype(2);
        ua.setAccountname(wui.getUsername());
        ua.setParentuserid(systemmanager.getAreauserid());
        ua.setSubarealevelpath("," + vo.getAreacode() + ",");
        if (StringUtils.isNotBlank(wui.getReferral())) {
            ua.setRefereeuserid(Long.valueOf(wui.getReferral()));
        }
        ua.setMemberuserid(Long.valueOf(vo.getAreacode()));
        ua.setAccountstatus(4);
        ua.setCreatetime(new Date());
        ua.setCreatorid(systemmanager.getAutoid());
        ua.setModifytime(new Date());
        ua.setModifierid(systemmanager.getAutoid());
        ua.setHasauth(1);
        ua.setRefernum(vo.getAreacode());

        List<Enumdicitem> li = iEnumdicitemMapper.selectList(new QueryWrapper<Enumdicitem>()
                .eq("enumdiccode", "currency")
                .eq("enumitemstatus", 1));
        BankSystemconfig config = iBankSystemconfigMapper.selectOne(new QueryWrapper<BankSystemconfig>().eq("CONFIGID", SysConstants.BANK_CONFIG_ACTIVATION));
        int cu_num = li.size();

        // 取证件类型后6位
        String carnum = EncryptionUtils.decryptForAES(wui.getCardnum());
        String password;
        if (carnum.length() < 6) {
            password = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, SysConstants.SYSPARAM_CODE_DEFAULT_PWD);
        } else {
            password = carnum.substring(carnum.length() - 6);
        }
        for (int i = 0; i < cu_num; i++) {
            String manageid = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "001");
            Long accountno = Long.valueOf(manageid + CommonUtil.addZero(String.valueOf(idGeneratorUtils.getGeneratorID(Taaccount.class)), 9));
            Taaccount ac = new Taaccount();
            ac.setAccountid(accountno);
            ac.setUserid(ua.getUserid());
            ac.setPassword(EncryptionUtils.encryptSHA(password));
            ac.setIsreckonaccount(0);
            ac.setCurrencyid(li.get(i).getEnumitemname().intValue());
            //资金账号是否需要激活
            if (config != null && config.getValidstatus() == 1 && config.getConfigvalue().equals("1") && ac.getIsmain() == 1) {
                ac.setTradestatus(6);
            } else {
                //激活时间
                ac.setTradestatuschangetime(new Date());
            }
            ac.setRelateduserid(ua.getUserid());
            ac.setRelatedaccountstatus(1);
            iTaaccountMapper.insert(ac);
            taaccountList.add(ac);

            Userreckonaccount ura = new Userreckonaccount();
            ura.setUserid(ac.getUserid());
            ura.setCurrencyid(ac.getCurrencyid());
            ura.setReckonaccountid(ac.getAccountid());
            ura.setUpdatetime(new Date());
            ura.setDefaultaccounttype(1);
            iUserreckonaccountMapper.insert(ura);
            if (li.get(i).getEnumitemname().intValue() == 1) {
                ua.setReckonaccountid(ac.getAccountid());
            }
        }

        ua.setCreatetradedate(iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid", 0L)).getTradedate());
        iUseraccountMapper.insert(ua);
        return taaccountList;
    }

    private void encrypt(WskhUserinfo wskhUserinfo) {
        if (StringUtils.isNotBlank(wskhUserinfo.getCardnum())) {
            wskhUserinfo.setCardnum(EncryptionUtils.encryptByAES(wskhUserinfo.getCardnum()));
        }
        if (StringUtils.isNotBlank(wskhUserinfo.getMobilephone())) {
            wskhUserinfo.setMobilephone(EncryptionUtils.encryptByAES(wskhUserinfo.getMobilephone()));
        }
        if (StringUtils.isNotBlank(wskhUserinfo.getWechat())) {
            wskhUserinfo.setWechat(EncryptionUtils.encryptByAES(wskhUserinfo.getWechat()));
        }
        if (StringUtils.isNotBlank(wskhUserinfo.getEmail())) {
            wskhUserinfo.setEmail(EncryptionUtils.encryptByAES(wskhUserinfo.getEmail()));
        }
        if (StringUtils.isNotBlank(wskhUserinfo.getBankaccount())) {
            wskhUserinfo.setBankaccount(EncryptionUtils.encryptByAES(wskhUserinfo.getBankaccount()));
        }
        if (StringUtils.isNotBlank(wskhUserinfo.getQq())) {
            wskhUserinfo.setQq(EncryptionUtils.encryptByAES(wskhUserinfo.getQq()));
        }
        if (StringUtils.isNotBlank(wskhUserinfo.getTelphone())) {
            wskhUserinfo.setTelphone(EncryptionUtils.encryptByAES(wskhUserinfo.getTelphone()));
        }
    }

    private String generateReferNum() {
        //系统参数996 为2时，推荐码只有数字；
        String value = iCommonService.getSysparmById("996");
        if ("2".equals(value)) {
            return CommonUtil.getUuid2();
        }
        return CommonUtil.getUuid();
    }
}
