package com.muchinfo.mtp3century.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muchinfo.mtp.proto.*;
import com.muchinfo.mtp3century.exception.GlobalException;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IOrganService;
import com.muchinfo.mtp3century.service.ISendMsgService;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3common.enumtype.*;
import com.muchinfo.mtp3common.utils.*;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.vo.Calculator;
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.ProtoErrorCodes;
import com.muchinfo.mtp3pojos.vo.common.OrganSelectParam;
import com.muchinfo.mtp3pojos.vo.common.OrganSelectResult;
import com.muchinfo.mtp3pojos.vo.investor.*;
import com.muchinfo.mtp3pojos.vo.organ.*;
import com.muchinfo.mtp3pojos.vo.organ.AccountRiskConfigAddParam;
import com.muchinfo.mtp3pojos.vo.organ.AccountRiskConfigParam;
import com.muchinfo.mtp3pojos.vo.organ.AccountRiskConfigResult;
import com.muchinfo.mtp3pojos.vo.organ.AccountTradeConfigTreeVo;
import com.muchinfo.mtp3pojos.vo.organ.son.OrganAddSonOrganParam;
import com.muchinfo.mtp3pojos.vo.taaccount.TaAccountMarketVo;
import com.muchinfo.mtp3pojos.vo.taaccount.TaAccountQueryParam;
import com.muchinfo.mtp3pojos.vo.taaccount.TaAccountQueryResult;
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.*;

@Service
public class OrganServiceImpl implements IOrganService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private IBankBankinfoMapper iBankBankinfoMapper;
    @Resource
    private IUserinfoMapper iUserinfoMapper;
    @Resource
    private IBankAccountsignMapper iBankAccountsignMapper;
    @Resource
    private ISendMsgService iSendMsgService;
    @Resource
    private IDivisionMapper iDivisionMapper;
    @Resource
    private SystemmanagerServiceImpl systemmanagerService;
    @Resource
    private IWskhOpenaccountconfigMapper iWskhOpenaccountconfigMapper;
    @Resource
    private IDraftUseraccountNewMapper iDraftUseraccountNewMapper;
    @Resource
    private IArearoleMapper iArearoleMapper;
    @Resource
    private IDraftUserinfoMapper iDraftUserinfoMapper;
    @Resource
    private ITaaccountMapper iTaaccountMapper;
    @Resource
    private ILoginaccountMapper iLoginaccountMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private IEnumdicitemMapper iEnumdicitemMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private IUserreckonaccountMapper iUserreckonaccountMapper;
    @Resource
    private IRoleuserMapper iRoleuserMapper;
    @Resource
    private IQuoterMapper iQuoterMapper;
    @Resource
    private ISystemmanagerlogMapper iSystemmanagerlogMapper;
    @Resource
    private IArearoledivideconfigMapper iArearoledivideconfigMapper;
    @Resource
    private IMarketMapper iMarketMapper;
    @Resource
    private IWskhUserinfoMapper iWskhUserinfoMapper;
    @Resource
    private ICustomertypeareadetailMapper iCustomertypeareadetailMapper;
    @Resource
    private IArearolemarketmakerMapper iArearolemarketmakerMapper;

    @Resource
    private IArearolemarketMapper iArearolemarketMapper;
    @Resource
    private IGoodsMapper iGoodsMapper;
    @Resource
    private IWarehouseinfoMapper iWarehouseinfoMapper;
    @Resource
    private IMmrelation2Mapper iMmrelation2Mapper;
    @Resource
    private IScoretypeMapper iScoretypeMapper;
    @Resource
    private IHedgeaccountMapper iHedgeaccountMapper;
    @Resource
    private ITaaccountmarketMapper iTaaccountmarketMapper;
    @Resource
    private IMsExtendroleMapper iMsExtendroleMapper;
    @Resource
    private ILogintaaccountMapper iLogintaaccountMapper;
    @Resource
    private IUsermarkettradeconfigMapper iUsermarkettradeconfigMapper;
    @Resource
    private ISystemparamMapper iSystemparamMapper;
    @Resource
    private TradingAccountServiceImpl tradingAccountService;
    @Resource
    private IMembergoodslimitconfigMapper iMembergoodslimitconfigMapper;
    @Resource
    private IAccountriskconfigMapper iAccountriskconfigMapper;
    @Resource
    private IAccounttradeconfigMapper iAccounttradeconfigMapper;
    @Resource
    private IUsergroupdetailMapper iUsergroupdetailMapper;
    @Resource
    private ITradepositionMapper iTradepositionMapper;
    @Resource
    private IUserauthinfoMapper iUserauthinfoMapper;

    @Override
    public PageResult<UserAccountRspResult> queryByPage(UserAccountReqParam userInfoReqParam, HttpServletRequest request) {
        IPage<UserAccountRspResult> userAccountVos;
        IPage<UserAccountRspResult> page = new Page<>(userInfoReqParam.getPageNum(), userInfoReqParam.getPageSize());
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype().equals(2)) {
            userAccountVos = iUseraccountMapper.querySonOrganPage(page, userInfoReqParam);
        } else {
            userAccountVos = iUseraccountMapper.queryOrganPage(page, userInfoReqParam);
        }
        PageResult<UserAccountRspResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(userAccountVos.getPages());
        pageResult.setCurrent(userAccountVos.getCurrent());
        pageResult.setTotal(userAccountVos.getTotal());
        pageResult.setPageSize(userAccountVos.getSize());
        pageResult.setData(userAccountVos.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<UserAccountDetailResult> queryDetail(Long areaId, Integer role, HttpServletRequest request) {
        UserAccountDetailResult result = new UserAccountDetailResult();
        UserAccountRspResult userAccountVo = new UserAccountRspResult();
        Useraccount useraccount = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("USERID", areaId));
        BeanUtils.copyProperties(useraccount, userAccountVo);
        result.setRspResult(userAccountVo);

        result.setRefereeusername(iUseraccountMapper.selectOrganName(userAccountVo.getRefereeuserid()) != null ? iUseraccountMapper.selectOrganName(userAccountVo.getRefereeuserid()) : "");
        result.setBorkername(iUseraccountMapper.selectOrganName(userAccountVo.getBroker()));

        Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", areaId));
        if (ui.getBankid() != null) {
            BankBankinfo bi = iBankBankinfoMapper.selectOne(new QueryWrapper<BankBankinfo>().eq("bankid", ui.getBankid()));
            if (bi != null) {
                ui.setBankname(bi.getBankname());
            }
        }

        if (userAccountVo.getCreditquota() != null) {
            ui.setCreditquota(userAccountVo.getCreditquota());
        }

        if (StringUtils.isNotBlank(ui.getOtherurl())) {
            result.setOtherurl(Arrays.asList(ui.getOtherurl().split(",")));
        }
        result.setUserinfo(ui);

        Long did = ui.getDistrictid() != null ? ui.getDistrictid() :
                (ui.getCityid() != null ? ui.getCityid() : ui.getProvinceid());
        if (did != null) {
            Division division = iDivisionMapper.selectOne(new QueryWrapper<Division>().eq("autoid", did));
            if (division != null) {
                result.setDivision(division.getSeparablename().replaceAll(">", ""));
            }
        }
        if (userAccountVo.getModifystatus() != null && userAccountVo.getModifystatus() == 2) {
            DraftUseraccountNew uo = iDraftUseraccountNewMapper.selectOne(new QueryWrapper<DraftUseraccountNew>().eq("userid", areaId));
            DraftUserinfo dui = iDraftUserinfoMapper.selectOne(new QueryWrapper<DraftUserinfo>().eq("userid", areaId));
            if (uo.getRefereeuserid() != null) {
                result.setAfterrefereeusername(iUseraccountMapper.selectOrganName(uo.getRefereeuserid()));
            }
            if (uo.getBroker() != null) {
                result.setAfterborkername(iUseraccountMapper.selectOrganName(uo.getBroker()));
            }

            result.setDraftUseraccountNew(uo);
            result.setDraftUserinfo(dui);
        }

        //管理员账户信息
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("areauserid", areaId).eq("isdefault", 1));
        result.setUsers(user);

        //如果是经纪会员、会员子机构、经纪人，则查询网上开户地址
        Map<String, Object> map = new HashMap<>();
        if (null == role || role == SysEnums.OrganRole.broker.getCode().intValue()
                || userAccountVo.getUsertype() == 3 || userAccountVo.getUsertype() == 4) {
            WskhOpenaccountconfig config = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("configtype", 59));
            if (null != config && null != config.getConfigvalue()) {
                result.setOpenUrl(config.getConfigvalue());
            }
        }
        //移动端开户地址
        WskhOpenaccountconfig config1 = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("configtype", 60));
        if (null != config1 && null != config1.getConfigvalue()) {
            result.setMobileUrl(config1.getConfigvalue());
        }

        //微信开户地址
        WskhOpenaccountconfig config2 = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("configtype", 65));
        if (null != config2 && null != config2.getConfigvalue()) {
            result.setWeixinUrl(config2.getConfigvalue());
        }

        //三方开户地址
        WskhOpenaccountconfig config3 = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("configtype", 66));
        if (null != config3 && null != config3.getConfigvalue()) {
            result.setSanfangUrl(config3.getConfigvalue());
        }

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

    @Override
    public PageResult<TaAccountQueryResult> organtaaccount(TaAccountQueryParam param, HttpServletRequest request) {
        IPage<TaAccountQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<TaAccountQueryResult> userAccountVos = iTaaccountMapper.queryTaAccountPage(page, param);
        //设置风险率
        getRiskFromRedis(userAccountVos.getRecords());
        PageResult<TaAccountQueryResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(userAccountVos.getPages());
        pageResult.setCurrent(userAccountVos.getCurrent());
        pageResult.setTotal(userAccountVos.getTotal());
        pageResult.setPageSize(userAccountVos.getSize());
        pageResult.setData(userAccountVos.getRecords());
        return pageResult;
    }

    @Override
    public PageResult<UserAccountSignlogResult> querySignlog(Long accountId, Integer querytype, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        IPage<UserAccountSignlogResult> page = new Page<>(pageNum, pageSize);
        IPage<UserAccountSignlogResult> resultIPage;
        if (querytype == 0) {
            resultIPage = iBankAccountsignMapper.query(page, accountId);
        } else {
            resultIPage = iBankAccountsignMapper.queryhis(page, accountId);
        }
        PageResult<UserAccountSignlogResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult resetPwd(Long accountid, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkTaAccountReport(systemmanager, accountid)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        String lPwd = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, "047");
        Taaccount la = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("accountid", accountid));
        if (la != null) {
            la.setPassword(EncryptionUtils.encryptSHA(lPwd));
            iTaaccountMapper.update(la, new QueryWrapper<Taaccount>().eq("accountid", accountid));
            systemmanagerService.writeOperateLog(SysConstants.PART_INVESTOR_MANAGE, "重置资金账户id=" + accountid + "的密码", systemmanager, null, null, null);
            sendMsg(la, 2);

            Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", la.getUserid()));
            if (StringUtils.isNotBlank(ui.getMobile())) {
                List<String> strs = new ArrayList<String>();
                strs.add(ui.getCustomername());
                strs.add(accountid.toString());
                strs.add("资金");
                strs.add(lPwd);
                //尊敬的{accountname},根据您的申请,您的交易账号{accountid}{type}密码已经重置为:{password};请及时登录系统修改您的相关密码,并注意妥善保管。
                iSendMsgService.sendSMSConnetion(23, EncryptionUtils.decryptForAES(ui.getMobile()), strs);
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<UserAccountOrgan2UserResult> queryorgan2User(Long userid, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        IPage<UserAccountOrgan2UserResult> page = new Page<>(pageNum, pageSize);
        IPage<UserAccountOrgan2UserResult> userAccountVos = iSystemmanagerMapper.getAllUserByOrgan2(page, userid);
        PageResult<UserAccountOrgan2UserResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(userAccountVos.getPages());
        pageResult.setCurrent(userAccountVos.getCurrent());
        pageResult.setTotal(userAccountVos.getTotal());
        pageResult.setPageSize(userAccountVos.getSize());
        pageResult.setData(userAccountVos.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult updateorgan2User(Long userid, Integer status, HttpServletRequest request) {
        iSystemmanagerMapper.updateorgan2User(userid, status);

        String lp = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, SysConstants.SYSPARAM_CODE_STOPORREST);
        if ("1".equals(lp.trim())) {
            if (status == 2) {
                setReadOnly(userid);
            } else if (status == 1) {
                setRoleBack(userid);
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult updatestatusbyautoid(Long autoid, Integer status, HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", autoid));
        if (user != null) {
            user.setManagerstatus(status);
            user.setModifytime(new Date());
            iSystemmanagerMapper.updateById(user);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

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

    @Override
    public AjaxResult selfsupportresetPwd(Long loginid, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkLoginAccountRole(systemmanager, loginid)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        String systemParam = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, "046");
        Loginaccount la = iLoginaccountMapper.selectOne(new QueryWrapper<Loginaccount>().eq("loginid", loginid));
        if (la != null) {
            la.setHasupdatedpwd(0);
            la.setPassword(EncryptionUtils.encryptSHA(la.getLoginid() + systemParam));
            la.setModifierid(systemmanager.getAutoid());
            la.setModifytime(new Date());

            iLoginaccountMapper.update(la, new QueryWrapper<Loginaccount>().eq("loginid", la.getLoginid()));

            Systemmanagerlog log = new Systemmanagerlog();
            log.setUserid(systemmanager.getAutoid());
            log.setReletype(systemmanager.getReletype());
            log.setLogincode(systemmanager.getLogincode());
            log.setUsername(systemmanager.getUsername());
            log.setParentuserid(systemmanager.getAreauserid());
            log.setOperatetime(new Date());
            log.setContent("重置交易商登录账户(loginid=" + la.getLoginid() + ")密码成功");
            log.setIp(systemmanager.getLoginip());
            log.setOldvalue("");
            log.setNewvalue("");
            iSystemmanagerlogMapper.insert(log);

            Set<Long> logins = new HashSet<>();
            logins.add(la.getLoginid());
            iSendMsgService.sendLoginMsg(logins, 2, 0);
        }

        //重置密码短信消息
        Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", la.getUserid()));
        if (StringUtils.isNotBlank(ui.getMobile())) {
            List<String> strs = new ArrayList<String>();
            strs.add(ui.getCustomername());
            strs.add(loginid.toString());
            strs.add("登录");
            strs.add(systemParam);
            //尊敬的{accountname}，根据您的申请，您的交易账号{accountid}{type}密码已经重置为:{password};请及时登录系统修改您的相关密码,并注意妥善保管。
            iSendMsgService.sendSMSConnetion(23, EncryptionUtils.decryptForAES(ui.getMobile()), strs);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult lockAccount(Long loginid, Integer status, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkLoginAccountRole(systemmanager, loginid)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        Loginaccount la = iLoginaccountMapper.selectOne(new QueryWrapper<Loginaccount>().eq("loginid", loginid));
        if (la != null) {
            // 发送消息 解锁 ,回应
            Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_account);

            SystemMI1.LoginStatusOperReq.Builder builder = SystemMI1.LoginStatusOperReq.newBuilder();
            Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
            hd.setUUID(uuid.toString());
            hd.setClientTime(System.currentTimeMillis());
            hd.setResponseTopic(SysConstants.RabbitUserNtfKey);
            hd.setFunCode(FunCodeConstants.FunCode_LoginStatusOperReq);
            builder.setHeader(hd);
            builder.setLoginID(loginid);
            builder.setLoginStatus(status);
            builder.setOperatorID(systemmanager.getAutoid().intValue());

            log.debug("手工锁定：{}", builder.build().toString());
            byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(),
                    FunCodeConstants.FunCode_LoginStatusOperReq);

            Calculator ca = new Calculator(uuid);
            SerialNumberUtils.lockMap.put(uuid, ca);

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

            if (status == 1) {
                systemmanagerService.writeOperateLog(SysConstants.PART_INVESTOR_MANAGE, String.format("解锁登录账户(loginid=%s)成功", loginid), systemmanager, null, null, null);
            } else if (status == 2) {
                systemmanagerService.writeOperateLog(SysConstants.PART_INVESTOR_MANAGE, String.format("锁定登录账户(loginid=%s)成功", loginid), systemmanager, null, null, null);
            }

            synchronized (ca) {
                try {
                    ca.wait(10000);
                    Object rsp = ca.obj;
                    if (rsp != null) {
                        SystemMI1.LoginStatusOperRsp rsp_ = (SystemMI1.LoginStatusOperRsp) rsp;
                        if (rsp_.getRetCode() == 0) {
                            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
                        } else {
                            return AjaxResult.error(Constants.Error_Code_Design, ProtoErrorCodes.resultMsg(rsp_.getRetCode()), "", null);
                        }
                    } else {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM006.getCode(), request.getHeader("Accept-Language"));
                    }
                } catch (InterruptedException e) {
                    log.error("rabbitmq收取返回信息" + FunCodeConstants.FunCode_LoginStatusOperReq + "失败，失败原因" + e.getMessage());
                } finally {
                    SerialNumberUtils.lockMap.remove(uuid);
                }
            }
        }
        return null;
    }

    @Override
    public PageResult<UserAccountRspResult> queryrole(UserAccountRoleParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getRoleid() == 7) {
            //如果有营销中心角色
            if (systemmanager.getReletype() != 1 && ("," + param.getOrgztypes() + ",").contains(",3,")) {
                param.setParentuserid(systemmanager.getAreauserid());
            }
        } else if (param.getRoleid() == 69) {
            param.setRoleid(6);
        }

        IPage<UserAccountRspResult> userAccountVos;
        IPage<UserAccountRspResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        if (systemmanager.getReletype().equals(4)) {
            userAccountVos = iTaaccountMapper.queryWarehouseOrganPage(page, param);
        } else {
            userAccountVos = iTaaccountMapper.queryRoleOrganPage(page, param);
        }
        PageResult<UserAccountRspResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(userAccountVos.getPages());
        pageResult.setCurrent(userAccountVos.getCurrent());
        pageResult.setTotal(userAccountVos.getTotal());
        pageResult.setPageSize(userAccountVos.getSize());
        pageResult.setData(userAccountVos.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<UserAccountRoleDetailResult> queryroleDetail(String rolename, Long userid, HttpServletRequest request) {
        UserAccountRoleDetailResult result = new UserAccountRoleDetailResult();
        Integer role = SysEnums.OrganRole.valueOf(rolename).getCode();
        UserAccountRspResult userAccountVo = new UserAccountRspResult();
        Useraccount useraccount = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("USERID", userid));
        BeanUtils.copyProperties(useraccount, userAccountVo);
        result.setOrgan(userAccountVo);
        result.setRoleid(role);

        //管理员账户信息
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("areauserid", userid).eq("isdefault", 1));
        result.setUsers(user);

        //如果是经纪会员、会员子机构、经纪人，则查询网上开户地址
        if (null == role || role == SysEnums.OrganRole.broker.getCode().intValue()
                || userAccountVo.getUsertype() == 3 || userAccountVo.getUsertype() == 4) {
            WskhOpenaccountconfig config = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("configtype", 59));
            if (null != config && null != config.getConfigvalue()) {
                result.setOpenUrl(config.getConfigvalue());
            }
        }
        //移动端开户地址
        WskhOpenaccountconfig config1 = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("configtype", 60));
        if (null != config1 && null != config1.getConfigvalue()) {
            result.setMobileUrl(config1.getConfigvalue());
        }

        //三方开户地址
        WskhOpenaccountconfig config3 = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("configtype", 66));
        if (null != config3 && null != config3.getConfigvalue()) {
            result.setSanfangUrl(config3.getConfigvalue());
        }

        if (role >= SysEnums.OrganRole.operate.getCode() && role <= SysEnums.OrganRole.tpart.getCode()) {
            List<Arearoledivideconfig> list = iArearoledivideconfigMapper.selectList(new QueryWrapper<Arearoledivideconfig>()
                    .eq("userid", userid)
                    .eq("roletype", role));
            List<Arearoledivideconfig> olist = new ArrayList<>();
            List<Arearoledivideconfig> plist = new ArrayList<>();
            for (Arearoledivideconfig arearoledivideconfig : list) {
                if (arearoledivideconfig.getGoodsid() != 0) {
                    plist.add(arearoledivideconfig);
                } else {
                    olist.add(arearoledivideconfig);
                }
            }
            result.setFee(olist);
            result.setPfee(plist);
        }

        if (role == SysEnums.OrganRole.operate.getCode().intValue()) {
            //运营机构 市场
            List<Market> list = iMarketMapper.selectList(new QueryWrapper<Market>().eq("exchareaid", userid));
            result.setMarkets(list);
        } else if (role == SysEnums.OrganRole.warehouse.getCode().intValue()) {
            //仓库机构 仓库
            List<Warehouseinfo> list = iWarehouseinfoMapper.selectList(new QueryWrapper<Warehouseinfo>().eq("areauserid", userid));
            result.setWarehouse(list);
        } else if (role == SysEnums.OrganRole.selfsupport.getCode().intValue()
                || role == SysEnums.OrganRole.broker.getCode().intValue()
                || role == SysEnums.OrganRole.seller.getCode().intValue()) {
            //会员  已选市场
            List<Integer> roletype = new ArrayList<Integer>();

            if (role == SysEnums.OrganRole.seller.getCode().intValue()) {
                roletype.add(6);
            } else {
                roletype.add(role);
            }
            List<Market> markets = iMarketMapper.getMarketsNameByUseridAndrole(userid, roletype,null);
            result.setMarkets(markets);
        } else if (role == SysEnums.OrganRole.industry.getCode().intValue()) {
            String sm = iCommonService.getSysparmById(SysConstants.SYSPAMA_CODE_NINESERVENNINE);
            if ("1".equals(sm)) {
                result.setIshsby(1);
                //会员   已选市场
                List<Integer> roletype = new ArrayList<Integer>();
                roletype.add(6);
                List<Market> markets = iMarketMapper.getMarketsNameByUseridAndrole(userid, roletype,null);
                result.setMarkets(markets);
            }
        } else if (role == SysEnums.OrganRole.marketer.getCode().intValue()) {
            //做市
            Customertypeareadetail ca = iCustomertypeareadetailMapper.selectOne(new QueryWrapper<Customertypeareadetail>()
                    .eq("userid", userid)
                    .eq("arearoleid", role));
            result.setCustomertype(ca);
        }

        if (role <= 5) {
            String divide = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, SysConstants.SYSPARAM_CODE_DIVIDE);
            result.setDividetype(Integer.valueOf(divide));
        } else if (role == 17) {
            //加载物流地址
            Arearole a = iArearoleMapper.selectOne(new QueryWrapper<Arearole>().eq("userid", userid)
                    .eq("roletype", role));
            result.setTransurl(a);
        } else if (role == 18 || role == 19) {
            List<Arearolemarketmaker> mm = iArearolemarketmakerMapper.selectList(new QueryWrapper<Arearolemarketmaker>()
                    .eq("areauserid", userid)
                    .eq("roletype", role));
            List<Long> set = new ArrayList<>(mm.size());
            mm.forEach(p -> {
                set.add(p.getMmuserid());
            });

            List<Useraccount> lis = iUseraccountMapper.selectList(new QueryWrapper<Useraccount>().eq("userid", set));
            result.setOrgans(lis);

        } else if (role == 8) {
            List<Userreckonaccount> list = iUseraccountMapper.queryUra(userid);
            result.setRoleNight(list);
        }

        if (role == 2) {
            // 运营机构功能变更 2024-01-15
            //查询本用户的交易市场
            result.setOperatemarkets(iMarketMapper.queryAreaGoodsMarkets(userid));
            //查询本用户的商品权限
            result.setOperategoodsinfo(iGoodsMapper.queryAreaGoodsConfig(userid));
        }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult del(Long areaid, Integer role, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (role == SysEnums.OrganRole.marketing.getCode().intValue()) {
            //营销中心
            List<Useraccount> list = iUseraccountMapper.selectList(new QueryWrapper<Useraccount>()
                    .eq("parentuserid", areaid)
                    .eq("accountstatus", 4)
                    .eq("usertype", 2));
            if (CollectionUtils.isNotEmpty(list)) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_026.getCode(), request.getHeader("Accept-Language"));
            }
        } else if (role == SysEnums.OrganRole.warehouse.getCode().intValue()) {
            //仓库
            List<Warehouseinfo> list = iWarehouseinfoMapper.selectList(new QueryWrapper<Warehouseinfo>()
                    .eq("areauserid", areaid)
                    .eq("warehousestatus", 1));
            if (CollectionUtils.isNotEmpty(list)) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_027.getCode(), request.getHeader("Accept-Language"));
            }
        } else if (role == SysEnums.OrganRole.marketer.getCode().intValue()) {
            //做市
            Arearole list = iArearoleMapper.selectOne(new QueryWrapper<Arearole>().eq("userid", areaid).eq("roletype", 8));
            Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("accountid", list.getTradeaccountid()));
            if (ta.getSignstatus() == 2) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_028.getCode(), request.getHeader("Accept-Language"));
            }
            iUserreckonaccountMapper.delete(new QueryWrapper<Userreckonaccount>().eq("userid", areaid).eq("defaultaccounttype", 2));

            //判断报价商
            List<Quoter> qu = iQuoterMapper.selectList(new QueryWrapper<Quoter>().eq("defaultmakerid", areaid).eq("quoterstatus", 1));
            if (CollectionUtils.isNotEmpty(qu)) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_029.getCode(), request.getHeader("Accept-Language"));
            }

            //二级对手关系
            List<Mmrelation2> mmList = iMmrelation2Mapper.selectList(new QueryWrapper<Mmrelation2>().eq("memberuserid", areaid));
            if (CollectionUtils.isNotEmpty(mmList)) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_030.getCode(), request.getHeader("Accept-Language"));
            }

            List<Arearolemarketmaker> l = iArearolemarketmakerMapper.selectList(new QueryWrapper<Arearolemarketmaker>()
                    .eq("mmuserid", areaid)
                    .eq("roletype", 19));
            if (CollectionUtils.isNotEmpty(l)) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_031.getCode(), request.getHeader("Accept-Language"));
            }
        } else if (role == SysEnums.OrganRole.broker.getCode().intValue()) {
            //经济;
            List<Useraccount> list = iUseraccountMapper.selectList(new QueryWrapper<Useraccount>()
                    .eq("parentuserid", areaid)
                    .eq("accountstatus", 4)
                    .in("usertype", 3, 4));
            if (CollectionUtils.isNotEmpty(list)) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language"));
            }

            List<Useraccount> list2 = iUseraccountMapper.selectList(new QueryWrapper<Useraccount>()
                    .eq("parentuserid", areaid)
                    .eq("accountstatus", 4)
                    .eq("usertype", 5));
            if (CollectionUtils.isNotEmpty(list2)) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language"));
            }
        } else if (role == SysEnums.OrganRole.integral.getCode().intValue()) {
            Scoretype st = iScoretypeMapper.selectOne(new QueryWrapper<Scoretype>().eq("scoreUserId", areaid));
            if (st != null) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_032.getCode(), request.getHeader("Accept-Language"));
            }
        } else if (role == SysEnums.OrganRole.quoterorgan.getCode().intValue()) {
            List<Hedgeaccount> l = iHedgeaccountMapper.selectList(new QueryWrapper<Hedgeaccount>().eq("quoteruserid", areaid));
            if (CollectionUtils.isNotEmpty(l)) {
                throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_033.getCode(), request.getHeader("Accept-Language"));
            }
        }
        /****************数据校验结束*********开始删除数据*********************************/
        String sysp = iCommonService.getSysparmById(SysConstants.SYSPAMA_CODE_NINESERVENNINE);
        //删除市场
        if (role == SysEnums.OrganRole.selfsupport.getCode().intValue()
                || role == SysEnums.OrganRole.broker.getCode().intValue()) {
            //市场
            iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", areaid).eq("roletype", role));

            Useraccount uc = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", areaid));
            iTaaccountmarketMapper.delete(new QueryWrapper<Taaccountmarket>().eq("accountid", uc.getReckonaccountid()));

            //Ms_ExtendRole
            iMsExtendroleMapper.delete(new QueryWrapper<MsExtendrole>().eq("areauserid", areaid).eq("roletypeid", 4L));

            //自营会员，删除资金市场权限
            if (role == SysEnums.OrganRole.selfsupport.getCode().intValue()) {
                Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("userid", areaid).eq("ismain", 1));
                iTaaccountmarketMapper.delete(new QueryWrapper<Taaccountmarket>().eq("accountid", ta.getAccountid()));
            }

            List<Integer> roletype = new ArrayList<>();
            roletype.add(role);
            if ("1".equals(sysp)) {
                roletype.add(9);
            }
            iArearoleMapper.delete(new QueryWrapper<Arearole>().eq("userid", areaid).in("roletype", roletype));
            iArearoledivideconfigMapper.delete(new QueryWrapper<Arearoledivideconfig>().eq("userid", areaid).in("roletype", roletype));

            Systemmanager admin = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("areauserid", areaid).eq("isdefault", 1));
            if (admin != null) {
                List<Long> roleids = new ArrayList<>();
                roleids.add(Long.valueOf(role));
                if ("1".equals(sysp)) {
                    roleids.add(9L);
                }
                iRoleuserMapper.delete(new QueryWrapper<Roleuser>()
                        .in("roleid", roleids)
                        .eq("roletype", 3)
                        .eq("managerid", admin.getAutoid()));
            }

            // 更新parentuserid为平台
            Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", areaid));
            if (ua != null) {
                ua.setParentuserid(1L);
                iUseraccountMapper.update(ua, new QueryWrapper<Useraccount>().eq("userid", ua.getUserid()));
            }

            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
        } else if (role == SysEnums.OrganRole.industry.getCode().intValue()) {
            if ("1".equals(sysp)) {
                //市场
                iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", areaid).eq("roletype", 6));

                List<Integer> roletype = new ArrayList<>();
                roletype.add(6);
                roletype.add(9);
                iArearoleMapper.delete(new QueryWrapper<Arearole>().eq("userid", areaid).in("roletype", roletype));
                iArearoledivideconfigMapper.delete(new QueryWrapper<Arearoledivideconfig>().eq("userid", areaid).in("roletype", roletype));

                Systemmanager admin = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("areauserid", areaid).eq("isdefault", 1));
                if (admin != null) {
                    iRoleuserMapper.delete(new QueryWrapper<Roleuser>()
                            .in("roleid", roletype)
                            .eq("roletype", 3)
                            .eq("managerid", admin.getAutoid()));
                }
                // 更新parentuserid为平台
                Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", areaid));
                iTaaccountmarketMapper.delete(new QueryWrapper<Taaccountmarket>().eq("accountid", ua.getReckonaccountid()));

                return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
            }
        } else if (role == SysEnums.OrganRole.marketer.getCode().intValue()) {
            //做市 删除客户类别
            iCustomertypeareadetailMapper.delete(new QueryWrapper<Customertypeareadetail>().eq("arearoleid", 8).eq("userid", areaid));
            iUserreckonaccountMapper.delete(new QueryWrapper<Userreckonaccount>().eq("userid", areaid).eq("defaultaccounttype", 2));

            Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("userid", areaid));
            ta.setIsmarketaccount(0);
            iTaaccountMapper.update(ta, new QueryWrapper<Taaccount>().eq("userid", areaid));
        } else if (role == SysEnums.OrganRole.quoterorgan.getCode().intValue()
                || role == SysEnums.OrganRole.outoption.getCode().intValue()) {

            iArearolemarketmakerMapper.delete(new QueryWrapper<Arearolemarketmaker>().eq("areauserid", areaid).eq("roletype", role));
        } else if (role == SysEnums.OrganRole.seller.getCode().intValue()) {
            iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", areaid).eq("roletype", 6));

            Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", areaid));
            iTaaccountmarketMapper.delete(new QueryWrapper<Taaccountmarket>().eq("accountid", ua.getReckonaccountid()));

            // 6 9 两个角色
            List<Integer> rs = new ArrayList<>();
            rs.add(6);
            rs.add(9);
            iArearoleMapper.delete(new QueryWrapper<Arearole>()
                    .eq("userid", areaid)
                    .in("roletype", rs));
            iArearoledivideconfigMapper.delete(new QueryWrapper<Arearoledivideconfig>()
                    .eq("userid", areaid)
                    .in("roletype", rs));

            Systemmanager admin = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("areauserid", areaid).eq("isdefault", 1));
            if (admin != null) {
                iRoleuserMapper.delete(new QueryWrapper<Roleuser>()
                        .in("roleid", rs)
                        .eq("roletype", 3)
                        .eq("managerid", admin.getAutoid()));
            }

            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
        } else if (role == SysEnums.OrganRole.ordinarymember.getCode().intValue() || role == SysEnums.OrganRole.coremember.getCode().intValue()) {
            //市场
            iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", areaid).eq("roletype", 6));

            Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("userid", areaid));
            iTaaccountmarketMapper.delete(new QueryWrapper<Taaccountmarket>().eq("accountid", ta.getAccountid()));

            List<Integer> roletypeArrTemp = new ArrayList<>();
            roletypeArrTemp.add(SysEnums.OrganRole.ordinarymember.getCode());
            roletypeArrTemp.add(SysEnums.OrganRole.coremember.getCode());
            if (iArearoleMapper.selectCount(new QueryWrapper<Arearole>().eq("userid", areaid).in("roletype", roletypeArrTemp)) > 1) {
                iArearoleMapper.delete(new QueryWrapper<Arearole>().eq("userid", areaid).eq("roletype", role));
            } else {
                List<Integer> roletypeArr = new ArrayList<>();
                roletypeArr.add(4);
                roletypeArr.add(6);
                roletypeArr.add(9);
                roletypeArr.add(role);
                iArearoleMapper.delete(new QueryWrapper<Arearole>().eq("userid", areaid).eq("roletype", roletypeArr));
            }

            iLoginaccountMapper.delete(new QueryWrapper<Loginaccount>().eq("userid", areaid));
            iLogintaaccountMapper.delete(new QueryWrapper<Logintaaccount>().eq("accountid", ta.getAccountid()));

            Systemmanager admin = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("areauserid", areaid).eq("isdefault", 1));
            if (admin != null) {
                List<Integer> roleids = new ArrayList<>();
                if (iRoleuserMapper.selectCount(new QueryWrapper<Roleuser>().eq("managerid", admin.getAutoid())
                        .eq("roletype", 3)
                        .in("roleid", roletypeArrTemp)) <= 1) {
                    roleids.add(4);
                    roleids.add(6);
                    roleids.add(9);
                }
                roleids.add(role);
                iRoleuserMapper.delete(new QueryWrapper<Roleuser>().eq("roletype", 3).in("roleid", roleids));
            }

            iUsermarkettradeconfigMapper.delete(new QueryWrapper<Usermarkettradeconfig>().eq("userid", areaid));
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
        }

        iArearoleMapper.delete(new QueryWrapper<Arearole>().eq("userid", areaid).eq("roletype", role));
        iArearoledivideconfigMapper.delete(new QueryWrapper<Arearoledivideconfig>()
                .eq("userid", areaid)
                .eq("roletype", role));

        if (role == SysEnums.OrganRole.quoterorgan.getCode().intValue()
                || role == SysEnums.OrganRole.outoption.getCode().intValue()) {
            iArearolemarketmakerMapper.delete(new QueryWrapper<Arearolemarketmaker>().eq("areauserid", areaid).eq("roletype", role));
        }
        if (role != SysEnums.OrganRole.quoterorgan.getCode().intValue()) {
            Systemmanager admin = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("areauserid", areaid).eq("isdefault", 1));
            if (admin != null) {
                iRoleuserMapper.delete(new QueryWrapper<Roleuser>()
                        .eq("managerid", admin.getAutoid())
                        .eq("roleid", role)
                        .eq("roletype", 3));
            }
        }

        // 删除运营机构商品权限配置 2024-01-15
        if (role == SysEnums.OrganRole.operate.getCode().intValue()) {
            iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", areaid));
        }

        List<Loginaccount> list = iLoginaccountMapper.selectList(new QueryWrapper<Loginaccount>()
                .eq("userid", areaid)
                .eq("loginusertype", 2));
        List<Long> loginids = new ArrayList<>();
        for (Loginaccount tmp : list) {
            if (!tmp.getLoginstatus().equals(3)) {
                tmp.setLoginstatus(3);
                tmp.setModifytime(new Date());
                tmp.setModifierid(systemmanager.getAutoid());
                iLoginaccountMapper.update(tmp, new QueryWrapper<Loginaccount>().eq("loginid", tmp.getLoginid()));
                loginids.add(tmp.getLoginid());
            }
        }

        if (CollectionUtils.isNotEmpty(loginids)) {
            try {
                Set<Long> set_msg = new HashSet<>(loginids);
                iSendMsgService.sendLoginMsg(set_msg, 1, 0);
            } catch (Exception e) {
                log.error("机构注销发送失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            }
        }

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

    @Override
    public AjaxResult<OrganInitAddResult> initAdd(String role, HttpServletRequest request) {
        OrganInitAddResult result = new OrganInitAddResult();
        String l = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "002");
        if (!"1".equals(l)) {
            result.setAllrole(1);
        }
        Integer r = SysEnums.OrganRole.valueOf(role).getCode();
        result.setRoleid(r);
        result.setRolename(role);
        if (r <= 5) {
            if (r == 2) {
                // 运营机构功能变更 2024-01-15
                //运营机构为空的有效交易类市场
                //查询可选的交易市场
                result.setMarkets(iArearoleMapper.queryMarketsForOperate());
                //查询可选的商品
                result.setGoodsinfo(iArearoleMapper.queryGoodsAndMarketInfo());
            }

            //分润方式
            String devidetype = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM,
                    SysConstants.SYSPARAM_CODE_DIVIDE);
            if (devidetype != null) {
                result.setDevidetype(devidetype);
            }
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
        } else {
            if (r == 6 || r == 7 || r == 69) {
                //市场
                List<Market> list = iMarketMapper.selectList(new QueryWrapper<Market>()
                        .eq("marketStatus", SysEnums.EnumMarketStatus.NORMAL.getType())
                        .eq("markettype", 2));

                result.setMarkets(list);
            } else if (r == 18 || r == 19) {
                if (r == 18) {
                    result.setAllrole(null);
                }
                //做市会员
                OrganSelectParam vo = new OrganSelectParam();
                vo.setUsertype("2");
                vo.setRoles("8");
                List<OrganSelectResult> list = iUseraccountMapper.queryOrganSelect(vo);
                result.setOrgans(list);
            } else if (r == 8) {
                List<Enumdicitem> ei = iEnumdicitemMapper.selectList(new QueryWrapper<Enumdicitem>().eq("enumdiccode", "currency"));
                result.setEnumDicItems(ei);
            } else if (r == 9) {
                String sm = iCommonService.getSysparmById(SysConstants.SYSPAMA_CODE_NINESERVENNINE);
                String isTHJ = iCommonService.getSysparmById("994");
                if ("1".equals(isTHJ)) {
                    //THJ 项目不配置市场权限
                } else {
                    if ("1".equals(sm)) {
                        result.setIshsby(1);
                        //市场
                        Map<String, Object> properties = new HashMap<String, Object>();
                        properties.put("marketStatus", SysEnums.EnumMarketStatus.NORMAL.getType());
                        properties.put("markettype", 2);
                        List<Market> list = iMarketMapper.selectList(new QueryWrapper<Market>()
                                .eq("marketStatus", SysEnums.EnumMarketStatus.NORMAL.getType())
                                .eq("markettype", 2));
                        result.setMarkets(list);
                    }
                }
            }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult roleadd(OrganRoleModifyParam vo, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (vo.getParentuserid() != null && vo.getRoleid().equals(7) && vo.getUserid().equals(vo.getParentuserid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_034.getCode(), request.getHeader("Accept-Language"));
        }

        if (vo.getType() == 1) {//新增
            if (vo.getRoleid() <= 5) {
                addAreaRoleModifyFee(vo, systemmanager, request);
            } else {
                addAreaRoleModifyMember(vo, systemmanager);
            }
        } else {//修改
            if (vo.getRoleid() <= 5) {
                editAreaRoleModifyFee(vo, systemmanager, request);
            } else {
                editARoleModifyMember(vo, systemmanager);
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

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

    @Override
    public AjaxResult addlimit(MemberGoodsAddParam vo, HttpServletRequest request) {
        Membergoodslimitconfig config = iMembergoodslimitconfigMapper.selectOne(new QueryWrapper<Membergoodslimitconfig>()
                .eq("userid", vo.getUserid())
                .eq("roletype", vo.getRoletype())
                .eq("goodsid", vo.getGoodsid()));
        if (config == null) {
            // 新增
            config = new Membergoodslimitconfig();
            config.setUserid(vo.getUserid());
            config.setGoodsid(vo.getGoodsid());
            config.setRoletype(vo.getRoletype());
            config.setUpdatetime(new Date());
            config.setIsnodisplay(vo.getIsnodisplay());
            config.setIscannotbuy(vo.getIscannotbuy());
            config.setIscannotsell(vo.getIscannotsell());
            iMembergoodslimitconfigMapper.insert(config);
        } else {
            config.setUpdatetime(new Date());
            config.setIsnodisplay(vo.getIsnodisplay());
            config.setIscannotbuy(vo.getIscannotbuy());
            config.setIscannotsell(vo.getIscannotsell());
            iMembergoodslimitconfigMapper.updateById(config);
        }

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

    @Override
    public AjaxResult dellimit(Integer autoid, HttpServletRequest request) {
        iMembergoodslimitconfigMapper.deleteById(autoid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<AccountRiskConfigResult> accountriskconfig(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());
        }
        param.setMember(1);
        IPage<AccountRiskConfigResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<AccountRiskConfigResult> userAccountVos = iWskhUserinfoMapper.accountriskconfig(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(userAccountVos.getPages());
        pageResult.setCurrent(userAccountVos.getCurrent());
        pageResult.setTotal(userAccountVos.getTotal());
        pageResult.setPageSize(userAccountVos.getSize());
        pageResult.setData(userAccountVos.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<Accountriskconfig> accountriskconfigview(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 addaccountriskconfig(AccountRiskConfigAddParam vo, HttpServletRequest request) {
        Accountriskconfig config = new Accountriskconfig();
        config.setAccountid(vo.getAccountid());
        config.setUserid(vo.getUserid());
        config.setCustomertype(vo.getCustomertype());
        iAccountriskconfigMapper.insert(config);

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

    @Override
    public AjaxResult editaccountriskconfig(AccountRiskConfigAddParam vo, HttpServletRequest request) {
        Accountriskconfig config = iAccountriskconfigMapper.selectOne(new QueryWrapper<Accountriskconfig>().eq("accountid", vo.getAccountid()));
        config.setAccountid(vo.getAccountid());
        config.setUserid(vo.getUserid());
        config.setCustomertype(vo.getCustomertype());
        iAccountriskconfigMapper.update(config, new QueryWrapper<Accountriskconfig>().eq("accountid", vo.getAccountid()));

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

    @Override
    public AjaxResult delaccountriskconfig(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 editorgan(OrganAddSonOrganParam param, HttpServletRequest request) {
        // #6597 管理端】不管是后台注册还是客户端注册，身份证号填写的那一栏，如果涉及到输入字母X，需要固定只能输入大写字母
        if (param != null && StringUtils.isNotBlank(param.getCardnum())) {
            param.setCardnum(param.getCardnum().toUpperCase());
        }

        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

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

        //当为特许经销商时，因为新增特许经销商的时候，默认加了一个名称一样的报价商，现在修改特许经销商名称时，报价商名称也一起修改
        if (param.getUsertype() == 2) {
            Long num = iArearoleMapper.selectCount(new QueryWrapper<Arearole>()
                    .eq("userid", organ.getUserid())
                    .eq("roletype", 13));
            if (num.intValue() > 0) {
                Quoter qt = iQuoterMapper.selectOne(new QueryWrapper<Quoter>()
                        .eq("areauserid", organ.getUserid())
                        .eq("quotername", organ.getAccountname()));
                if (null != qt && null != qt.getQuoterid()) {
                    //修改为修改后的机构名称
                    qt.setQuotername(param.getAccountname());
                    qt.setModifytime(new Date());
                    qt.setModifierid(systemmanager.getAutoid());
                    iQuoterMapper.updateById(qt);
                }
            }
        }

        organ.setAccountname(param.getAccountname());
        organ.setModifierid(systemmanager.getAutoid());
        organ.setModifytime(new Date());
        if (param.getRefereeuserid() != null) {
            organ.setRefereeuserid(param.getRefereeuserid());
        }
        iUseraccountMapper.update(organ, new QueryWrapper<Useraccount>().eq("userid", organ.getUserid()));

        Systemparam sysparm = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("paramcode", Constants.SYSPARAM_CARD_NO));

        Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", param.getUserid()));
        String card = EncryptionUtils.encryptByAES(param.getCardnum());
        if (!ui.getCardnum().equals(card)) {
            List<Userinfo> uiList = iUserinfoMapper.selectList(new QueryWrapper<Userinfo>()
                    .eq("cardnum", card)
                    .eq("userid", param.getUserid())
                    .eq("userstatus", 1)
            );
            if (CollectionUtils.isNotEmpty(uiList)) {
                if (sysparm == null || "1".equals(sysparm.getParamvalue())) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_011.getCode(), request.getHeader("Accept-Language"));
                }
            }
        }
        if (ui.getUserinfotype() == 2 && !ui.getCustomername().equals(param.getCustomername().trim())) {
            //机构类型为企业需 名称唯一
            Long c3 = iUserinfoMapper.selectCount(new QueryWrapper<Userinfo>()
                    .eq("customername", param.getCustomername().trim())
                    .eq("userinfotype", 2));
            if (c3 > 0) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_017.getCode(), request.getHeader("Accept-Language"));
            }
        }
        ui.setAddress(param.getAddress());
        ui.setBiznature(param.getBiznature());
        ui.setCardbackphotourl(param.getCardbackphotourl());
        ui.setCardfrontphotourl(param.getCardfrontphotourl());
        ui.setCardnum(param.getCardnum());
        ui.setCardtypeid(param.getCardtypeid());
        ui.setCityid(param.getCityid());
        ui.setCompany(param.getCompany());
        ui.setCountryid(param.getCountryid());
        ui.setCustomername(param.getCustomername());
        ui.setDistrictid(param.getDistrictid());
        ui.setEmail(param.getEmail());
        ui.setMobile(param.getMobile());
        ui.setModifierid(systemmanager.getAutoid());
        ui.setModifiertime(new Date());
        ui.setContactname(param.getContactname());
        ui.setPostalcode(param.getPostalcode());
        ui.setProvinceid(param.getProvinceid());
        ui.setQq(param.getQq());
        ui.setRemark(param.getRemark());
        ui.setSex(param.getSex());
        ui.setTelphone(param.getTelphone());
        ui.setLegalcardbackphotourl(param.getLegalcardbackphotourl());
        ui.setLegalpersonname(param.getLegalpersonname());
        ui.setLegalcardfrontphotourl(param.getLegalcardfrontphotourl());
        ui.setWechat(param.getWechat());
        ui.setAttachment1(param.getAttachment1());
        ui.setAttachment2(param.getAttachment2());

        ui = (Userinfo) SensitiveEncryptUtil.sensitiveEncrypt(ui, null);
        iUserinfoMapper.update(ui, new QueryWrapper<Userinfo>().eq("userid", ui.getUserid()));

        if (organ.getUsertype() != 4) {
            Systemmanager admin = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", param.getAutoid()));
            if (admin != null && !admin.getUsername().equals(param.getUsername())) {
                admin.setUsername(param.getUsername());
                iSystemmanagerMapper.updateById(admin);
            }
        }

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

    @Override
    public AjaxResult<AccountTradeConfigTreeVo> createTree(HttpServletRequest request) {
        List<Accounttradeconfig> list = iAccounttradeconfigMapper.getListForTree(0L);

        if (list == null || list.isEmpty()) {
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), list);
        }

        //先按类型
        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<Accounttradeconfig>();
                        _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<Accounttradeconfig> tradeConfigView(PersonalizationDelParam param, HttpServletRequest request) {
        Usergroupdetail ug = iUsergroupdetailMapper.selectOne(new QueryWrapper<Usergroupdetail>().eq("userid", param.getUserid()));
        if (ug != null) {
            param.setUsergroupid2(ug.getUsergroupid());
        }

        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<RulesConfigVo> ruleList = iUseraccountMapper.getTradeRuleDescriptions(param);
        List<FeesConfigVo> feeList = iUseraccountMapper.getTradeFeeDescriptions(param);

        List<Accounttradeconfig> list = iAccounttradeconfigMapper.selectList(new QueryWrapper<Accounttradeconfig>()
                .eq("accountid", param.getAccountid())
                .eq("userid", param.getUserid())
                .eq("tradetype", param.getTradetype())
                .eq("goodsid", param.getGoodsid())
                .eq("marketid", param.getMarketid())
                .eq("memberuserid", param.getMemberuserid()));

        Accounttradeconfig detail = new Accounttradeconfig();
        detail.setGoodsid(param.getGoodsid());
        detail.setMemberuserid(param.getMemberuserid());
        detail.setMarketid(param.getMarketid());
        detail.setUserid(param.getUserid());
        detail.setAccountid(param.getAccountid());
        detail.setTradetype(param.getTradetype());
        Map<String, Accounttradeconfig> map = new HashMap<>();

        for (Accounttradeconfig config : list) {
            if (config.getRuletype() == 1) {
                detail.setParamid(config.getParamid());
            } else if (config.getRuletype() == 2) {
                map.put("rule" + config.getParamid(), config);
            } else {
                map.put("fee" + config.getParamid(), config);
            }
        }

        if (ruleList != null && !ruleList.isEmpty()) {
            for (RulesConfigVo rulesConfigVo : ruleList) {
                Accounttradeconfig config = map.get("rule" + rulesConfigVo.getRuleid());
                if (config != null) {
                    //小数位放大
                    if (qtyde != null && rulesConfigVo.getRuleid() >= 101 && rulesConfigVo.getRuleid() <= 104) {
                        if (config.getParamvalue() != null &&
                                config.getParamvalue().compareTo(BigDecimal.ZERO) != 0) {
                            rulesConfigVo.setCvalue(config.getParamvalue().divide(qtyde));
                        }
                        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));
                        }
                    } else {
                        rulesConfigVo.setCvalue(config.getParamvalue());
                    }
                }
            }
        }
        if (feeList != null && !feeList.isEmpty()) {
            for (FeesConfigVo feesConfigVo : feeList) {
                Accounttradeconfig config = map.get("fee" + feesConfigVo.getTradefeeid());
                if (config != null) {
                    feesConfigVo.setCrithm(config.getFeealgorithm());
                    if (Cude != null && config.getFeealgorithm() == 2) {
                        if (config.getParamvalue() != null
                                && config.getParamvalue().compareTo(BigDecimal.ZERO) != 0) {
                            feesConfigVo.setCvalue(config.getParamvalue().divide(Cude));
                        }
                        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 {
                        feesConfigVo.setCvalue(config.getParamvalue());
                    }
                }
                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")));
                    }
                }
            }
        }
        detail.setDruleList(ruleList);
        detail.setDfeeList(feeList);

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult tradeConfigEdit(SupportTradeConfigAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

        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()));
        }

        iAccounttradeconfigMapper.delete(new QueryWrapper<Accounttradeconfig>()
                .eq("goodsid", param.getGoodsid())
                .eq("marketid", param.getMarketid())
                .eq("accountid", param.getAccountid())
                .eq("memberuserid", param.getMemberuserid())
                .eq("userid", param.getUserid())
                .eq("tradetype", param.getTradetype())
        );

        if (param.getParamid() != null) {
            Accounttradeconfig config = new Accounttradeconfig();
            config.setUserid(param.getUserid());
            config.setMemberuserid(param.getMemberuserid());
            config.setMarketid(param.getMarketid());
            config.setGoodsid(param.getGoodsid());
            config.setAccountid(param.getAccountid());
            config.setRuletype(1);
            config.setParamid(param.getParamid());
            config.setCreatetime(new Date());
            config.setCreatorid(systemmanager.getAutoid());
            config.setFeealgorithm(param.getFeealgorithm());
            config.setTradetype(param.getTradetype());
            iAccounttradeconfigMapper.insert(config);
        }

        List<Accounttradeconfig> ruleList = param.getRuleList();
        if (ruleList != null && !ruleList.isEmpty()) {
            for (Accounttradeconfig 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.setUserid(param.getUserid());
                fig.setMemberuserid(param.getMemberuserid());
                fig.setAccountid(param.getAccountid());
                fig.setMarketid(param.getMarketid());
                fig.setGoodsid(param.getGoodsid());
                fig.setRuletype(2);
                fig.setCreatetime(new Date());
                fig.setCreatorid(systemmanager.getAutoid());
                fig.setTradetype(param.getTradetype());
                iAccounttradeconfigMapper.insert(fig);
            }
        }

        List<Accounttradeconfig> feeList = param.getFeeList();
        if (feeList != null && !feeList.isEmpty()) {
            for (Accounttradeconfig 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.setUserid(param.getUserid());
                fig.setMemberuserid(param.getMemberuserid());
                fig.setMarketid(param.getMarketid());
                fig.setGoodsid(param.getGoodsid());
                fig.setAccountid(param.getAccountid());
                fig.setRuletype(3);
                fig.setCreatetime(new Date());
                fig.setCreatorid(systemmanager.getAutoid());
                fig.setTradetype(param.getTradetype());
                iAccounttradeconfigMapper.insert(fig);
            }
        }

        iSendMsgService.sendAccountConfigChangeNtf(4, 2, param.getUserid(), param.getAccountid(), param.getGoodsid(),
                null, param.getTradetype());

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

    @Override
    public AjaxResult tradeConfigDelete(PersonalizationDelParam param, HttpServletRequest request) {

        iAccounttradeconfigMapper.delete(new QueryWrapper<Accounttradeconfig>()
                .eq("memberuserid", param.getMemberuserid())
                .eq("userid", param.getUserid())
                .eq("tradetype", param.getTradetype())
                .eq(param.getGoodsid() != null, "goodsid", param.getGoodsid())
                .eq(param.getMarketid() != null, "marketid", param.getMarketid())
                .eq(param.getAccountid() != null, "accountid", param.getAccountid())
        );

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

    @Override
    public AjaxResult<OrganInitAccountAddResult> loadSelectOption(PersonalizationDelParam param, HttpServletRequest request) {
        OrganInitAccountAddResult result = new OrganInitAccountAddResult();
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if(param.getMemberuserid() == 1){
            if (param.getGoodsid() != null) {
                param.setMemberuserid(systemmanager.getAreauserid());
            }
        }
        if (param.getGoodsid() != null) {
            //客户类别
            List<InvestorInitBZResult> bzResults = iUseraccountMapper.getCustomerTypeByGoodsid(param.getGoodsid(), null);
            result.setResults(bzResults);
            List<FeesConfigVo> tradeFeeDescriptions = iUseraccountMapper.getTradeFeeDescriptions(param);
            for (FeesConfigVo tradeFeeDescription : tradeFeeDescriptions) {
                if(tradeFeeDescription.getFeealgorithm() == 1){
                    tradeFeeDescription.setExchangevalue(tradeFeeDescription.getExchangevalue().multiply(new BigDecimal("10000")));
                    tradeFeeDescription.setMembermaxvalue(tradeFeeDescription.getMembermaxvalue().multiply(new BigDecimal("10000")));
                    tradeFeeDescription.setMemberminvalue(tradeFeeDescription.getMemberminvalue().multiply(new BigDecimal("10000")));
                }
            }
            result.setFeesConfigVos(tradeFeeDescriptions);
            result.setRulesConfigVos(iUseraccountMapper.getTradeRuleDescriptions(param));
        } else if (param.getMarketid() != null) {
            List<Goods> goods = iGoodsMapper.getNoTradeConfigGoodsForAccount(param);
            result.setGoods(goods);
        } else if (param.getAccountid() != null) {
            if(param.getMemberuserid() == 1){
                param.setAccountid(null);
                param.setMemberuserid(null);
            }
            List<Market> markets = iMarketMapper.getNoTradeConfigMarketsForAccount(param);
            result.setMarkets(markets);
        } else if (param.getUserid() != null) {
            List<Long> longs = iTaaccountMapper.getNoTradeConfigAccounts(param);
            result.setAccountids(longs);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult tradeConfigAdd(SupportTradeConfigAddParam vo, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

        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", vo.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()));
        }

        if (vo.getParamid() != null) {
            Accounttradeconfig config = new Accounttradeconfig();
            config.setUserid(vo.getUserid());
            config.setMemberuserid(vo.getMemberuserid());
            config.setMarketid(vo.getMarketid());
            config.setGoodsid(vo.getGoodsid());
            config.setAccountid(vo.getAccountid());
            config.setRuletype(1);
            config.setParamid(vo.getParamid());
            config.setCreatetime(new Date());
            config.setCreatorid(systemmanager.getAutoid());
            config.setFeealgorithm(vo.getFeealgorithm());
            config.setTradetype(vo.getTradetype());
            iAccounttradeconfigMapper.insert(config);
        }

        List<Accounttradeconfig> ruleList = vo.getRuleList();
        if (ruleList != null && !ruleList.isEmpty()) {
            for (Accounttradeconfig 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.setUserid(vo.getUserid());
                fig.setMemberuserid(vo.getMemberuserid());
                fig.setAccountid(vo.getAccountid());
                fig.setMarketid(vo.getMarketid());
                fig.setGoodsid(vo.getGoodsid());
                fig.setRuletype(2);
                fig.setCreatetime(new Date());
                fig.setCreatorid(systemmanager.getAutoid());
                fig.setTradetype(vo.getTradetype());
                iAccounttradeconfigMapper.insert(fig);
            }
        }

        List<Accounttradeconfig> feeList = vo.getFeeList();
        if (feeList != null && !feeList.isEmpty()) {
            for (Accounttradeconfig 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.setUserid(vo.getUserid());
                fig.setMemberuserid(vo.getMemberuserid());
                fig.setMarketid(vo.getMarketid());
                fig.setGoodsid(vo.getGoodsid());
                fig.setAccountid(vo.getAccountid());
                fig.setRuletype(3);
                fig.setCreatetime(new Date());
                fig.setCreatorid(systemmanager.getAutoid());
                fig.setTradetype(vo.getTradetype());
                iAccounttradeconfigMapper.insert(fig);
            }
        }
        iSendMsgService.sendAccountConfigChangeNtf(4, 1, vo.getUserid(), vo.getAccountid(), vo.getGoodsid(),
                null, vo.getTradetype());

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

    @Override
    public AjaxResult logout(Long areaid, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Useraccount org = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", areaid));
        if (org.getUsertype() != 5) {
            List<Arearole> list2 = iArearoleMapper.selectList(new QueryWrapper<Arearole>().eq("userid", areaid));
            if (CollectionUtils.isNotEmpty(list2)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language"));
            }
            List<Useraccount> list = iUseraccountMapper.selectList(new QueryWrapper<Useraccount>()
                    .eq("parentuserid", areaid)
                    .eq("accountstatus", 4)
                    .in("usertype", 3, 4)
            );
            if (CollectionUtils.isNotEmpty(list)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language"));
            }
            if (org.getUsertype() == 4) {
                list = iUseraccountMapper.selectList(new QueryWrapper<Useraccount>()
                        .eq("usertype", 5)
                        .eq("broker", areaid)
                        .eq("accountstatus", 4));
                if (CollectionUtils.isNotEmpty(list)) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language"));
                }
            } else {
                list = iUseraccountMapper.selectList(new QueryWrapper<Useraccount>()
                        .eq("parentuserid", areaid)
                        .eq("accountstatus", 4)
                        .eq("usertype", 5));
                if (CollectionUtils.isNotEmpty(list)) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language"));
                }
            }

        } else {
            List<Taaccount> taList = iTaaccountMapper.selectList(new QueryWrapper<Taaccount>()
                    .eq("userid", areaid)
                    .gt("currentbalance", 0)
            );
            if (CollectionUtils.isNotEmpty(taList)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
            }
            List<Tradeposition> tpList = iTradepositionMapper.queryAmount(areaid);
            if (CollectionUtils.isNotEmpty(tpList)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }

        }

        log.info("收到用户注销请求：" + areaid.toString());

        org.setAccountstatus(6);
        org.setModifierid(systemmanager.getAutoid());
        org.setModifytime(new Date());
        org.setCanceltime(new Date());
        iUseraccountMapper.update(org, new QueryWrapper<Useraccount>().eq("userid", org.getUserid()));

        Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", areaid));
        ui.setUserstatus(2);
        iUserinfoMapper.update(ui, new QueryWrapper<Userinfo>().eq("userid", areaid));

        //注销 所有账户
        List<Systemmanager> admin = iSystemmanagerMapper.selectList(new QueryWrapper<Systemmanager>().eq("areauserid", areaid));
        if (CollectionUtils.isNotEmpty(admin)) {
            admin.forEach(p -> {
                p.setManagerstatus(2);//停用
                iSystemmanagerMapper.updateById(p);
            });
        }

        //删除登录关联关系
        iUserauthinfoMapper.delete(new QueryWrapper<Userauthinfo>().eq("userid", areaid));

        //写入日志
        if (org.getUsertype() == 2)
            systemmanagerService.writeOperateLog(SysConstants.PART_CODE_ORGZ, "注销或删除机构id=" + org.getUserid(), systemmanager, null, null, null);
        else if (org.getUsertype() == 3 || org.getUsertype() == 4) {
            String name = "";
            if (org.getUsertype() == 3)
                name = "子机构";
            if (org.getUsertype() == 4)
                name = "经纪人";
            if (systemmanager.getReletype() == 1)
                systemmanagerService.writeOperateLog(SysConstants.PART_CODE_ORGZ, "注销或删除" + name + "id=" + org.getUserid(), systemmanager, null, null, null);
            else
                systemmanagerService.writeOperateLog(SysConstants.PART_CODE_ORGZ_ZJG, "注销或删除" + name + "id=" + org.getUserid(), systemmanager, null, null, null);
        } else if (org.getUsertype() == 5)
            systemmanagerService.writeOperateLog(SysConstants.PART_INVESTOR_MANAGE, "注销或删除投资者id=" + org.getUserid(), systemmanager, null, null, null);

        log.info("用户注销更新完成：" + areaid.toString());
        List<Loginaccount> las = iLoginaccountMapper.selectList(new QueryWrapper<Loginaccount>()
                .eq("userid", org.getUserid())
                .eq("loginstatus", 1));

        if (CollectionUtils.isNotEmpty(las)) {
            // 创建一个 UpdateWrapper 实例
            UpdateWrapper<Loginaccount> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("userid", org.getUserid());
            iLoginaccountMapper.update(new Loginaccount().setLoginstatus(3), updateWrapper);

            NotifyMI1.LoginAccChangeNtf.Builder builder = NotifyMI1.LoginAccChangeNtf.newBuilder();
            Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
            PublicMI1.NotifyHead.Builder nhd = PublicMI1.NotifyHead.newBuilder();
            nhd.setNtfMode(0);
            hd.setFunCode(FunCodeConstants.FunCode_Trade_LoginAccChangeNtf);
            hd.setClientTime(System.currentTimeMillis());
            builder.setNtfHeader(nhd);
            builder.setHeader(hd);
            las.forEach(p -> {
                NotifyMI1.LoginAccChange.Builder lab = NotifyMI1.LoginAccChange.newBuilder();
                lab.setChangeType(SysEnums.AccountOperateTypeEnum.DEL.getType());
                lab.setLoginId(p.getLoginid());
                builder.addLoginAccChange(lab);
            });
            byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(),
                    FunCodeConstants.FunCode_Trade_LoginAccChangeNtf);
            rabbitTemplate.send(SysConstants.RabbitNtfKey,
                    new Message(body, new MessageProperties()));

            log.info("用户注销发送登录账户变更通知：" + areaid.toString());
        }

        // 发送用户注销消息给中心\银行接口
        List<Taaccount> tas = iTaaccountMapper.selectList(new QueryWrapper<Taaccount>()
                .eq("userid", org.getUserid())
                .eq("ismain", 1));
        iSendMsgService.sendM2BUnregistCustomerInfo(tas);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<InitInvestorTradeResult> initAccTrade(String searchName, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Long memberuserid = null;
        if (systemmanager.getReletype() != 1) {
            memberuserid = systemmanager.getAreauserid();
        }
        List<InitInvestorTradeResult> results = iUseraccountMapper.getNoTradeConfigInvestorsLikeName(memberuserid, searchName);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    @Override
        public AjaxResult<String> getOragnDefaultManager(Long userid, HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>()
                .eq("areauserid", userid)
                .eq("isdefault", 1));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), user == null ? "" : user.getLogincode() + "(" + user.getUsername() + ")");
    }

    private void editARoleModifyMember(OrganRoleModifyParam vo, Systemmanager opeartion) {
        Date date = new Date();

        //卖方管理  当前修改角色时 等同自营  2019年6月18日 10:30:28
        Integer roleid = vo.getRoleid() == SysEnums.OrganRole.seller.getCode().intValue() ?
                SysEnums.OrganRole.selfsupport.getCode().intValue() : vo.getRoleid();
        Arearole or = iArearoleMapper.selectOne(new QueryWrapper<Arearole>().eq("userid", vo.getUserid()).eq("roletype", roleid));

        if (roleid == SysEnums.OrganRole.selfsupport.getCode().intValue()
                || roleid == SysEnums.OrganRole.broker.getCode().intValue()) {
            //市场
            iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", vo.getUserid()).eq("roletype", roleid));
            List<TaAccountMarketVo> dtype = vo.getDtype();

            List<Long> marketids = new ArrayList<>();
            if (dtype != null && !dtype.isEmpty()) {
                for (TaAccountMarketVo td : dtype) {
                    if (td != null && td.getMarketId() != null) {
                        marketids.add(td.getMarketId());
                        Arearolemarket m = new Arearolemarket();
                        m.setAreauserid(vo.getUserid());
                        m.setMarketid(td.getMarketId());
                        m.setRoletype(roleid);
                        m.setModifierid(opeartion.getAutoid());
                        m.setModifytime(date);
                        m.setSpotrighttype(td.getSpotRightType());
                        m.setBuyspotrighttype(td.getDType());
                        iArearolemarketMapper.insert(m);
                    }
                }
            }

            if (roleid == SysEnums.OrganRole.broker.getCode().intValue()) {
                Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", vo.getUserid()));
                if (vo.getParentuserid() == null) {
                    ua.setParentuserid(1L);
                } else {
                    ua.setParentuserid(vo.getParentuserid());
                }
                iUseraccountMapper.update(ua, new QueryWrapper<Useraccount>().eq("userid", ua.getUserid()));
            }

            if (roleid == SysEnums.OrganRole.selfsupport.getCode().intValue()) {
                //更新资金账户市场权限
                iTaaccountMapper.deleteUserMarket(vo.getUserid(), marketids);

                // 处理自营账号信息
                handleSelfMemberAccount(roleid, vo, opeartion, dtype);
            }
        } else if (roleid == SysEnums.OrganRole.marketer.getCode().intValue()) {

            if (CollectionUtils.isNotEmpty(vo.getAccountids())) {
                Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("userid", vo.getUserid()));
                ta.setIsmarketaccount(0);
                iTaaccountMapper.update(ta, new QueryWrapper<Taaccount>().eq("userid", ta.getUserid()));

                iUserreckonaccountMapper.delete(new QueryWrapper<Userreckonaccount>().eq("userid", vo.getUserid()).eq("defaultaccounttype", 2));
                for (int i = 0; i < vo.getAccountids().size(); i++) {
                    Taaccount current = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("userid", vo.getAccountids().get(i)));
                    current.setIsmarketaccount(1);
                    iTaaccountMapper.update(ta, new QueryWrapper<Taaccount>().eq("userid", current.getAccountid()));

                    Userreckonaccount iura = new Userreckonaccount();
                    iura.setUserid(vo.getUserid());
                    iura.setCurrencyid(vo.getEnumdicnames().get(i).intValue());
                    iura.setReckonaccountid(vo.getAccountids().get(i));
                    iura.setUpdatetime(new Date());
                    iura.setDefaultaccounttype(2);
                    iUserreckonaccountMapper.insert(iura);
                }
            }

            iCustomertypeareadetailMapper.delete(new QueryWrapper<Customertypeareadetail>()
                    .eq("userid", vo.getUserid())
                    .eq("arearoleid", roleid));
            if (vo.getCustomertype() != null) {
                Customertypeareadetail ca = new Customertypeareadetail();
                ca.setArearoleid(SysEnums.OrganRole.marketer.getCode());
                ca.setCustomertype(vo.getCustomertype());
                ca.setUserid(vo.getUserid());
                iCustomertypeareadetailMapper.insert(ca);
            }
        } else if (roleid == SysEnums.OrganRole.quoterorgan.getCode().intValue()
                || roleid == SysEnums.OrganRole.outoption.getCode().intValue()) {
            //保存做市机构
            iArearolemarketmakerMapper.delete(new QueryWrapper<Arearolemarketmaker>()
                    .eq("areauserid", vo.getUserid())
                    .eq("roletype", roleid));
            String marketings = vo.getMarketings();
            if (StringUtils.isNotBlank(marketings)) {
                String[] ids = marketings.split(",");
                for (String id : ids) {
                    if (StringUtils.isNotBlank(id)) {
                        Arearolemarketmaker am = new Arearolemarketmaker();
                        am.setAreauserid(vo.getUserid());
                        am.setRoletype(roleid);
                        am.setMmuserid(Long.valueOf(id));
                        am.setModifytime(date);
                        am.setModifierid(opeartion.getAutoid());
                        iArearolemarketmakerMapper.insert(am);
                    }
                }
            }
        } else if (roleid == SysEnums.OrganRole.ordinarymember.getCode().intValue() || roleid == SysEnums.OrganRole.coremember.getCode().intValue()) {
            //市场
            iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", vo.getUserid()).eq("roletype", 6));
            List<TaAccountMarketVo> dtype = vo.getDtype();
            List<Long> marketids = new ArrayList<>();
            if (dtype != null && !dtype.isEmpty()) {
                for (TaAccountMarketVo td : dtype) {
                    if (td != null && td.getMarketId() != null) {
                        marketids.add(td.getMarketId());
                        Arearolemarket m = new Arearolemarket();
                        m.setAreauserid(vo.getUserid());
                        m.setMarketid(td.getMarketId());
                        m.setRoletype(6);
                        m.setModifierid(opeartion.getAutoid());
                        m.setModifytime(date);
                        m.setSpotrighttype(td.getSpotRightType());
                        m.setBuyspotrighttype(td.getDType());
                        iArearolemarketMapper.insert(m);
                    }
                }
            }

            //送检账户
            Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", vo.getUserid()));
            ua.setSjaccountno(vo.getSjaccountno());
            iUseraccountMapper.update(ua, new QueryWrapper<Useraccount>().eq("userid", ua.getUserid()));

            //更新资金账户市场权限
            iTaaccountMapper.deleteUserMarket(vo.getUserid(), marketids);

            Map<String, Object> properties = new HashMap<String, Object>();
            if (CollectionUtils.isNotEmpty(marketids)) {
                Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("userid", vo.getUserid()).eq("ismain", 1));
                iTaaccountmarketMapper.delete(new QueryWrapper<Taaccountmarket>().eq("accountid", ta.getAccountid()));
                for (TaAccountMarketVo td : dtype) {
                    if (td != null && td.getMarketId() != null) {
                        Taaccountmarket tm = new Taaccountmarket();
                        tm.setAccountid(ta.getAccountid());
                        tm.setMarketid(td.getMarketId());
                        tm.setModifytime(date);
                        tm.setModifierid(opeartion.getAutoid());
                        tm.setSpotrighttype(td.getSpotRightType());
                        tm.setBuyspotrighttype(td.getDType());
                        iTaaccountmarketMapper.insert(tm);
                    }
                }
            }
        }

        or.setUserid(vo.getUserid());
        or.setRoletype(roleid);
        or.setTradeaccountid(vo.getAccountid());
        or.setModifierid(opeartion.getAutoid());
        or.setModifytime(date);
        or.setTransurl(vo.getTransurl());
    }

    private void editAreaRoleModifyFee(OrganRoleModifyParam vo, Systemmanager opeartion, HttpServletRequest request) {
        Arearole or = iArearoleMapper.selectOne(new QueryWrapper<Arearole>()
                .eq("userid", vo.getUserid())
                .eq("roletype", vo.getRoleid()));
        or.setUserid(vo.getUserid());
        or.setRoletype(vo.getRoleid());
        or.setTradeaccountid(vo.getAccountid());
        or.setModifierid(opeartion.getAutoid());
        or.setModifytime(new Date());
        iArearoleMapper.update(or, new QueryWrapper<Arearole>().eq("userid", vo.getUserid()).eq("roletype", vo.getRoleid()));

        if (vo.getRoleid().compareTo(SysEnums.OrganRole.operate.getCode()) == 0) {
            iMarketMapper.updateExchareaidNull(vo.getUserid());
            List<Integer> marketids = vo.getMarketids();
            if (marketids != null && !marketids.isEmpty()) {
                Map<String, Object> update = new HashMap<>();
                update.put("marketids", marketids);
                update.put("exchareaid", vo.getUserid());
                iMarketMapper.updateExchareaid(marketids, vo.getUserid());

                Systemparam p = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_ID_MARKET));
                if (p != null) {
                    p.setParamvalue(String.valueOf(System.currentTimeMillis()));
                    p.setUpdatetime(new Date());
                    iSystemparamMapper.update(p, new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_ID_MARKET));
                }
            }
        }

        //清除原数据
        iArearoledivideconfigMapper.delete(new QueryWrapper<Arearoledivideconfig>()
                .eq("userid", vo.getUserid())
                .eq("roletype", vo.getRoleid()));

        //分润
        if (vo.getFee() != null && !vo.getFee().isEmpty()) {
            int size = vo.getFee().size();
            for (int i = 0; i < size; i++) {
                Arearoledivideconfig fee = vo.getFee().get(i);
                if (fee.getTradefeeid() == null || fee.getFeealgorithm() == null ||
                        fee.getDividevalue() == null) {
                    continue;
                }
                if (fee.getFeealgorithm() == 1 && fee.getDividevalue().compareTo(new BigDecimal(100)) > 0) {
                    throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_035.getCode(), request.getHeader("Accept-Language"));
                }
                if (fee.getFeealgorithm() == 1) {
                    fee.setDividevalue(fee.getDividevalue().divide(new BigDecimal(100)));
                }
                fee.setUserid(or.getUserid());
                fee.setMarketid(0L);
                fee.setGoodsid(0L);
                fee.setRoletype(or.getRoletype());
                fee.setCreatetime(new Date());
                fee.setCreatorid(opeartion.getAutoid());
                fee.setModifytime(new Date());
                fee.setModifierid(opeartion.getAutoid());
                iArearoledivideconfigMapper.insert(fee);
            }
        }

        //商品个性化配置
        if (vo.getPfee() != null && !vo.getPfee().isEmpty()) {
            int size = vo.getPfee().size();
            for (int i = 0; i < size; i++) {
                Arearoledivideconfig fee = vo.getPfee().get(i);
                if (fee.getGoodsid() == null || fee.getTradefeeid() == null || fee.getFeealgorithm() == null ||
                        fee.getDividevalue() == null) {
                    continue;
                }
                if (fee.getFeealgorithm() == 1 && fee.getDividevalue().compareTo(new BigDecimal(100)) > 0) {
                    throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_035.getCode(), request.getHeader("Accept-Language"));
                }
                if (fee.getFeealgorithm() == 1) {
                    fee.setDividevalue(fee.getDividevalue().divide(new BigDecimal(100)));
                }
                fee.setUserid(or.getUserid());
                fee.setRoletype(or.getRoletype());
                fee.setCreatetime(new Date());
                fee.setCreatorid(opeartion.getAutoid());
                fee.setModifytime(new Date());
                fee.setModifierid(opeartion.getAutoid());
                iArearoledivideconfigMapper.insert(fee);
            }
        }

        // 运营机构权限变更为可查询有商品权限的交易单据 2024-01-15
        updateOperateGoodsConfig(vo);
    }

    private void addAreaRoleModifyMember(OrganRoleModifyParam vo, Systemmanager opeartion) {
        Integer roleid = vo.getRoleid();
        Arearole or = new Arearole();
        Date date = new Date();
        Systemmanager user = null;
        Long loginid = null; //新加的登录账号ID
        String sysp = iCommonService.getSysparmById(SysConstants.SYSPAMA_CODE_NINESERVENNINE);
        if (roleid == SysEnums.OrganRole.selfsupport.getCode().intValue()
                || roleid == SysEnums.OrganRole.broker.getCode().intValue()) {

            if (roleid == SysEnums.OrganRole.broker.getCode().intValue()) {
                //经纪会员更新营销中心
                Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", vo.getUserid()));
                if (ua != null) {
                    if (vo.getParentuserid() != null) {
                        ua.setParentuserid(vo.getParentuserid());
                    } else {
                        ua.setParentuserid(1L);
                    }
                    iUseraccountMapper.update(ua, new QueryWrapper<Useraccount>().eq("userid", vo.getUserid()));
                }
            }

            //市场
            iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", vo.getUserid()).eq("roletype", roleid));

            List<TaAccountMarketVo> dtype = vo.getDtype();
            if (dtype != null && !dtype.isEmpty()) {
                for (TaAccountMarketVo td : dtype) {
                    if (td != null && td.getMarketId() != null) {
                        Arearolemarket m = new Arearolemarket();
                        m.setAreauserid(vo.getUserid());
                        m.setMarketid(td.getMarketId());
                        m.setRoletype(roleid);
                        m.setModifierid(opeartion.getAutoid());
                        m.setModifytime(date);
                        m.setSpotrighttype(td.getSpotRightType());
                        m.setBuyspotrighttype(td.getDType());
                        iArearolemarketMapper.insert(m);
                    }
                }
            }
            // 自营会员 处理自营账号信息
            if (roleid == SysEnums.OrganRole.selfsupport.getCode().intValue()) {
                handleSelfMemberAccount(roleid, vo, opeartion, dtype);
            }
        } else if (roleid == SysEnums.OrganRole.industry.getCode().intValue()) {
            // 创建产业角色时是否同时创建自营角色
            if ("1".equals(sysp)) {
                //市场
                iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", vo.getUserid()).eq("roletype", 6));

                iArearoleMapper.delete(new QueryWrapper<Arearole>()
                        .in("roletype", 6, 9)
                        .eq("userid", vo.getUserid()));

                List<TaAccountMarketVo> dtype = vo.getDtype();
                if (dtype != null && !dtype.isEmpty()) {
                    for (TaAccountMarketVo td : dtype) {
                        if (td != null && td.getMarketId() != null) {
                            Arearolemarket m = new Arearolemarket();
                            m.setAreauserid(vo.getUserid());
                            m.setMarketid(td.getMarketId());
                            m.setRoletype(6);
                            m.setModifierid(opeartion.getAutoid());
                            m.setModifytime(date);
                            m.setSpotrighttype(td.getSpotRightType());
                            m.setBuyspotrighttype(td.getDType());
                            iArearolemarketMapper.insert(m);
                        }
                    }
                }
                Arearole ar = new Arearole();
                ar.setCreatetime(new Date());
                ar.setCreatorid(opeartion.getAutoid());
                ar.setUserid(vo.getUserid());
                ar.setRoletype(6);
                ar.setTradeaccountid(vo.getAccountid());
                ar.setModifierid(opeartion.getAutoid());
                ar.setModifytime(new Date());
                ar.setTransurl(vo.getTransurl());
                ar.setOutuserid(vo.getOutuserid());
                iArearoleMapper.insert(ar);

                // 处理自营账号信息
                handleSelfMemberAccount(roleid, vo, opeartion, dtype);

            }
        } else if (roleid == SysEnums.OrganRole.marketer.getCode().intValue()) {
            if (CollectionUtils.isNotEmpty(vo.getAccountids())) {
                for (int i = 0; i < vo.getAccountids().size(); i++) {
                    Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>().eq("accountid", vo.getAccountids().get(i)));
                    ta.setIsmarketaccount(1);
                    iTaaccountMapper.update(ta, new QueryWrapper<Taaccount>().eq("accountid", ta.getAccountid()));

                    Userreckonaccount iura = new Userreckonaccount();
                    iura.setUserid(vo.getUserid());
                    iura.setCurrencyid(vo.getEnumdicnames().get(i).intValue());
                    iura.setReckonaccountid(vo.getAccountids().get(i));
                    iura.setUpdatetime(new Date());
                    iura.setDefaultaccounttype(2);
                    iUserreckonaccountMapper.insert(iura);
                }
            }
            if (vo.getCustomertype() != null) {
                Customertypeareadetail ca = new Customertypeareadetail();
                ca.setArearoleid(SysEnums.OrganRole.marketer.getCode());
                ca.setCustomertype(vo.getCustomertype());
                ca.setUserid(vo.getUserid());
                iCustomertypeareadetailMapper.insert(ca);
            }

        } else if (roleid == SysEnums.OrganRole.shoping.getCode().intValue()) {
            //商城 同步数据
            or.setShoppassword(EncryptionUtils.encryptSHA(vo.getUserid() + vo.getShoppassword()));
        } else if (roleid == SysEnums.OrganRole.quoterorgan.getCode().intValue()
                || roleid == SysEnums.OrganRole.outoption.getCode().intValue()) {
            //保存做市机构
            String marketings = vo.getMarketings();
            if (StringUtils.isNotBlank(marketings)) {
                String[] ids = marketings.split(",");
                for (String id : ids) {
                    if (StringUtils.isNotBlank(id)) {
                        Arearolemarketmaker am = new Arearolemarketmaker();
                        am.setAreauserid(vo.getUserid());
                        am.setRoletype(roleid);
                        am.setMmuserid(Long.valueOf(id));
                        am.setModifytime(date);
                        am.setModifierid(opeartion.getAutoid());
                        iArearolemarketmakerMapper.insert(am);
                    }
                }
            }
        } else if (roleid == SysEnums.OrganRole.seller.getCode().intValue()) {
            //市场
            iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", vo.getUserid()).eq("roletype", 6));

            List<TaAccountMarketVo> dtype = vo.getDtype();
            if (dtype != null && !dtype.isEmpty()) {
                for (TaAccountMarketVo td : dtype) {
                    if (td != null && td.getMarketId() != null) {
                        Arearolemarket m = new Arearolemarket();
                        m.setAreauserid(vo.getUserid());
                        m.setMarketid(td.getMarketId());
                        m.setRoletype(6);
                        m.setModifierid(opeartion.getAutoid());
                        m.setModifytime(date);
                        m.setSpotrighttype(td.getSpotRightType());
                        m.setBuyspotrighttype(td.getDType());
                        iArearolemarketMapper.insert(m);
                    }
                }
            }

            // 处理自营账号信息
            handleSelfMemberAccount(roleid, vo, opeartion, dtype);

            or.setCreatorid(opeartion.getAutoid());
            or.setUserid(vo.getUserid());
            or.setRoletype(6);
            or.setTradeaccountid(vo.getAccountid());
            or.setModifierid(opeartion.getAutoid());
            or.setModifytime(new Date());
            or.setTransurl(vo.getTransurl());
            or.setOutuserid(vo.getOutuserid());
            iArearoleMapper.insert(or);

            Arearole or1 = new Arearole();
            BeanUtils.copyProperties(or, or1);
            or1.setRoletype(9);
            iArearoleMapper.insert(or1);

            String l = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "002");
            if ("2".equals(l)) {
                user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>()
                        .eq("areauserid", vo.getUserid())
                        .eq("isdefault", 1));

                Roleuser ur = new Roleuser();
                ur.setRoleid(6L);
                ur.setManagerid(user.getAutoid());
                ur.setRoletype(3);
                iRoleuserMapper.insert(ur);

                Roleuser ur1 = new Roleuser();
                ur1.setRoleid(9L);
                ur1.setManagerid(user.getAutoid());
                ur1.setRoletype(3);
                iRoleuserMapper.insert(ur1);
            }
            return;
        } else if (roleid == SysEnums.OrganRole.ordinarymember.getCode().intValue() || roleid == SysEnums.OrganRole.coremember.getCode().intValue()) {
            // 市场
            iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("areauserid", vo.getUserid()).eq("roletype", 6));

            List<TaAccountMarketVo> dtype = vo.getDtype();
            if (dtype != null && !dtype.isEmpty()) {
                for (TaAccountMarketVo td : dtype) {
                    if (td != null && td.getMarketId() != null) {
                        Arearolemarket m = new Arearolemarket();
                        m.setAreauserid(vo.getUserid());
                        m.setMarketid(td.getMarketId());
                        m.setRoletype(6);
                        m.setModifierid(opeartion.getAutoid());
                        m.setModifytime(date);
                        m.setSpotrighttype(td.getSpotRightType());
                        m.setBuyspotrighttype(td.getDType());
                        iArearolemarketMapper.insert(m);
                    }
                }
            }

            //送检账户
            Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", vo.getUserid()));
            ua.setSjaccountno(vo.getSjaccountno());
            iUseraccountMapper.update(ua, new QueryWrapper<Useraccount>().eq("userid", ua.getUserid()));

            //角色
            iArearoleMapper.delete(new QueryWrapper<Arearole>().eq("userid", vo.getUserid()).in("roletype", 4, 6, 9, roleid));

            or.setCreatorid(opeartion.getAutoid());
            or.setCreatetime(new Date());
            or.setUserid(vo.getUserid());
            or.setRoletype(4);
            or.setTradeaccountid(vo.getAccountid());
            or.setModifierid(opeartion.getAutoid());
            or.setModifytime(new Date());
            or.setTransurl(vo.getTransurl());
            or.setOutuserid(vo.getOutuserid());
            iArearoleMapper.insert(or);

            Arearole or1 = new Arearole();
            BeanUtils.copyProperties(or, or1);
            or1.setRoletype(6);
            iArearoleMapper.insert(or1);

            or1 = new Arearole();
            BeanUtils.copyProperties(or, or1);
            or1.setRoletype(9);
            iArearoleMapper.insert(or1);

            or = new Arearole();

            user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>()
                    .eq("areauserid", vo.getUserid())
                    .eq("isdefault", 1));

            iRoleuserMapper.delete(new QueryWrapper<Roleuser>()
                    .eq("managerid", user.getAutoid())
                    .in("roleid", 4, 6, 9, roleid));

            Roleuser ur = new Roleuser();
            ur.setRoleid(4L);
            ur.setManagerid(user.getAutoid());
            ur.setRoletype(3);
            iRoleuserMapper.insert(ur);

            ur = new Roleuser();
            ur.setRoleid(6L);
            ur.setManagerid(user.getAutoid());
            ur.setRoletype(3);
            iRoleuserMapper.insert(ur);

            ur = new Roleuser();
            ur.setRoleid(9L);
            ur.setManagerid(user.getAutoid());
            ur.setRoletype(3);
            iRoleuserMapper.insert(ur);

            //添加会员登录账号

            List<Loginaccount> loginList = iLoginaccountMapper.selectList(new QueryWrapper<Loginaccount>()
                    .eq("userid", vo.getUserid())
                    .eq("loginusertype", 2));
            if (CollectionUtils.isEmpty(loginList)) {
                String defaultPwd = "123456";
                Systemparam defaultPwdParam = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("paramcode", SysConstants.SYSPARAM_CODE_DEFAULT_PWD));
                if (defaultPwdParam != null && !defaultPwdParam.getParamvalue().isEmpty()) {
                    defaultPwd = defaultPwdParam.getParamvalue();
                }
                //添加自营会员登录账号
                loginid = tradingAccountService.getNewLoginIdByUserid(vo.getUserid(), 2);
                Loginaccount la = new Loginaccount();
                la.setLoginfailnum(0);
                la.setLoginid(loginid);
                la.setLoginstatus(1);
                la.setLoginusertype(2);
                la.setPassword(EncryptionUtils.encryptSHA(loginid.toString() + defaultPwd));
                la.setUserid(vo.getUserid());
                la.setModifierid(opeartion.getAutoid());
                la.setModifytime(date);
                la.setHasupdatedpwd(0);
                String logincode = null;
                Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", vo.getUserid()));
                if (StringUtils.isBlank(ui.getLogincode())) {
                    Systemmanager systemManager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>()
                            .eq("areauserid", vo.getUserid())
                            .eq("isdefault", 1));
                    logincode = systemManager.getLogincode();
                } else {
                    logincode = ui.getLogincode();
                }
                la.setLogincode(logincode);
                iLoginaccountMapper.insert(la);

                Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>()
                        .eq("userid", vo.getUserid())
                        .eq("ismain", 1));
                Logintaaccount lta = new Logintaaccount();
                lta.setLoginid(loginid);
                lta.setAccountid(ta.getAccountid());
                lta.setModifytime(new Date());
                lta.setModifierid(opeartion.getAutoid());
                iLogintaaccountMapper.insert(lta);
            } else {
                for (Loginaccount la : loginList) {
                    la.setLoginstatus(1);
                    iLoginaccountMapper.update(la, new QueryWrapper<Loginaccount>().eq("loginid", la.getLoginid()));
                }
            }

            // 默认资金账户附上所选市场权限 0-否，1-是
            if (dtype != null && !dtype.isEmpty()) {
                // 删除
                Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>()
                        .eq("userid", vo.getUserid())
                        .eq("ismain", 1));
                iTaaccountmarketMapper.delete(new QueryWrapper<Taaccountmarket>().eq("accountid", ta.getAccountid()));

                for (TaAccountMarketVo td : dtype) {
                    if (td != null && td.getMarketId() != null) {
                        Taaccountmarket tm = new Taaccountmarket();
                        tm.setAccountid(ta.getAccountid());
                        tm.setMarketid(td.getMarketId());
                        tm.setModifytime(date);
                        tm.setModifierid(opeartion.getAutoid());
                        tm.setSpotrighttype(td.getSpotRightType());
                        tm.setBuyspotrighttype(td.getDType());
                        iTaaccountmarketMapper.insert(tm);
                    }
                }
            }
        }

        if (roleid != SysEnums.OrganRole.quoterorgan.getCode().intValue()) {
            if (roleid == SysEnums.OrganRole.ordinarymember.getCode().intValue() || roleid == SysEnums.OrganRole.coremember.getCode().intValue()) {
                if (user == null) {
                    user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>()
                            .eq("areauserid", vo.getUserid())
                            .eq("isdefault", 1));
                }
                Roleuser ur = new Roleuser();
                ur.setRoleid(Long.valueOf(roleid));
                ur.setManagerid(user.getAutoid());
                ur.setRoletype(3);
                iRoleuserMapper.insert(ur);
            } else {
                String l = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "002");
                if ("2".equals(l)) {
                    user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>()
                            .eq("areauserid", vo.getUserid())
                            .eq("isdefault", 1));
                    if ("1".equals(sysp) && roleid == 9) {
                        iRoleuserMapper.delete(new QueryWrapper<Roleuser>()
                                .eq("managerid", user.getAutoid())
                                .in("roleid", 6, 9));

                        Roleuser ru = new Roleuser();
                        ru.setRoleid(6L);
                        ru.setManagerid(user.getAutoid());
                        ru.setRoletype(3);
                        iRoleuserMapper.insert(ru);
                    }
                    Roleuser ur = new Roleuser();
                    ur.setRoleid(Long.valueOf(roleid));
                    ur.setManagerid(user.getAutoid());
                    ur.setRoletype(3);
                    iRoleuserMapper.insert(ur);
                }
            }
        }
        or.setCreatetime(new Date());
        or.setCreatorid(opeartion.getAutoid());
        or.setUserid(vo.getUserid());
        or.setRoletype(roleid);
        or.setTradeaccountid(vo.getAccountid());
        or.setModifierid(opeartion.getAutoid());
        or.setModifytime(new Date());
        or.setTransurl(vo.getTransurl());
        or.setOutuserid(vo.getOutuserid());
        iArearoleMapper.insert(or);

        if (loginid != null) {
            List<Long> loginids = new ArrayList<>();
            loginids.add(loginid);
            Set<Long> set_msg = new HashSet<>(loginids);
            iSendMsgService.sendLoginMsg(set_msg, 0, 0);
        }
    }

    private void handleSelfMemberAccount(Integer roleid, OrganRoleModifyParam vo, Systemmanager opeartion, List<TaAccountMarketVo> dtype) {
        // 自营会员创建PC登录账号
        generatePCLoginAccount(vo, opeartion);

        // 默认资金账户附上所选市场权限 0-否，1-是
        addMarketRightToMainAccount(vo, opeartion, dtype);

        // 添加登录账号与资金账户有关系表
        addLoginTaaccount(vo, opeartion);

        // 发送登录账号变更通知
        sendLoginAccountChangeMsg(vo.getUserid());
    }

    private void sendLoginAccountChangeMsg(Long userid) {
        Map<String, Object> resultMap = new HashMap<>();
        Userinfo ui = iUserinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("userid", userid));
        if (ui != null) {
            resultMap.put("userinfo", ui);
        }
        List<Taaccount> tas = iTaaccountMapper.selectList(new QueryWrapper<Taaccount>().eq("userid", userid));
        if (tas != null) {
            resultMap.put("taaccount", tas);
        }
        Loginaccount la = iLoginaccountMapper.selectOne(new QueryWrapper<Loginaccount>().eq("userid", userid));
        if (la != null) {
            resultMap.put("loginaccount", la);
        }
        Thread myThread = new Thread(new Runnable() {
            public void run() {
                try {
                    // 使用线程发送消息  延迟5秒发送, 避免数据库未写入
                    Thread.sleep(5000);
                    sendAuditMsg(resultMap);
                    if (la != null) {
                        // 登录账户变更通知 changetype = 4 修改账户权限
                        sendLoginAccChangeNtf(la.getLoginid(), 4);
                    }
                } catch (Exception ex) {
                    log.error("发送登录账号变更通知失败，失败原因：" + Arrays.toString(ex.getStackTrace()));
                }
            }
        });

        // 启动线程
        myThread.start();
    }

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

    private void sendAuditMsg(Map<String, Object> resultMap) {
        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 (int i = 0; i < ta.size(); i++) {
                iSendMsgService.sendCustomerInfo(ui, ta.get(i).getAccountid(), "1", 0);

                //发给账户服务的，用户变更通知
                iSendMsgService.sendUserChangeMsg(ta.get(i).getAccountid(), ta.get(i).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);
        }
    }

    private void addLoginTaaccount(OrganRoleModifyParam vo, Systemmanager opeartion) {
        Loginaccount la = iLoginaccountMapper.selectOne(new QueryWrapper<Loginaccount>().eq("userid", vo.getUserid()));
        Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>()
                .eq("userid", vo.getUserid())
                .eq("ismain", 1));
        if (ta != null && la != null) {
            Logintaaccount lta = iLogintaaccountMapper.selectOne(new QueryWrapper<Logintaaccount>()
                    .eq("loginid", la.getLoginid())
                    .eq("accountid", ta.getAccountid()));
            if (lta == null) {
                // 不存在则添加
                lta = new Logintaaccount();
                lta.setLoginid(la.getLoginid());
                lta.setAccountid(ta.getAccountid());
                lta.setModifytime(new Date());
                lta.setModifierid(opeartion.getAutoid());
                iLogintaaccountMapper.insert(lta);
            }
        }
    }

    private void addMarketRightToMainAccount(OrganRoleModifyParam vo, Systemmanager opeartion, List<TaAccountMarketVo> dtype) {
        //默认资金账户附上所选市场权限 0-否，1-是
        Systemparam sysparm = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("paramcode", SysConstants.SYSPARAM_CODE_ISTAACCOUNTMARKETROLE));
        if (sysparm != null && "1".equals(sysparm.getParamvalue())) {
            if (dtype != null && !dtype.isEmpty()) {
                Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>()
                        .eq("userid", vo.getUserid())
                        .eq("ismain", 1));
                //删除
                iTaaccountmarketMapper.delete(new QueryWrapper<Taaccountmarket>().eq("accountid", ta.getAccountid()));

                for (TaAccountMarketVo td : dtype) {
                    if (td != null && td.getMarketId() != null) {
                        Taaccountmarket tm = new Taaccountmarket();
                        tm.setAccountid(ta.getAccountid());
                        tm.setMarketid(td.getMarketId());
                        tm.setModifytime(new Date());
                        tm.setModifierid(opeartion.getAutoid());
                        tm.setSpotrighttype(td.getSpotRightType());
                        tm.setBuyspotrighttype(td.getDType());
                        iTaaccountmarketMapper.insert(tm);
                    }
                }
            }
        }
    }

    private void generatePCLoginAccount(OrganRoleModifyParam vo, Systemmanager opeartion) {
        Long loginid = null; //新加的登录账号ID
        Systemparam sysparm = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("paramcode", SysConstants.SYSPARAM_CODE_ISAUTOEXCUTELOGIN));
        //自营会员是否自动生成登录账户
        if (sysparm != null && "1".equals(sysparm.getParamvalue())) {
            List<Loginaccount> loginList = iLoginaccountMapper.selectList(new QueryWrapper<Loginaccount>()
                    .eq("userid", vo.getUserid())
                    .eq("loginusertype", 2));
            if (loginList.isEmpty()) {
                String defaultPwd = "123456";

                Systemparam defaultPwdParam = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("paramcode", SysConstants.SYSPARAM_CODE_DEFAULT_PWD));
                if (defaultPwdParam != null && !defaultPwdParam.getParamvalue().equals("")) {
                    defaultPwd = defaultPwdParam.getParamvalue();
                }
                //添加自营会员登录账号
                loginid = tradingAccountService.getNewLoginIdByUserid(vo.getUserid(), 2);
                Loginaccount la = new Loginaccount();
                la.setLoginfailnum(0);
                la.setLoginid(loginid);
                la.setLoginstatus(1);
                la.setLoginusertype(2);
                la.setPassword(EncryptionUtils.encryptSHA(loginid.toString() + defaultPwd));
                la.setUserid(vo.getUserid());
                la.setModifierid(opeartion.getAutoid());
                la.setModifytime(new Date());
                la.setHasupdatedpwd(0);
                iLoginaccountMapper.insert(la);
            } else {
                for (Loginaccount la : loginList) {
                    la.setLoginstatus(1);
                    iLoginaccountMapper.update(la, new QueryWrapper<Loginaccount>().eq("loginid", la.getLoginid()));
                }
            }
        }
    }

    private void addAreaRoleModifyFee(OrganRoleModifyParam vo, Systemmanager opeartion, HttpServletRequest request) {
        Arearole or = new Arearole();
        or.setCreatetime(new Date());
        or.setCreatorid(opeartion.getAutoid());
        or.setUserid(vo.getUserid());
        or.setRoletype(vo.getRoleid());
        or.setTradeaccountid(vo.getAccountid());
        or.setModifierid(opeartion.getAutoid());
        or.setModifytime(new Date());
        iArearoleMapper.insert(or);

        if (vo.getRoleid() == SysEnums.OrganRole.operate.getCode().intValue()) {
            if (CollectionUtils.isNotEmpty(vo.getMarketids())) {
                iMarketMapper.updateExchareaid(vo.getMarketids(), vo.getUserid());
                Systemparam systemparam = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_ID_MARKET));
                if (systemparam != null) {
                    systemparam.setParamvalue(String.valueOf(System.currentTimeMillis()));
                    systemparam.setUpdatetime(new Date());
                    iSystemparamMapper.update(new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_ID_MARKET));
                }
            }
        }

        //清除原数据
        iArearoledivideconfigMapper.delete(new QueryWrapper<Arearoledivideconfig>()
                .eq("userid", vo.getUserid())
                .eq("roletype", vo.getRoleid()));
        //分润
        if (vo.getFee() != null && !vo.getFee().isEmpty()) {
            int size = vo.getFee().size();
            for (int i = 0; i < size; i++) {
                Arearoledivideconfig fee = vo.getFee().get(i);
                if (fee.getTradefeeid() == null || fee.getFeealgorithm() == null ||
                        fee.getDividevalue() == null) {
                    continue;
                }
                if (fee.getFeealgorithm() == 1 && fee.getDividevalue().compareTo(new BigDecimal(100)) > 0) {
                    throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_035.getCode(), request.getHeader("Accept-Language"));
                }
                if (fee.getFeealgorithm() == 1) {
                    fee.setDividevalue(fee.getDividevalue().divide(new BigDecimal(100)));
                }
                fee.setUserid(or.getUserid());
                fee.setMarketid(0L);
                fee.setGoodsid(0L);
                fee.setRoletype(or.getRoletype());
                fee.setCreatetime(new Date());
                fee.setCreatorid(opeartion.getAutoid());
                fee.setModifytime(new Date());
                fee.setModifierid(opeartion.getAutoid());
                iArearoledivideconfigMapper.insert(fee);
            }
        }

        //商品个性化配置
        if (vo.getPfee() != null && !vo.getPfee().isEmpty()) {
            int size = vo.getPfee().size();
            for (int i = 0; i < size; i++) {
                Arearoledivideconfig fee = vo.getPfee().get(i);
                if (fee.getTradefeeid() == null || fee.getFeealgorithm() == null ||
                        fee.getDividevalue() == null) {
                    continue;
                }
                if (fee.getFeealgorithm() == 1 && fee.getDividevalue().compareTo(new BigDecimal(100)) > 0) {
                    throw new GlobalException(Constants.Error_Code_Design, MessageType.ORGAN_ERROR_CODE_035.getCode(), request.getHeader("Accept-Language"));
                }
                if (fee.getFeealgorithm() == 1) {
                    fee.setDividevalue(fee.getDividevalue().divide(new BigDecimal(100)));
                }
                fee.setUserid(or.getUserid());
                fee.setRoletype(or.getRoletype());
                fee.setCreatetime(new Date());
                fee.setCreatorid(opeartion.getAutoid());
                fee.setModifytime(new Date());
                fee.setModifierid(opeartion.getAutoid());
                iArearoledivideconfigMapper.insert(fee);
            }
        }

        String l = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "002");
        if ("2".equals(l)) {
            Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>()
                    .eq("areauserid", vo.getUserid())
                    .eq("isdefault", 1));
            if (user != null) {
                Roleuser ur = new Roleuser();
                ur.setRoleid(Long.valueOf(vo.getRoleid()));
                ur.setManagerid(user.getAutoid());
                ur.setRoletype(3);
                iRoleuserMapper.insert(ur);
            }
        }

        // 运营机构权限变更为可查询有商品权限的交易单据 2024-01-15
        updateOperateGoodsConfig(vo);
    }

    private void updateOperateGoodsConfig(OrganRoleModifyParam vo) {
        // 运营机构权限变更为可查询有商品权限的交易单据 2024-01-15
        if (vo.getRoleid().equals(2) && vo.getUserid() != null) {
            //运营机构删除商品配置表记录 AreaGoodsConfig 2024-01-15
            iArearolemarketMapper.deleteOperateGoodsConfig(vo.getUserid());

            //添加新的运营机构商品配置 AreaGoodsConfig
            if (CollectionUtils.isNotEmpty(vo.getGoodsids())) {
                List<Map<String, Object>> insertList = new ArrayList<>();
                for (Long goodsid : vo.getGoodsids()) {
                    Map<String, Object> configMap = new HashMap<>();
                    configMap.put("userid", vo.getUserid());
                    configMap.put("roletype", 2); // 运营机构
                    configMap.put("goodsid", goodsid);
                    insertList.add(configMap);
                }
                iArearolemarketMapper.insertOperateGoodsConfigBatch(insertList);
            }
        }
    }

    private void sendMsg(Taaccount ta, Integer type) {
        NotifyMI1.UserChangeNtf.Builder builder = NotifyMI1.UserChangeNtf.newBuilder();
        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        PublicMI1.NotifyHead.Builder nhd = PublicMI1.NotifyHead.newBuilder();
        NotifyMI1.AccountDataChange.Builder ac = NotifyMI1.AccountDataChange.newBuilder();

        nhd.addAccountIDs(ta.getAccountid());
        nhd.setNtfMode(0);
        builder.setNtfHeader(nhd);

        hd.setAccountID(ta.getAccountid());
        hd.setFunCode(FunCodeConstants.FunCode_Trade_UserChangeNtf);
        hd.setClientTime(System.currentTimeMillis());
        builder.setHeader(hd);

        ac.setAccountId(ta.getAccountid());
        ac.setChangeType(type);
        builder.addAccountChange(ac);

        builder.setUserId(ta.getUserid());
        builder.setChangeType(type);

        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(), FunCodeConstants.FunCode_Trade_UserChangeNtf);
        rabbitTemplate.send(SysConstants.RabbitNtfKey, new Message(body, new MessageProperties()));
        log.debug("edit account----{}", builder.build().toString());
    }

    private void getRiskFromRedis(List<TaAccountQueryResult> records) {
        try {
            for (TaAccountQueryResult record : records) {
                byte[] valuebts = redisServiceUtil.getBytes("risk:" + record.getAccountId());
                AccountRedis.AccRiskInfo accRiskInfo = null;
                if (valuebts != null) {
                    accRiskInfo = AccountRedis.AccRiskInfo.newBuilder().mergeFrom(valuebts).build();
                    log.info("risk:" + record.getAccountId() + "--------------accRiskInfo:" + accRiskInfo);
                    record.setCurRiskRate(BigDecimal.valueOf(accRiskInfo.getCURRISKRATE()).multiply(BigDecimal.valueOf(100d)).setScale(2, RoundingMode.DOWN));
                } else {
                    // Redis无记录，风险率、浮动盈亏设置为0
                    record.setCurRiskRate(BigDecimal.ZERO);
                }
            }
        } catch (Exception e) {
            log.error("设置风险率失败，请检查！" + Arrays.toString(e.getStackTrace()));
        }
    }

    private void setReadOnly(Long userid) {
        //查询会员默认管理端,改回正常
        Systemmanager manage = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>()
                .eq("areauserid", userid)
                .eq("isdefault", 1));
        manage.setManagerstatus(1);
        iSystemmanagerMapper.update(manage, new QueryWrapper<Systemmanager>().eq("autoid", manage.getAutoid()));
        //替换掉对应的角色
        List<Roleuser> ullist = iRoleuserMapper.selectList(new QueryWrapper<Roleuser>().eq("managerid", manage.getAutoid()));
        for (Roleuser ul : ullist) {
            Roleuser nul = new Roleuser();
            if (ul.getRoleid() == 2) {
                nul.setRoleid(32L);
            } else if (ul.getRoleid() == 3) {
                nul.setRoleid(33L);
            } else if (ul.getRoleid() == 4) {
                nul.setRoleid(34L);
            } else if (ul.getRoleid() == 5) {
                nul.setRoleid(35L);
            } else if (ul.getRoleid() == 6) {
                nul.setRoleid(36L);
            } else if (ul.getRoleid() == 7) {
                nul.setRoleid(37L);
            } else if (ul.getRoleid() == 8) {
                nul.setRoleid(38L);
            } else if (ul.getRoleid() == 9) {
                nul.setRoleid(39L);
            } else if (ul.getRoleid() == 10) {
                nul.setRoleid(40L);
            } else if (ul.getRoleid() == 11) {
                nul.setRoleid(41L);
            } else if (ul.getRoleid() == 13) {
                nul.setRoleid(43L);
            } else if (ul.getRoleid() == 14) {
                nul.setRoleid(44L);
            } else if (ul.getRoleid() == 15) {
                nul.setRoleid(45L);
            }
            if (nul.getRoleid() != null && nul.getRoleid() > 0) {
                nul.setManagerid(ul.getManagerid());
                nul.setRoletype(ul.getRoletype());
                iRoleuserMapper.delete(new QueryWrapper<Roleuser>()
                        .eq("managerid", ul.getManagerid())
                        .eq("roleid", ul.getRoleid())
                        .eq("roletype", ul.getRoletype())
                );
                iRoleuserMapper.insert(nul);
            }
        }
    }


    private void setRoleBack(Long userid) {
        //查询会员默认管理端,改回正常
        Systemmanager manage = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>()
                .eq("areauserid", userid)
                .eq("isdefault", 1));
        manage.setManagerstatus(1);
        iSystemmanagerMapper.update(manage, new QueryWrapper<Systemmanager>().eq("autoid", manage.getAutoid()));
        //替换掉对应的角色
        List<Roleuser> ullist = iRoleuserMapper.selectList(new QueryWrapper<Roleuser>().eq("managerid", manage.getAutoid()));
        for (Roleuser ul : ullist) {
            Roleuser nul = new Roleuser();
            if (ul.getRoleid() == 32) {
                nul.setRoleid(2L);
            } else if (ul.getRoleid() == 33) {
                nul.setRoleid(3L);
            } else if (ul.getRoleid() == 34) {
                nul.setRoleid(4L);
            } else if (ul.getRoleid() == 35) {
                nul.setRoleid(5L);
            } else if (ul.getRoleid() == 36) {
                nul.setRoleid(6L);
            } else if (ul.getRoleid() == 37) {
                nul.setRoleid(7L);
            } else if (ul.getRoleid() == 38) {
                nul.setRoleid(8L);
            } else if (ul.getRoleid() == 39) {
                nul.setRoleid(9L);
            } else if (ul.getRoleid() == 40) {
                nul.setRoleid(10L);
            } else if (ul.getRoleid() == 41) {
                nul.setRoleid(11L);
            } else if (ul.getRoleid() == 43) {
                nul.setRoleid(13L);
            } else if (ul.getRoleid() == 44) {
                nul.setRoleid(14L);
            } else if (ul.getRoleid() == 45) {
                nul.setRoleid(15L);
            }
            if (nul.getRoleid() != null && nul.getRoleid() > 0) {
                nul.setManagerid(ul.getManagerid());
                nul.setRoletype(ul.getRoletype());
                iRoleuserMapper.delete(new QueryWrapper<Roleuser>()
                        .eq("managerid", ul.getManagerid())
                        .eq("roleid", ul.getRoleid())
                        .eq("roletype", ul.getRoletype())
                );
                iRoleuserMapper.insert(nul);
            }
        }
    }
}
