package com.ytpm.lemonios.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytpm.advertise.enums.AdSourceTypeEnum;
import com.ytpm.agent.enums.AdRecordEnum;
import com.ytpm.agent.enums.UserStatusEnum;
import com.ytpm.agent.param.AdRecordListParam;
import com.ytpm.agent.param.AuditCheckParam;
import com.ytpm.agent.param.AuditUserParam;
import com.ytpm.agent.view.AgentAuditCheckVO;
import com.ytpm.annotation.ApiEncrypt;
import com.ytpm.annotation.Internal;
import com.ytpm.app.model.YtDyzAdRecord;
import com.ytpm.app.model.YtDyzAnswerRecord;
import com.ytpm.app.model.YtDyzLoginRecord;
import com.ytpm.app.model.YtDyzUser;
import com.ytpm.app.param.AppQueryUserTodayTimeParam;
import com.ytpm.app.param.AppUserParam;
import com.ytpm.app.param.AppUserQueryParam;
import com.ytpm.app.param.AppUserTodayBannedParam;
import com.ytpm.app.param.LoginRiskYtDyzUserParam;
import com.ytpm.app.param.YtAppUserListParam;
import com.ytpm.app.view.*;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.lemonios.dao.AdRecordMapper;
import com.ytpm.lemonios.dao.AppUserMapper;
import com.ytpm.lemonios.dao.LoginRecordMapper;
import com.ytpm.lemonios.dao.QuestionMapper;
import com.ytpm.lemonios.redis.RedisService;
import com.ytpm.risk.enums.BannedTypeEnum;
import com.ytpm.risk.view.RiskConfigView;
import com.ytpm.risk.view.RiskTemplateView;
import com.ytpm.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private LoginRecordMapper loginRecordMapper;
    @Autowired
    private AdRecordMapper adRecordMapper;
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private RedisService redisService;
    /**
     * 根据应用ID查询当月注册用户
     */

    @GetMapping("/getMonthRegistryUser")
    public List<YtDyzUser> getMonthRegistryUser(@RequestParam("appIds")String appIds, @RequestParam("type")Integer type) {
        return appUserMapper.getMonthRegistryUser(appIds,type);
    }
    /**
     * 查询app 所有玩家
     *  汇聚分库应用
     */

    @PostMapping("/queryAll")
    public ResultTable<YtAppUserListView> queryAll(@RequestBody YtAppUserListParam param) {
        //查询主应用
        PageHelper.startPage(param.getPage(), param.getLimit());
        List<YtAppUserListView> result = appUserMapper.queryAll(param);
        setUserExtInfo(result,param);
        return ResultTable.resultTableOk(new PageInfo<>(result));
    }

    /**
     * 记录用户额外信息<br>
     * 1.查询用户过往登陆信息<br>
     * 2.查询并计算用户当日收益、当日视频播放数、前三日收益<br>
     */
    private void setUserExtInfo(List<YtAppUserListView> result,YtAppUserListParam param) {
        Date currentDate = new Date();
        String userIds = result.stream().map(YtAppUserListView::getUserId).collect(Collectors.joining(","));
        List<YtDyzAdRecord> adRecords = adRecordMapper.getByUserIds(userIds);
        List<YtDyzLoginRecord> dyzLogins = loginRecordMapper.getLoginRecordByIds(userIds);
        List<YtDyzAnswerRecord> answerRecords = questionMapper.getAnswerRecordsByIds(userIds,
                DateUtil.beginOfDay(currentDate), DateUtil.endOfDay(currentDate));
        Map<String, List<YtDyzAdRecord>> userAdMap = adRecords.stream()
                .collect(Collectors.groupingBy(YtDyzAdRecord::getUserId));
        // 筛选查询游客广告记录
        Map<String, List<YtDyzAdRecord>> userVisitorAdMap = adRecords.stream()
                .filter(item -> AdRecordEnum.LOGIN_BEFORE.getCode().equals(item.getLoginStatus()))
                .collect(Collectors.groupingBy(YtDyzAdRecord::getUserId));
        Map<String, List<YtDyzLoginRecord>> loginMap = dyzLogins.stream()
                .collect(Collectors.groupingBy(YtDyzLoginRecord::getUserId));
        // 今日答题记录
        Map<String, Long> todayAnswerMap = answerRecords.stream().collect(
                Collectors.groupingBy(YtDyzAnswerRecord::getUserId, Collectors.counting()));
        Map<String, Long> ipAdRecordMap = new HashMap<>();
        // 查询该IP是否有激励视频已达要求的用户
        if (StrUtil.isNotEmpty(param.getLastLoginIp()) && param.getVideoThreshold() != null) {
            ipAdRecordMap = adRecordMapper.queryGroupByIpSourceType(param)
                    .stream().collect(Collectors.toMap(IpAdRecordView::getUserId, IpAdRecordView::getAdCount,
                            (o1, o2) -> o2));
        }
        for (YtAppUserListView user : result) {
            if (loginMap.containsKey(user.getUserId())) {
                user.setLoginRecordList(loginMap.get(user.getUserId()));
            }
            computeTodayIncome(user, userAdMap.get(user.getUserId()), param);
            // 由于ios服务端 总收益字段未累加游客广告收益，手动查询并累加至用户总收益
            List<YtDyzAdRecord> visitorAdList = userVisitorAdMap.get(user.getUserId());
            if (CollUtil.isNotEmpty(visitorAdList)) {
                BigDecimal totalVisitorRevenue = visitorAdList.stream().map(YtDyzAdRecord::getRevenue)
                        .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                user.setTotalIncome(user.getTotalIncome() == null ? totalVisitorRevenue : user.getTotalIncome().add(totalVisitorRevenue));
                if (user.getNearlyBeginTime() != null) {
                    BigDecimal nearlyRevenue = visitorAdList.stream()
                            .filter(item-> DateUtil.parseDate(item.getFinishTime()).before(user.getNearlyBeginTime()))
                            .map(YtDyzAdRecord::getRevenue).filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    user.setNearlyIncome(user.getNearlyIncome() == null ? nearlyRevenue : user.getNearlyIncome().add(nearlyRevenue));
                }
            }
            user.setMaybeDone(0);
            user.setTodayAnswer(Math.toIntExact(todayAnswerMap.getOrDefault(user.getUserId(), 0L)));
            if (StrUtil.equals(param.getLastLoginIp(), user.getLastLoginIp()) && param.getVideoThreshold() != null
                    && ipAdRecordMap.get(user.getUserId()) != null && param.getVideoThreshold() <= ipAdRecordMap.get(user.getUserId())) {
                user.setMaybeDone(1);
            }
        }
    }

    /**
     * 当日收益、当日视频播放数、前三日收益
     */
    private void computeTodayIncome(YtAppUserListView user, List<YtDyzAdRecord> adRecords, YtAppUserListParam param) {
        //获取当日收益收益 | 当日收益视频播放数 = 统计筛选登陆时间段
        int todayVideo = 0;
        BigDecimal todayIncome = BigDecimal.ZERO;
        DateTime currentDate = DateUtil.date();
        if (CollUtil.isNotEmpty(adRecords)) {
            // 默认筛选今日广告记录 并计算前三日收益
            List<YtDyzAdRecord> ytDyzAdRecords = adRecords.stream()
                    .filter(s -> DateUtil.isSameDay(currentDate, DateUtil.parseDate(s.getFinishTime())))
                    .collect(Collectors.toList());
            todayIncome = ytDyzAdRecords.stream().map(YtDyzAdRecord::getRevenue)
                    .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            // 统计4天-今日收益=前三日收益
            if (user.getNearlyIncome() != null && user.getNearlyIncome().compareTo(todayIncome) >= 0) {
                user.setNearlyIncome(user.getNearlyIncome().subtract(todayIncome));
            }
            // 如果传递时间段 则按时间段筛选广告记录
            if(param.getLastLoginTimeBegin() != null || param.getLastLoginTimeEnd() != null) {
                ytDyzAdRecords = adRecords;
                if (param.getLastLoginTimeBegin() != null) {
                    ytDyzAdRecords = ytDyzAdRecords.stream()
                            .filter(record -> DateUtil.afterSameDay(
                                    DateUtil.parseDate(record.getFinishTime()), param.getLastLoginTimeBegin()))
                            .collect(Collectors.toList());
                }
                if (param.getLastLoginTimeEnd() != null) {
                    ytDyzAdRecords = ytDyzAdRecords.stream()
                            .filter(record -> DateUtil.beforeSameDay(
                                    DateUtil.parseDate(record.getFinishTime()), param.getLastLoginTimeEnd()))
                            .collect(Collectors.toList());
                }
                todayIncome = ytDyzAdRecords.stream().map(YtDyzAdRecord::getRevenue)
                        .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            todayVideo = (int) ytDyzAdRecords.stream()
                    .filter(record -> record.getAdSourceType() == AdSourceTypeEnum.rewarded_video.getAdSourceType())
                    .count();
        }
        user.setTodayVideo(todayVideo);
        user.setTodayIncome(todayIncome);
    }

    /**
     * 根据时间统计收益
     */

    @PostMapping("/getRevenueByTime")
    public BigDecimal getRevenueByTime(@RequestBody YtAppUserListParam param) {
        BigDecimal result = new BigDecimal(0);
        BigDecimal dyzRevenue = adRecordMapper.getRevenueByTime(param);
        if(Objects.nonNull(dyzRevenue)){
            result = result.add(dyzRevenue);
        }
        return result;
    }


    /**
     * 主键查询用户信息
     */
    @ApiEncrypt(response = true)
    @GetMapping("/getUserInfo")
    public Result<YtDyzUser> getUserInfo(@RequestParam("userId") String userId) {
        YtDyzUser user = appUserMapper.selectPrimaryKey(userId);
        user.setLoginRecordList(loginRecordMapper.getLoginRecords(userId));
        user.setTodayAnswerCount(questionMapper.getAnswerCount(userId,1));
        user.setHistoryAnswerCount(questionMapper.getAnswerCount(userId,2));
        user.setAnswerRecordList(questionMapper.getAnswerRecords(userId));
        return Result.resultObjOk(user);
    }

    /**
     * 查询用户信息
     */

    @PostMapping("/getUserList")
    public ResultTable<YtDyzUser> getUserList(@RequestBody AppUserParam param) {
        List<YtDyzUser> resultList = new ArrayList<>();
        List<YtDyzUser> userList = appUserMapper.getUserList(param);
        if(CollUtil.isNotEmpty(userList)){resultList.addAll(userList);}
        return ResultTable.resultTableOk(new PageInfo<>(resultList));
    }


    @PostMapping("/getUserAll")
    public ResultTable<YtDyzUser> getUserAll(@RequestBody AppUserParam param) {
        List<YtDyzUser> userList = appUserMapper.getUserList(param);
        return ResultTable.resultTableOk(new PageInfo<>(userList));
    }

    /**
     * 修改用户信息
     */

    @PostMapping("/updateUserInfo")
    public Result<?> updateUserInfo(@RequestBody YtDyzUser dyzUser) {
        appUserMapper.updateUser(dyzUser);
        return Result.resultOk(RepMessage.MODIFY_SUCCESS);
    }

    /**
     * 查询用户的广告记录
     */

    @GetMapping("/adRecords")
    public ResultTable<YtDyzAdRecord> adRecords(@RequestParam(name = "userId",required = true) String userId,
                                                @RequestParam(name = "adsourceType",required = false)Integer adsourceType) {
        List<YtDyzAdRecord> result = new ArrayList<>();
        List<YtDyzAdRecord> adrecords = adRecordMapper.getByUserId(userId, adsourceType);
        if(CollUtil.isNotEmpty(adrecords)){
            result.addAll(adrecords);
        }
        return ResultTable.resultTableOk(new PageInfo<YtDyzAdRecord>(result));
    }


    @PostMapping("/adRecords/page")
    public ResultTable<YtDyzAdRecord> adRecordsPage(@RequestBody AdRecordListParam param) {
        YtDyzUser user = appUserMapper.selectById(param.getUserId());
        param.setIosId(user.getIosId());
        PageHelper.startPage(param.getPage(), param.getLimit());
        List<YtDyzAdRecord> adRecords = adRecordMapper.getByUserByParam(param);
        if(CollUtil.isNotEmpty(adRecords) && AdRecordEnum.LOGIN_BEFORE.getCode().equals(param.getLoginStatus())){
            for (YtDyzAdRecord adRecord: adRecords){
                if (adRecord.getUserId() == null){
                    adRecord.setUserId(user.getUserId());
                    adRecordMapper.updateOneVisitor(adRecord);
                }
                adRecord.setLoginStatus(AdRecordEnum.LOGIN_BEFORE.getCode());
            }
        }
        return ResultTable.resultTableOk(new PageInfo<>(adRecords));
    }

    /**
     * 用户广告数据分类统计
     */
    @PostMapping("/adRecords/statistic")
    public Result<YtUserEcpmStatisticView> adRecordsStatistic(@RequestBody AdRecordListParam param){
        YtDyzUser user = appUserMapper.selectById(param.getUserId());
        param.setIosId(user.getIosId());
        YtUserEcpmStatisticView view = adRecordMapper.selectAdStatistic(param);
        return Result.resultObjOk(view);
    }

    /**
     * 查询广告记录统计数
     */

    @GetMapping("/adRecords/count/month")
    public Result<Integer> queryRecordMonthCount(@RequestParam(name = "userId") String userId,
                                                 @RequestParam(name = "adSourceType", required = false) Integer adSourceType,
                                                 @RequestParam(name = "startTime", required = false) String startTime) {
        Date time;
        // 统计起始时间为空，则默认查询当月信息
        if (StrUtil.isEmpty(startTime)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            time = calendar.getTime();
        } else {
            time = DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss");
        }
        return Result.resultObjOk(adRecordMapper.getRecordMonthCount(userId, adSourceType, time));
    }


    @PostMapping("/queryUserByTime")
    public List<YtDyzUser> queryUserByTime(@RequestBody AppUserQueryParam appUserQueryParam) {
        List<YtDyzUser> ytDyzUsers = appUserMapper.queryAllByTime(appUserQueryParam.getStartTime(),
                appUserQueryParam.getEndTime(),appUserQueryParam.getAppIdList());
        return ytDyzUsers;
    }


    @PostMapping("/queryUserByTodayTime")
    public int[] queryUserByTodayTime(@RequestBody AppQueryUserTodayTimeParam appQueryUserTodayTimeParam) {
        // 获取当前日期
        LocalDate localDate = LocalDate.now();

        // 构建当天起始时间段
        LocalDateTime startOfDay = localDate.atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1).minusSeconds(1);

        Date startTime = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Date endTime = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
        // 查询用户注册数据
        List<HourCountView> hourCountViews = appUserMapper.countUsersByHour(startTime, endTime,appQueryUserTodayTimeParam.getAppIdList());
        // 初始化每小时用户数量数组
        int[] hourlyCounts = new int[24];
        for (HourCountView hc : hourCountViews) {
            if (hc.getHour() >= 0 && hc.getHour() < 24) {
                hourlyCounts[hc.getHour()] = hc.getCount();
            }
        }
        return hourlyCounts;
    }


    @PostMapping("/queryLoginRecords")
    public List<String> queryLoginRecords(@RequestBody AppUserQueryParam appUserQueryParam) {
        return loginRecordMapper.queryLoginCount(appUserQueryParam);
    }


    @GetMapping("/queryByOpenid")
    public List<YtDyzUser> queryByOpenid(@RequestParam("openid") String openid){
        return appUserMapper.queryByOpenid(openid);
    }


    @GetMapping("/queryByIosId")
    public List<YtDyzUser> queryByIosId(@RequestParam("iosId") String iosId){
        return appUserMapper.queryByIosId(iosId);
    }


    @PostMapping("/queryTodayBanned")
    public List<YtDyzUser> queryTodayBanned(@RequestBody AppUserTodayBannedParam appUserTodayBannedParam){
        return appUserMapper.queryTodayBanned(appUserTodayBannedParam.getStartTime(),
                appUserTodayBannedParam.getEndTime(), appUserTodayBannedParam.getUserIdList());
    }


    @PostMapping("/unLockUser")
    public void unLockUser(@RequestParam("userIds")String userIds){
        List<YtDyzUser> dyzUsers = appUserMapper.queryByUserIds(userIds);
        if(CollUtil.isNotEmpty(dyzUsers)){
            appUserMapper.unlockUser(userIds);
        }
    }


    @GetMapping("/lockUser")
    public YtDyzUser lockUser(@RequestParam("userId")String userId,@RequestParam("userStatus")Integer userStatus){
        YtDyzUser dyzUser = appUserMapper.selectPrimaryKey(userId);
        YtDyzUser newUser = new YtDyzUser();
        newUser.setUserId(userId);
        newUser.setUserStatus(userStatus);
        newUser.setRiskReason(BannedTypeEnum.CHANNEL.getDesc()+"禁止登录");
        if(Objects.nonNull(dyzUser)){
            appUserMapper.updateUser(newUser);
            return dyzUser;
        }
        return null;
    }


    @GetMapping("/queryAllUserByIps")
    public List<YtDyzUser> queryAllUserByIps(@RequestParam("appId") String appId, @RequestParam("bannedIps") String bannedIps) {
        List<String> ips = Arrays.asList(bannedIps.split("\\|"));
        return appUserMapper.queryByIps(appId, ips);
    }


    @GetMapping("/queryCountByIpTime")
    public Result<Integer> queryCountByIpTime(@RequestParam("appId") String appId, @RequestParam("lastLoginIp") String lastLoginIp,
                                                 @RequestParam("limitHour") Integer limitHour) {
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.HOUR_OF_DAY, -limitHour);
        Date startTime = instance.getTime();
        //不校验渠道查询所有
        Long userCount = appUserMapper.queryCountByIpTime(lastLoginIp, startTime);
        return Result.resultObjOk(Math.toIntExact(userCount));
    }


    @PostMapping("/queryUserByParam")
    public RiskYtDyzUserView queryUserByParam(@RequestBody LoginRiskYtDyzUserParam param) {
        RiskYtDyzUserView riskYtDyzUserView = new RiskYtDyzUserView();
        Calendar instance = Calendar.getInstance();
        Date currentDate = new Date();
        // 查询指定时间内同ip登陆用户数
        if (StringUtils.isNotEmpty(param.getLastLoginIp()) && param.getLimitHour() != null) {
            instance.setTime(currentDate);
            instance.add(Calendar.HOUR_OF_DAY, -param.getLimitHour());
            Date startTime = instance.getTime();
            Long userCount = appUserMapper.queryCountByIpTime(param.getLastLoginIp(), startTime);
            riskYtDyzUserView.setUserCount(Math.toIntExact(userCount));
        }
        // 查询同一设备的所有用户
        if (StringUtils.isNotEmpty(param.getIosId())) {
            List<YtDyzUser> dyzUsers = appUserMapper.queryByIosId(param.getIosId());
            riskYtDyzUserView.setUserList(dyzUsers);
        }
        // 查询指定地区的的所有登陆用户
        if (StringUtils.isNotEmpty(param.getLimitCity()) && param.getLimitHour335() != null) {
            List<String> cityList = Arrays.asList(param.getLimitCity().split(","));
            instance.setTime(currentDate);
            instance.add(Calendar.HOUR_OF_DAY, -param.getLimitHour());
            Date startTime = instance.getTime();
            Long userCount = appUserMapper.queryCountByIpRegion(cityList, startTime);
            riskYtDyzUserView.setCityUserCount(Math.toIntExact(userCount));
        }
        // 查询三天内 该渠道 相同IP 相同设备应用列表的用户数
        if (StrUtil.isNotEmpty(param.getLastLoginIp()) && StrUtil.isNotEmpty(param.getPhoneJson())) {
            JSONObject phoneJson = JSONObject.parseObject(param.getPhoneJson());
            String appList = phoneJson.get("appList") == null ? null : phoneJson.getString("appList");
            if ("[]".equals(appList)) {
                appList = "";
            }
            if (StrUtil.isNotEmpty(appList)) {
                String lastLoginIp = param.getLastLoginIp();
                Date startTime = null;
                if (param.getLimitDays322() != null) {
                    instance.setTime(currentDate);
                    instance.add(Calendar.DAY_OF_MONTH, -param.getLimitDays322());
                    startTime = instance.getTime();
                }
                Long count = appUserMapper.countUserByLastLoginIpAndAppList(lastLoginIp, appList, startTime);
                riskYtDyzUserView.setSameDeviceCount(count);
            }
        }
        return riskYtDyzUserView;
    }

    /**
     * 批量审核用户是否满足风控规则
     * 不满足风控规则的审核通过后直接封禁指定天数
     */

    @PostMapping("/batchAudit")
    public void batchAudit(@RequestBody AuditCheckParam checkParam){
        AuditUserParam auditParam = checkParam.getAuditParam();
        RiskTemplateView ecpmLimit = checkParam.getEcpmLimit();
        RiskTemplateView revenueLimit = checkParam.getRevenueLimit();
        //查询用户，指定应用激励视频的广告记录
        List<AgentAuditCheckVO> auditList = new ArrayList<>();
        List<AgentAuditCheckVO> auditCheckList = appUserMapper.queryTodayUserAd(auditParam);
        if(CollUtil.isNotEmpty(auditCheckList)){auditList.addAll(auditCheckList);}
        Map<String, List<YtDyzAdRecord>> adRecordMap = auditList.stream().collect(
                Collectors.toMap(AgentAuditCheckVO::getUserId, AgentAuditCheckVO::getAdRecordList));
        checkRisk742(ecpmLimit,adRecordMap,auditParam);
        checkRisk746(revenueLimit,adRecordMap,auditParam);
    }

    /**
     * 校验默认风控规则742
     */
    private void checkRisk742(RiskTemplateView ecpmLimit,Map<String, List<YtDyzAdRecord>> adRecordMap,AuditUserParam auditParam) {
        if(ecpmLimit.getEnabled()!=1)return;
        Map<String, String> limitMap = ecpmLimit.getConfigList().stream().collect(
                Collectors.toMap(RiskConfigView::getFieldName, RiskConfigView::getConfigVal));
        int adCount = 0;
        for (Map.Entry<String, List<YtDyzAdRecord>> entry : adRecordMap.entrySet()) {
            adCount = CollUtil.isEmpty(entry.getValue())?adCount:entry.getValue().size();
            ++adCount;
            //判断当日观看视频数已经达到风控条件预设的视频数
            int firstAdCount = Integer.parseInt(limitMap.get("firstAdCount"));
            if(adCount>=firstAdCount){
                //过滤出ecpm值小于预设值的视频数
                int ecpm = Integer.parseInt(limitMap.get("ecpm"));
                long count = entry.getValue().stream().filter(
                        s -> Objects.nonNull(s.getEcpm())&&(s.getEcpm().compareTo(BigDecimal.valueOf(ecpm))) < 0).count();
                int exact = Math.toIntExact(count);
                //判断小于预设值的视频数超出预设次数
                int haveCount = Integer.parseInt(limitMap.get("haveCount"));
                if(exact>haveCount){//把风控不满足的用户记录redis 进行封禁
                    checkLock(entry,auditParam);
                }
            }
        }

    }

    /**
     * 用户锁定操作
     */
    private void checkLock(Map.Entry<String, List<YtDyzAdRecord>> entry, AuditUserParam auditParam) {
        log.error("执行对低价值用户{}的定时风控操作", entry.getKey());
        if(auditParam.getEffectTime() == 0){ //立即锁定
            lockUser(entry.getKey(), UserStatusEnum.RISK.getCode());
            redisService.setTimeOutHoursStr("unlock_"+entry.getKey(),auditParam.getAppId(), auditParam.getBannedLimit()*24L);
        }else{//延迟锁定
            redisService.setTimeOutHoursStr("lock_"+entry.getKey(), auditParam.getAppId(), auditParam.getEffectTime());
            redisService.setTimeOutHoursStr("unlock_"+entry.getKey(),auditParam.getAppId(),
                    auditParam.getBannedLimit()*24L + auditParam.getEffectTime());
        }
    }

    /**
     * 校验默认风控规则746
     */
    private void checkRisk746(RiskTemplateView revenueLimit,Map<String, List<YtDyzAdRecord>> adRecordMap,AuditUserParam auditParam) {
        if(revenueLimit.getEnabled()!=1)return;
        Map<String, String> revenueMap = revenueLimit.getConfigList().stream().collect(
                Collectors.toMap(RiskConfigView::getFieldName, RiskConfigView::getConfigVal));
        for (Map.Entry<String, List<YtDyzAdRecord>> entry : adRecordMap.entrySet()) {
            List<YtDyzAdRecord> revenues = entry.getValue().stream().filter(
                    s -> Objects.nonNull(s.getRevenue())&&(s.getRevenue().compareTo(BigDecimal.ZERO)) > 0).collect(Collectors.toList());
            int incomeCount = 0;
            incomeCount = CollUtil.isEmpty(revenues)?incomeCount:entry.getValue().size();
            //判断当日获得收益的广告达到预设数值，触发风控规则
            int rewardCount = Integer.parseInt(revenueMap.get("rewardCount"));
            if(incomeCount>=rewardCount){
                BigDecimal income = new BigDecimal(revenueMap.get("income"));
                //获取最先的两条
                BigDecimal reduce = revenues.stream().map(YtDyzAdRecord::getRevenue).reduce(BigDecimal.ZERO, BigDecimal::add);
                if(reduce.compareTo(income)<0){
                    checkLock(entry,auditParam);
                }
            }
        }

    }
}
