package com.ytpm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytpm.agent.enums.UserStatusEnum;
import com.ytpm.agent.model.YtApp;
import com.ytpm.agent.model.YtPlatformBanned;
import com.ytpm.agent.model.YtPlatformDeblocking;
import com.ytpm.agent.model.YtPlatformUserApp;
import com.ytpm.agent.view.AgentAppClassView;
import com.ytpm.agent.view.AgentEnableAppView;
import com.ytpm.agent.view.AgentUserInfo;
import com.ytpm.app.model.YtDyzLoginRecord;
import com.ytpm.app.model.YtDyzUser;
import com.ytpm.app.param.AppUserParam;
import com.ytpm.custom.CustomField;
import com.ytpm.dao.AgentAppMapper;
import com.ytpm.dao.AgentDictMapper;
import com.ytpm.dao.AppMapper;
import com.ytpm.dao.RiskMapper;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.handle.CustomerException;
import com.ytpm.risk.enums.BannedTypeEnum;
import com.ytpm.risk.model.YtRiskConfig;
import com.ytpm.risk.model.YtRiskTemplate;
import com.ytpm.risk.model.YtRiskTemplateLog;
import com.ytpm.risk.param.RiskBannedListParam;
import com.ytpm.risk.param.RiskBannedParam;
import com.ytpm.risk.param.RiskConfigListParam;
import com.ytpm.risk.param.RiskConfigParam;
import com.ytpm.risk.param.RiskDeblockingListParam;
import com.ytpm.risk.param.RiskRelativeAppParam;
import com.ytpm.risk.param.RiskUserStatusParam;
import com.ytpm.risk.view.RiskBannedListView;
import com.ytpm.risk.view.RiskConfigListView;
import com.ytpm.risk.view.RiskConfigView;
import com.ytpm.risk.view.RiskDeblockingListView;
import com.ytpm.risk.view.RiskTemplateView;
import com.ytpm.service.RiskService;
import com.ytpm.util.RedisService;
import com.ytpm.utils.FeignClientInvoker;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Marx
 * @date 2025/8/19 9:56
 */
@Slf4j(topic = "RiskService")
@Service
public class RiskServiceImpl implements RiskService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private RiskMapper riskMapper;
    @Autowired
    private AgentAppMapper agentAppMapper;
    @Resource
    private AppMapper appMapper;
    @Autowired
    private AgentDictMapper dictMapper;
    @Autowired
    private FeignClientInvoker feignInvoker;

    /**
     * 风控锁定用户
     */
    @Override
    public Result<?> lockUser(AgentUserInfo curUser, String userId, String appId) {
        redisService.setTimeOutStr("lock_"+userId,appId,1000);
        addBannedRecord(userId,curUser,appId,24,BannedTypeEnum.CHANNEL.getDesc()+"禁止登录");
        return Result.resultOk(RepMessage.LOCK_USER_SUCCESS);
    }

    /**
     * 风控封禁用户
     */
    @Override
    public Result<?> banned(RiskBannedParam param,AgentUserInfo curUser) {
        redisService.setTimeOutStr("lock_"+param.getUserId(),param.getAppId(),1000);
        addBannedRecord(param.getUserId(),curUser,param.getAppId(),param.getBannedLimit()*24,param.getBannedReason());
        //预设24小时过期key 用于解锁用户
        redisService.setTimeOutHoursStr("unlock_"+param.getUserId(),param.getAppId(),param.getBannedLimit() * 24L);
        return Result.resultOk(RepMessage.ALREADY_RISK_USER);
    }

    /**
     * 风控批量封禁用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> batchBanned(RiskBannedParam param,AgentUserInfo curUser) {
        if(StrUtil.isBlank(param.getUserIds())){
            return Result.resultErr("请选择封禁用户");
        }
        List<String> userIds = Arrays.asList(param.getUserIds().split(","));
        // 母包封禁
        if (param.getIfSuperiorBanned() != null && param.getIfSuperiorBanned() == 1) {
            YtApp ytApp = appMapper.selectPrimary(param.getAppId());
            YtPlatformUserApp platformUserApp = ytApp == null ? null : agentAppMapper.selectByPrimaryKey(ytApp.getSuperiorId());
            if (platformUserApp != null) {
                Object obj = feignInvoker.invoke(platformUserApp.getServiceName(), "queryAllDitchUser",
                        param.getUserIds());
                if (obj != null) {
                    List<YtDyzUser> dyzUsers = JSONArray.parseArray(JSON.toJSONString(obj), YtDyzUser.class);
                    userIds = dyzUsers.stream()
                            .filter(user-> UserStatusEnum.NORMAL.getCode().equals(user.getUserStatus()))
                            .map(YtDyzUser::getUserId).collect(Collectors.toList());
                }
            }
        }
        for (String userId : userIds) { // 为避免大量解锁的key再同一时间过期， 这里采用随机数
            redisService.setTimeOutStr("lock_"+userId,param.getAppId(),RandomUtil.randomInt(500, 2000));
            addBannedRecord(userId,curUser,param.getAppId(),param.getBannedLimit()*24, param.getBannedReason());
            //预设20-24小时过期key 用于解锁用户
            redisService.setTimeOutHoursStr("unlock_"+userId,param.getAppId(),param.getBannedLimit() * RandomUtil.randomLong(20, 24));
        }
        return Result.resultOk(RepMessage.ALREADY_RISK_USER);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> batchBannedByIps(RiskBannedParam param,AgentUserInfo curUser){
        if (StrUtil.isEmpty(param.getBannedIps())) {
            return Result.resultErr("请输入封禁IP");
        }
        if (StrUtil.isEmpty(param.getAppId())) {
            return Result.resultErr("appId为空");
        }
        List<String> userIds = new ArrayList<>();
        YtApp ytApp = appMapper.selectPrimary(param.getAppId());
        YtPlatformUserApp platformUserApp = ytApp == null ? null : agentAppMapper.selectByPrimaryKey(ytApp.getSuperiorId());
        if (platformUserApp != null) {
            Object obj = feignInvoker.invoke(platformUserApp.getServiceName(), "queryAllUserByIps",
                    param.getAppId(), param.getBannedIps());
            if (obj != null) {
                List<YtDyzUser> dyzUsers = JSONArray.parseArray(JSON.toJSONString(obj), YtDyzUser.class);
                userIds = dyzUsers.stream()
                        .filter(user-> UserStatusEnum.NORMAL.getCode().equals(user.getUserStatus()))
                        .map(YtDyzUser::getUserId).collect(Collectors.toList());
            }
        }
        if(CollUtil.isNotEmpty(userIds)){
            for (String userId : userIds) {
                redisService.setTimeOutStr("lock_"+userId,param.getAppId(),RandomUtil.randomInt(500, 2000));
                addBannedRecord(userId,curUser,param.getAppId(),param.getBannedLimit()*24, param.getBannedReason());
                //预设20-24小时过期key 用于解锁用户
                redisService.setTimeOutHoursStr("unlock_"+userId,param.getAppId(),param.getBannedLimit() * RandomUtil.randomLong(20, 24));
            }
        }
        return Result.resultOk(RepMessage.ALREADY_RISK_USER);
    }

    /**
     * 批量解禁用户
     */
    @Override
    public Result<?> batchDeblock(RiskDeblockingListParam param, AgentUserInfo curUser) {
        if(StrUtil.isBlank(param.getUserIds())){
            return Result.resultErr("请选择解禁用户");
        }
        String[] split = param.getUserIds().split(",");
        RiskUserStatusParam riskUserStatusParam;
        for (String userId : split) {
            //批量解封用户并增加解封记录
            redisService.setTimeOutStr("unlock_"+userId,param.getAppId(),RandomUtil.randomInt(500, 2000));
            YtPlatformBanned lastBanned = riskMapper.getLastBanned(userId);
            riskUserStatusParam = new RiskUserStatusParam();
            riskUserStatusParam.setAgentId(curUser.getUserId());
            riskUserStatusParam.setOperator(curUser.getUserId());
            riskUserStatusParam.setOperatorName(curUser.getNickName());
            riskUserStatusParam.setReason(param.getDeblockingReason());
            addDeblockingRecord(lastBanned,riskUserStatusParam);
            //查询用户id 在redis中是否存在未处理的 lock_ 清除掉
            redisService.del("lock_"+userId);
        }
        return Result.resultOk(RepMessage.PROCESS_SUCCESS);
    }

    /**
     * 风控配置列表
     */
    @Override
    public ResultTable<RiskConfigListView> getConfigList(RiskConfigParam param) {
        PageHelper.startPage(param.getPage(),param.getLimit());
        return ResultTable.resultTableOk(new PageInfo<RiskConfigListView>(riskMapper.getRiskConfigList(param)));
    }

    /**
     * 查询封禁记录
     */
    @Override
    public ResultTable<RiskBannedListView> bannedList(RiskBannedListParam param) {
        PageHelper.startPage(param.getPage(),param.getLimit());
        List<RiskBannedListView> bannedList = riskMapper.getBannedList(param);
        if(CollUtil.isNotEmpty(bannedList)){
            List<YtPlatformUserApp> issuedAppList = agentAppMapper.getIssuedAppList(param.getAgentId());
            if(CollUtil.isEmpty(issuedAppList)){
                return ResultTable.resultTableOk(new PageInfo<>(bannedList));
            }

            String userIds = bannedList.stream().map(
                    RiskBannedListView::getUserId).distinct().collect(Collectors.joining(","));
            AppUserParam appUserParam = new AppUserParam();
            appUserParam.setUserIds(userIds);
            List<YtDyzUser> data = dealWithFeignData(issuedAppList,appUserParam);
            setBannedLoginInfo(bannedList,data);
        }
        return ResultTable.resultTableOk(new PageInfo<RiskBannedListView>(bannedList));
    }

    /**
     * 查询解封记录
     */
    @Override
    public ResultTable<RiskDeblockingListView> deblockingList(RiskDeblockingListParam param) {
        PageHelper.startPage(param.getPage(),param.getLimit());
        List<RiskDeblockingListView> deblockingList = riskMapper.getDeblockingList(param);
        if(CollUtil.isNotEmpty(deblockingList)){
            List<YtPlatformUserApp> issuedAppList = agentAppMapper.getIssuedAppList(param.getAgentId());
            if(CollUtil.isEmpty(issuedAppList)){
                return ResultTable.resultTableOk(new PageInfo<>(deblockingList));
            }
            String userIds = deblockingList.stream().map(
                    RiskDeblockingListView::getUserId).distinct().collect(Collectors.joining(","));
            AppUserParam appUserParam = new AppUserParam();
            appUserParam.setUserIds(userIds);
            appUserParam.setLoginTimeBegin(param.getLoginTimeBegin());
            appUserParam.setLoginTimeEnd(param.getLoginTimeEnd());
            List<YtDyzUser> data = dealWithFeignData(issuedAppList,appUserParam);
            setDeblockLoginInfo(deblockingList,data);
        }
        return ResultTable.resultTableOk(new PageInfo<>(deblockingList));
    }

    /**
     * 修改用户风控状态
     */
    @Override
    public Result<?> changeUserStatus(RiskUserStatusParam param, AgentUserInfo curUser) {
        //如果原账号状态正常且本次操作状态不正常
        modifyAppUserInfo(param.getUserId(),param,curUser);
        return Result.resultOk(RepMessage.USER_STATUS_MODIFY);
    }

    /**
     * 风控配置关联应用
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> relativeApp(RiskRelativeAppParam param) {
        List<AgentEnableAppView> appList = param.getAppList();
        if(CollUtil.isEmpty(appList)){
            return Result.resultErr(RepMessage.COLLECTION_EMPTY);
        }
        riskMapper.deleteRelatives(param.getTemplateId());
        riskMapper.relativeApps(param);
        return Result.resultOk(RepMessage.RELATIVE_APP_SUCCESS);
    }
    /**
     * 风控配置保存
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> saveConfig(RiskConfigParam param) {
        List<RiskConfigListParam> configList = param.getConfigList();
        if(CollUtil.isEmpty(param.getConfigList())){
            return Result.resultErr(RepMessage.COLLECTION_EMPTY);
        }
        List<YtRiskConfig> configs = new ArrayList<>();
        YtRiskConfig config;
        StringBuilder content = new StringBuilder();
        for (RiskConfigListParam listVO : configList) {
            listVO.setConfigId(IdUtil.fastSimpleUUID());
            config = new YtRiskConfig();
            BeanUtil.copyProperties(listVO, config);
            config.setChannelId(param.getChannelId());
            String format = String.format(config.getFieldDesc(), config.getConfigVal());
            if(CharSequenceUtil.isNotBlank(format)){
                content.append(format);
                if(configList.indexOf(listVO)!= (configList.size() - 1)){
                    content.append(",");
                }
            }
            configs.add(config);
        }
        riskMapper.batchInsertConfig(configs);
        addTemplateAndRelative(param,content.toString(),configs);
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }
    /**
     * 风控配置修改
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> updateConfig(RiskConfigParam param) {
        YtRiskTemplate old = riskMapper.selectOneTemplate(param.getTemplateId());
        if(Objects.isNull(old)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        // 获取原有配置信息
        List<YtRiskConfig> configs = riskMapper.selectRiskConfig(param.getTemplateId());
        Map<String, String> valueMap = configs.stream().collect(Collectors.toMap(
                YtRiskConfig::getConfigId, YtRiskConfig::getConfigVal,
                (o1, o2) -> o2));
        //修改配置值
        List<RiskConfigListParam> configList = param.getConfigList();
        StringBuilder content = new StringBuilder();
        List<YtRiskTemplateLog> logs = new ArrayList<>();
        for (RiskConfigListParam listParam : configList) {
            YtRiskConfig config = new YtRiskConfig();
            config.setConfigId(listParam.getConfigId());
            config.setConfigVal(listParam.getConfigVal());
            riskMapper.updateConfigVal(config);
            String format = String.format(listParam.getFieldDesc(), listParam.getConfigVal());
            if(CharSequenceUtil.isNotBlank(format)){
                content.append(format).append(",");
            }
            String oldValue = valueMap.get(listParam.getConfigId());
            if (!StrUtil.emptyIfNull(oldValue).equals(StrUtil.emptyIfNull(listParam.getConfigVal()))) {
                YtRiskTemplateLog log = new YtRiskTemplateLog();;
                log.setTemplateId(old.getTemplateId());
                log.setTemplateCode(old.getTemplateCode());
                log.setConfigId(listParam.getConfigId());
                log.setOldValue(oldValue);
                log.setNewValue(listParam.getConfigVal());
                log.setOperator(param.getChannelId());
                log.setOperatorName(param.getOperatorName());
                logs.add(log);
            }
        }
        //同步修改配置模版内容
        YtRiskTemplate template = new YtRiskTemplate();
        BeanUtil.copyProperties(param,template);
        template.setTemplateContent(content.toString());
        template.setUpdateTime(new Date());
        template.setUpdateUserId(param.getChannelId());
        riskMapper.updateByTempId(template);
        if (CollUtil.isNotEmpty(logs)) {
            riskMapper.addRiskTemplateLog(logs);
        }
        return Result.resultOk(RepMessage.MODIFY_SUCCESS);
    }

    /**
     * 风控配置字段选项
     */
    @Override
    public ResultTable<RiskConfigView> getRiskConfig(String appIds) {
        List<AgentAppClassView> viewList = riskMapper.getAppClazz(appIds);
        List<RiskConfigView> configList = new ArrayList<>();
        try{
            for (AgentAppClassView view : viewList) {
                addConfigItem(Class.forName(view.getFullName()).getDeclaredFields(),configList,null);
            }
        }catch (Exception e){
            log.error(e.getMessage());
            throw new CustomerException(e.getMessage());
        }
        return ResultTable.resultTableOk(new PageInfo<RiskConfigView>(configList));
    }

    /**
     * 风控配置启用关闭
     */
    @Override
    public Result<?> isEnabledConfig(String templateId, String userId) {
        YtRiskTemplate template = riskMapper.selectOneTemplate(templateId);
        if(Objects.isNull(template)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        Integer enabled = template.getEnabled();

        YtRiskTemplate newTemp = new YtRiskTemplate();
        newTemp.setTemplateId(templateId);
        newTemp.setUpdateUserId(userId);
        newTemp.setUpdateTime(new Date());
        newTemp.setEnabled(enabled == 0?1:0);
        riskMapper.updateByTempId(newTemp);
        if (!Objects.equals(newTemp.getEnabled(), template.getEnabled())) {
            // 风控启用或关闭 增加日志记录
            YtRiskTemplateLog log = new YtRiskTemplateLog();
            log.setTemplateId(templateId);
            log.setTemplateCode(template.getTemplateCode());
            log.setConfigId("enabled");
            log.setOldValue(template.getEnabled().toString());
            log.setNewValue(newTemp.getEnabled().toString());
            log.setOperator(newTemp.getChannelId());
            log.setOperatorName(newTemp.getChannelId());
            riskMapper.addRiskTemplateLog(Collections.singletonList(log));
        }
        return Result.resultOk(RepMessage.MODIFY_SUCCESS);
    }
    /**
     * 风控配置模版详情
     */
    @Override
    public Result<RiskTemplateView> templateView(String templateId, String channelId) {
        return Result.resultObjOk(riskMapper.getTemplateView(templateId,channelId));
    }

    /**
     * 根据业务节点查询配置项
     */
    @Override
    public ResultTable<RiskConfigView> getFieldConfigByNode(Integer effectNode) {
        List<AgentAppClassView> viewList = riskMapper.getAppClazz("");
        List<RiskConfigView> configList = new ArrayList<>();
        Set<String> clazzSet = viewList.stream().map(AgentAppClassView::getFullName).collect(Collectors.toSet());
        try{
            for (String fullName : clazzSet) {
                addConfigItem(Class.forName(fullName).getDeclaredFields(),configList,effectNode);
            }
        }catch (Exception e){
            log.error(e.getMessage());
            throw new CustomerException(e.getMessage());
        }
        return ResultTable.resultTableOk(new PageInfo<RiskConfigView>(configList));
    }

    /**
     * 添加配置项
     */
    private void addConfigItem(Field[] fields, List<RiskConfigView> configList, Integer effectNode) {
        RiskConfigView view;
        for (Field field : fields) {
            field.setAccessible(true);
            if((Objects.nonNull(effectNode) && field.getAnnotation(CustomField.class).node()!=99 &&
                    field.getAnnotation(CustomField.class).node() != effectNode)||
                    !field.isAnnotationPresent(CustomField.class)
            )continue;
            view = new RiskConfigView();
            view.setFieldName(field.getName());
            if(CharSequenceUtil.isNotBlank(field.getAnnotation(CustomField.class).value())){
                view.setDictList(dictMapper.getByTypeCode(field.getAnnotation(CustomField.class).value()));
            }
            view.setFieldDesc(field.getAnnotation(ApiModelProperty.class).value());
            configList.add(view);
        }
    }
    /**
     * 新增模版和关联配置
     */
    private void addTemplateAndRelative(RiskConfigParam param,String content,List<YtRiskConfig> configs) {
        YtRiskTemplate template = new YtRiskTemplate();
        BeanUtil.copyProperties(param,template);
        template.setTemplateId(IdUtil.fastSimpleUUID());
        template.setTemplateContent(content);
        template.setEnabled(0);
        template.setCreateUserId(param.getChannelId());
        template.setCreateTime(new Date());
        riskMapper.saveTemplate(template);
        riskMapper.addRelease(template.getTemplateId(),
                configs.stream().map(YtRiskConfig::getConfigId).collect(Collectors.toList()),
                param.getOperator(),param.getOperatorName()
        );
    }
    /**
     * 修改用户信息
     */
    private void modifyAppUserInfo(String userId, RiskUserStatusParam param, AgentUserInfo curUser) {
        YtDyzUser appUser = new YtDyzUser();
        appUser.setUserId(param.getUserId());
        appUser.setUserStatus(param.getUserStatus());
        switch (param.getUserStatus()){
            case 2:
                appUser.setRiskReason(param.getReason());
                //1s锁定用户，并设置 24小时后进行解锁
                redisService.setTimeOutStr("lock_"+userId,param.getAppId(),1000);
                redisService.setTimeOutHoursStr("unlock_"+userId,param.getAppId(),24);
                break;
            case 3: //增加封禁记录
                appUser.setRiskReason(param.getReason());
                addBannedRecord(userId,curUser,param.getAppId(),param.getBannedLimit()*24, param.getReason());
                //1s锁定用户，并设置 24小时后进行解锁
                redisService.setTimeOutStr("lock_"+userId,param.getAppId(),1000);
                redisService.setTimeOutHoursStr("unlock_"+userId,param.getAppId(),param.getBannedLimit()*24L);
                break;
            default: //解禁
                YtPlatformBanned banned = riskMapper.getLastBanned(userId);
                if(Objects.nonNull(banned)){
                    addDeblockingRecord(banned,param);
                }
                redisService.setTimeOutStr("unlock_"+userId,param.getAppId(),1000);
        }
    }
    /**
     * 根据应用远程调用获取数据
     */
    private List<YtDyzUser> dealWithFeignData(List<YtPlatformUserApp> issuedAppList, AppUserParam appUserParam) {
        List<YtDyzUser> data = new ArrayList<>();
        List<String> collect = issuedAppList.stream().map(YtPlatformUserApp::getServiceName).distinct().collect(Collectors.toList());
        for (String serviceName : collect) {
            Object o = feignInvoker.invoke(serviceName, "getUserList", appUserParam);
            String jsonString = JSON.toJSONString(o);
            JSONObject object = JSONObject.parseObject(jsonString);
            List<YtDyzUser> dyzUsers = JSONArray.parseArray(object.getString("data"), YtDyzUser.class);
            if(CollUtil.isNotEmpty(dyzUsers)){
                data.addAll(dyzUsers.stream().distinct().collect(Collectors.toList()));
            }
        }
        return data;
    }

    /**
     * 增加解禁记录
     */
    private void addDeblockingRecord(YtPlatformBanned banned, RiskUserStatusParam param) {
        YtPlatformDeblocking deblocking = new YtPlatformDeblocking();
        deblocking.setDeblockingId(IdUtil.fastSimpleUUID());
        deblocking.setUserId(banned.getUserId());
        deblocking.setAppId(banned.getAppId());
        deblocking.setAgentId(param.getAgentId());
        deblocking.setOperator(param.getOperator());
        deblocking.setOperatorName(param.getOperatorName());
        deblocking.setBannedId(banned.getBannedId());
        deblocking.setDeblockingReason(param.getReason());
        deblocking.setDeblockingTime(new Date());
        riskMapper.addDeblockingRecord(deblocking);
    }

    /**
     * 设置解封用户信息
     */
    private void setDeblockLoginInfo(List<RiskDeblockingListView> deblockingList,List<YtDyzUser> data) {
        Map<String, YtDyzUser> collect = data.stream().collect(Collectors.toMap(YtDyzUser::getUserId, o->o));
        for (RiskDeblockingListView view : deblockingList) {
            if(!collect.containsKey(view.getUserId()))continue;
            YtDyzUser dyzUser = collect.get(view.getUserId());
            view.setPlatformId(dyzUser.getPlatformId());
            view.setChannelId(dyzUser.getUserId());
            view.setUserId(dyzUser.getUserId());
            view.setNickName(dyzUser.getNickName());
            view.setRegistryTime(dyzUser.getRegistryTime());
            view.setLastLoginTime(dyzUser.getLastLoginTime());
            view.setUserStatus(dyzUser.getUserStatus());
        }
    }
    /**
     * 设置封禁用户信息
     */
    private void setBannedLoginInfo(List<RiskBannedListView> bannedList, List<YtDyzUser> data) {
        Map<String, YtDyzUser> collectMap = data.stream().collect(Collectors.toMap(
                item-> StrUtil.format("{}_{}", item.getAppId(), item.getUserId()), o -> o));
        for (RiskBannedListView view : bannedList) {
            String key = StrUtil.format("{}_{}", view.getAppId(), view.getUserId());
            if(!collectMap.containsKey(key))continue;
            YtDyzUser dyzUser = collectMap.get(key);
            List<YtDyzLoginRecord> recordList = dyzUser.getLoginRecordList();
            if(CollUtil.isNotEmpty(recordList)){
                view.setPhoneModel(recordList.get(0).getDeviceModel());
                view.setPhoneBrand(recordList.get(0).getDeviceBrand());
                view.setIpAddr(recordList.get(0).getIpAddr());
                view.setCommunicationOperator(recordList.get(0).getOperator());
            }
            view.setPlatformId(dyzUser.getPlatformId());
            view.setChannelId(dyzUser.getUserId());
            view.setUserId(dyzUser.getUserId());
            view.setNickName(dyzUser.getNickName());
            view.setRegistryTime(dyzUser.getRegistryTime());
            view.setLastLoginIp(dyzUser.getLastLoginIp());
            view.setLastLoginTime(dyzUser.getLastLoginTime());
            view.setUserStatus(dyzUser.getUserStatus());
        }
    }

    /**
     * 增加封禁记录
     */
    private void addBannedRecord(String userId, AgentUserInfo curUser,String appId,Integer limit,String bannedReason) {
        YtPlatformBanned banned = new YtPlatformBanned();
        banned.setBannedId(IdUtil.fastSimpleUUID());
        banned.setUserId(userId);
        banned.setAppId(curUser.getUserId());
        banned.setAgentId(curUser.getUserId());
        banned.setBannedLimit(limit);
        banned.setBannedReason(bannedReason);
        banned.setBannedType(BannedTypeEnum.CHANNEL.getCode());
        banned.setBannedTime(new Date());
        banned.setOperator(curUser.getUserId());
        banned.setOperatorName(curUser.getNickName());
        banned.setAppId(appId);
        riskMapper.addBannedRecord(banned);
    }
}
