package com.ytpm.middle.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.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytpm.agent.model.YtApp;
import com.ytpm.agent.model.YtAppConfigLog;
import com.ytpm.agent.model.YtPlatformUserApp;
import com.ytpm.agent.param.AppListParam;
import com.ytpm.agent.param.AppParam;
import com.ytpm.agent.view.AgentAppView;
import com.ytpm.app.model.YtAppDefaultConfig;
import com.ytpm.app.view.WxDefaultConfig;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.middle.dao.ApkMapper;
import com.ytpm.middle.dao.AppMapper;
import com.ytpm.middle.dao.RiskMapper;
import com.ytpm.middle.service.ApkService;
import com.ytpm.middle.util.AliOSSUtil;
import com.ytpm.middle.util.BeanChangeUtil;
import com.ytpm.middle.util.FeignClientInvoker;
import com.ytpm.middle.view.MiddleUserInfo;
import com.ytpm.risk.model.YtRiskConfig;
import com.ytpm.risk.model.YtRiskTemplate;
import com.ytpm.risk.model.YtRiskTemplateConfig;
import com.ytpm.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
@RefreshScope
public class ApkServiceImpl implements ApkService {

    @Resource
    private ApkMapper apkMapper;
    @Resource
    private RiskMapper riskMapper;
    @Resource
    private FeignClientInvoker feignInvoker;
    @Resource
    private AppMapper appMapper;

    @Value("${risk.config.initEcpm}")
    private String initEcpm;
    @Value("${risk.config.initRevenue}")
    private String initRevenue;

    @Value("${risk.config.initAdCompletedCount:10}")
    private String initAdCompletedCount;

    @Value("${risk.config.initFirstCount:4}")
    private String initFirstCount;

    @Value("${risk.config.initAverageRevenue:0.12}")
    private String initAverageRevenue;

    @Value("${risk.config.initMonthCount:1}")
    private String initMonthCount;

    @Value("${risk.config.initMonthTaskLimit:80}")
    private String initMonthTaskLimit;

    @Value("${risk.config.initHourCount:3}")
    private String initHourCount;

    @Value("${risk.config.initHourTaskLimit:10}")
    private String initHourTaskLimit;

    @Value("${risk.config.visitor.initEcpmLimit:20}")
    private String initVisitorEcpmLimit;

    @Value("${risk.config.visitor.initRevenueLimit:0.04}")
    private String initVisitorRevenueLimit;

    @Value(("${risk.config.visitor.initHours:3}"))
    private String initVisitorHours;
    @Value(("${risk.config.visitor.initRidCount:10}"))
    private String initVisitorRidCount;

    @Value("${risk.config.334.limitHour:24}")
    private String init334LimitHour;
    @Value("${risk.config.334.limitUserCount:1}")
    private String init334LimitUserCount;

    @Value("${risk.config.335.limitHour:24}")
    private String init335LimitHour;
    @Value("${risk.config.335.limitHour:}")
    private String init335LimitCity;
    @Value("${risk.config.335.limitUserCount:100}")
    private String init335LimitUserCount;



    /**
     * 查询应用列表
     */
    @Override
    public ResultTable<AgentAppView> searchAppList(AppListParam appListParam) {
        PageHelper.startPage(appListParam.getPage(), appListParam.getLimit());
        List<AgentAppView> views = apkMapper.searchAppList(appListParam);
        String appIds = views.stream().map(AgentAppView::getAppId).collect(Collectors.joining(","));
        List<String> serviceList = views.stream().map(AgentAppView::getServiceName).distinct().collect(Collectors.toList());
        List<WxDefaultConfig> configs = new ArrayList<>();
        for (String serve : serviceList) {
            Object o;
            try {
                o = feignInvoker.invoke(serve, "getConfigs", appIds);
            }catch (Exception e){
                continue;
            }
            List<WxDefaultConfig> configList = JSONArray.parseArray(JSON.toJSONString(o), WxDefaultConfig.class);
            configs.addAll(configList);
        }
        Map<String, WxDefaultConfig> appTypeMap = configs.stream().collect(Collectors.toMap(WxDefaultConfig::getAppId, o->o));
        //分析OSS实时日志统计下载次数
        Map<String, Integer> countDownloadMap = AliOSSUtil.getCountDownload(
                Math.toIntExact(DateUtil.getTodayStart().getTime() / 1000), (int) (System.currentTimeMillis() / 1000));
        WxDefaultConfig config;
        // 查询配置修改记录
        List<YtAppConfigLog> configLogs = appMapper.selectLastConfigLog(appIds);
        Map<String, YtAppConfigLog> configLogMap = configLogs.stream().collect(Collectors.toMap(
                YtAppConfigLog::getAppId, item-> item,
                (o1,o2) -> o2
        ));
        for (AgentAppView view : views) {
            view.setLastChangeLog(configLogMap.get(view.getAppId()));
            if(appTypeMap.containsKey(view.getAppId())) {
                config = appTypeMap.get(view.getAppId());
                view.setAppCode(config.getAppType());
                view.setDitchId(config.getDitchId());
                view.setTakuAppId(config.getTakuAppId());
                view.setTakuKey(config.getTakuKey());
                view.setTakuBannerPid(config.getTakuBannerPid());
                view.setTakuNativePid(config.getTakuNativePid());
                view.setTakuRewardPid(config.getTakuRewardPid());
                view.setTakuInterstitialPid(config.getTakuInterstitialPid());
                view.setCanUseRoot(config.getCanUseRoot());
                view.setCanUseAdb(config.getCanUseAdb());
                view.setCanUseFloat(config.getCanUseFloat());
                view.setCanAccumulation(config.getCanAccumulation());
                view.setCanSimulator(config.getCanSimulator());
                view.setPowerWaitTime(config.getPowerWaitTime());
                view.setInterstitialIntervalTime(config.getInterstitialIntervalTime());
                view.setCanCacheVideo(config.getCanCacheVideo());
                view.setStartWaitTime(config.getStartWaitTime());
                view.setTaskLimitTip(config.getTaskLimitTip());
                view.setLowValueTip(config.getLowValueTip());
                view.setBrushTip(config.getBrushTip());
                view.setFlowIntervalTime(config.getFlowIntervalTime());
                view.setCanAllowAutoRefresh(config.getCanAllowAutoRefresh());
            }
            if(CharSequenceUtil.isBlank(view.getApkUrl())) {
                continue;
            }
            String substring = view.getApkUrl().substring(view.getApkUrl().lastIndexOf("/")+1).toLowerCase(Locale.ENGLISH);
            if(countDownloadMap.containsKey(substring)){
                view.setDownloadCount(countDownloadMap.get(substring));
            }
        }
        return ResultTable.resultTableOk(new PageInfo<>(views));
    }

    /**
     * 新增应用
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> saveApp(AppParam param, MiddleUserInfo loginUser) {
        YtPlatformUserApp app = appMapper.getByPrimary(param.getSuperiorId());
        // 保存修改记录
        saveConfigChangeLog(param, app, loginUser.getUserId());
        //数据库操作，有appId为修改， 没有时为新增
        changeDataAction(param, loginUser.getUserId());
        //出包修改 default_config
        changeDefaultConfig(param);
        if(CharSequenceUtil.isNotBlank(param.getAppId())){
            generateRiskDefaultConfig(param,loginUser);
        }
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }

    /**
     * 修改子包配置
     */
    @Override
    public Result<?> changeConfig(AppParam param) {
        //出包修改 default_config
        YtPlatformUserApp app = appMapper.getByPrimary(param.getSuperiorId());
        saveConfigChangeLog(param, app, null);
        changeDefaultConfig(param);
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }

    /**
     * 出包修改对应子包的默认配置
     */
    private void changeDefaultConfig(AppParam param) {
        YtPlatformUserApp app = appMapper.getByPrimary(param.getSuperiorId());
        YtAppDefaultConfig config = convertToYtDefaultConfig(param, app);
        feignInvoker.invoke(app.getServiceName(), "updateAppConfig", config);
    }

    private YtAppDefaultConfig convertToYtDefaultConfig(AppParam param, YtPlatformUserApp app){
        YtAppDefaultConfig config = new YtAppDefaultConfig();
        config.setAppId(param.getAppId());
        if(Objects.nonNull(param.getDitchId())){
            config.setDitchId(param.getDitchId().toString());
        }
        config.setTakuAppId(app.getTakuAppId());
        config.setTakuKey(app.getTakuKey());
        config.setTakuBannerPid(app.getTakuBannerPid());
        config.setTakuNativePid(app.getTakuNativePid());
        config.setTakuRewardPid(app.getTakuRewardPid());
        config.setTakuInterstitialPid(app.getTakuInterstitialPid());
        config.setCanAccumulation(param.getCanAccumulation());
        config.setCanUseAdb(param.getCanUseAdb());
        config.setCanUseFloat(param.getCanUseFloat());
        config.setCanUseRoot(param.getCanUseRoot());
        config.setPowerWaitTime(param.getPowerWaitTime());
        config.setInterstitialIntervalTime(param.getInterstitialIntervalTime());
        config.setFlowIntervalTime(param.getFlowIntervalTime());
        config.setTaskLimitTip(param.getTaskLimitTip());
        config.setLowValueTip(param.getLowValueTip());
        config.setBrushTip(param.getBrushTip());
        config.setCanCacheVideo(param.getCanCacheVideo());
        config.setStartWaitTime(param.getStartWaitTime());
        config.setCanAllowAutoRefresh(param.getCanAllowAutoRefresh());
        return config;
    }

    private void saveConfigChangeLog(AppParam appParam, YtPlatformUserApp app, String loginUserId) {
        StringBuilder changeContent = new StringBuilder();
        try {
            YtApp oldYtApp = appMapper.selectByPrimaryId(appParam.getAppId());
            if (oldYtApp != null) {
                YtApp newYtApp = new YtApp();
                BeanUtil.copyProperties(appParam, newYtApp);
                changeContent.append(BeanChangeUtil.compareBeans(oldYtApp, newYtApp));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        try {
            Object object = feignInvoker.invoke(app.getServiceName(), "getConfigs", appParam.getAppId());
            WxDefaultConfig oldDefault = null;
            if (object != null) {
                List<WxDefaultConfig> configList = JSONArray.parseArray(JSON.toJSONString(object), WxDefaultConfig.class);
                oldDefault = CollUtil.isNotEmpty(configList) ? configList.get(0) : null;
            }
            if (oldDefault != null) {
                // 变更记录修改
                YtAppDefaultConfig config = convertToYtDefaultConfig(appParam, app);
                WxDefaultConfig newConfig = new WxDefaultConfig();
                BeanUtils.copyProperties(config, newConfig);
                changeContent.append(BeanChangeUtil.compareBeans(oldDefault, newConfig));
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
        if (changeContent.length() > 0) {
            YtAppConfigLog configLog = new YtAppConfigLog();
            configLog.setRecordId(IdUtil.fastSimpleUUID());
            configLog.setAppId(appParam.getAppId());
            configLog.setChangeContent(changeContent.toString());
            configLog.setChangeTime(new Date());
            configLog.setChangeBy(loginUserId);
            appMapper.insertConfigLog(configLog);
        }
    }

    /**
     * 给应用生成默认的风控配置
     */
    private void generateRiskDefaultConfig(AppParam param,MiddleUserInfo loginUser) {
        YtApp ytApp = appMapper.selectByPrimaryId(param.getAppId());
        if (ytApp != null) {
            param.setAppType(ytApp.getAppType());
        }
        List<YtRiskTemplate> templates = riskMapper.selectByAppId(param.getAppId());
        Map<String, YtRiskTemplate> templateMap = templates.stream()
                .filter(item -> StrUtil.isNotEmpty(item.getTemplateCode()))
                .collect(Collectors.toMap(item -> item.getTemplateCode().split("-")[1], item -> item,
                        (o1, o2) -> o2
                ));
        // 激励视频ecpm值控制
        if(templateMap.get("742") == null){
            addTemp742(param,loginUser);
        }
        // 最低收益限制
        if(templateMap.get("746") == null) {
            addTemp746(param,loginUser);
        }
        // 游客用户总预估收益限制
        if (templateMap.get("344") == null) {
            addTemp344(param, loginUser);
        }
        // 游客用户总ecpm限制
        if (templateMap.get("345") == null) {
            addTemp345(param, loginUser);
        }
        // 平均收益风控
        if (templateMap.get("766") == null) {
            addTemp766(param, loginUser);
        }
        // 月区间任务完成数限制
        if (templateMap.get("767") == null) {
            addTemp767(param, loginUser);
        }
        // 小时区间任务数完成限制
        if (templateMap.get("768") == null) {
            addTemp768(param, loginUser);
        }
        // 同IP登陆限制
        if (templateMap.get("334") == null) {
            addTemp334(param, loginUser);
        }
        // 地区IP登陆用户限制
        if (templateMap.get("335") == null) {
            addTemp335(param, loginUser);
        }

    }

    private void addTemp335(AppParam param, MiddleUserInfo loginUser) {
        if (param.getAppType() != 2) {
            return;
        }
        // 24小时内{}城市限制{}个账号登陆
        String appId = param.getAppId();
        String agentId = param.getUserId();
        Date currentDate = new Date();
        List<YtRiskConfig> configs = new ArrayList<>();
        YtRiskConfig riskConfig;
        riskConfig = createRiskConfig(agentId, "limitHour",
                StrUtil.format("{}小时内", init335LimitHour), init335LimitHour, 2);
        configs.add(riskConfig);
        riskConfig = createRiskConfig(agentId, "limitCity",
                StrUtil.format("{}地区", init335LimitCity), init335LimitCity, 2);
        configs.add(riskConfig);
        riskConfig = createRiskConfig(agentId, "limitCityCount",
                StrUtil.format("登陆用户不多于{}", init335LimitUserCount), init335LimitUserCount, 2);
        configs.add(riskConfig);
        String templateId = IdUtil.getSnowflakeNextIdStr();
        Integer enabled = 0; // IOS默认启用
        YtRiskTemplate template = new YtRiskTemplate(templateId, "地区IP登陆用户限制",
                StrUtil.format("{}小时内{}地区登陆用户不多于{}个", init335LimitHour, init335LimitCity, init335LimitUserCount),
                appId + "-335", agentId, 2, appId,
                currentDate, loginUser.getUserId(), null, null,
                enabled, 1, 1);
        riskMapper.insertTemplate(template);
        // 风控模板关联配置项
        bindTempConfig(loginUser, template, configs);
        //风控模版关联应用
        riskMapper.relativeApp(appId, param.getAppName(), template.getTemplateId(), loginUser.getNickName(), loginUser.getUserId());
    }

    private void addTemp334(AppParam param, MiddleUserInfo loginUser) {
        if (param.getAppType() != 2) {
            return;
        }
        // 24小时內同一IP仅1个账号登陆
        String appId = param.getAppId();
        String agentId = param.getUserId();
        Date currentDate = new Date();
        List<YtRiskConfig> configs = new ArrayList<>();
        YtRiskConfig riskConfig;
        riskConfig = createRiskConfig(agentId, "limitHour",
                StrUtil.format("{}小时内", init334LimitHour), init334LimitHour, 2);
        configs.add(riskConfig);
        riskConfig = createRiskConfig(agentId, "limitCount",
                StrUtil.format("仅{}个账号登陆", init334LimitUserCount), init334LimitUserCount, 2);
        configs.add(riskConfig);
        String templateId = IdUtil.getSnowflakeNextIdStr();
        Integer enabled = 1; // IOS默认启用
        YtRiskTemplate template = new YtRiskTemplate(templateId,"同IP登陆限制",
                StrUtil.format("{}小时内仅{}个账号登陆", init334LimitHour, init334LimitUserCount),
                appId + "-334", agentId, 2, appId,
                currentDate, loginUser.getUserId(),null, null,
                enabled,1,1);
        riskMapper.insertTemplate(template);
        // 风控模板关联配置项
        bindTempConfig(loginUser, template, configs);
        //风控模版关联应用
        riskMapper.relativeApp(appId, param.getAppName(), template.getTemplateId(), loginUser.getNickName(), loginUser.getUserId());
    }

    /**
     * 创建输出框类型配置项
     */
    private YtRiskConfig createRiskConfig(String agentId, String fieldName, String filedDesc, String initVal, Integer multi){
        String configId = IdUtil.getSnowflakeNextIdStr();
        YtRiskConfig config = new YtRiskConfig(configId, agentId, fieldName, filedDesc, 1, initVal, multi);
        riskMapper.insertConfigItem(config);
        return config;
    }

    /**
     * 绑定模板配置项
     */
    private void bindTempConfig(MiddleUserInfo loginUser, YtRiskTemplate template, List<YtRiskConfig> configs) {
        YtRiskTemplateConfig templateConfig;
        Date currentDate = new Date();
        for (YtRiskConfig config : configs) {
            templateConfig = new YtRiskTemplateConfig(template.getTemplateId(), config.getConfigId(),
                    loginUser.getUserId(), loginUser.getNickName(), currentDate);
            riskMapper.insertTempConfig(templateConfig);
        }
    }

    private void addTemp333(AppParam param, MiddleUserInfo loginUser) {
        // 风控规则 设备在{}小时内注册的渠道数>={}
        String appId = param.getAppId();
        String agentId = param.getUserId();
        Date currentDate = new Date();
        List<YtRiskConfig> configs = new ArrayList<>();
        YtRiskConfig riskConfig = createRiskConfig(param.getUserId(), "hours",
                StrUtil.format("{}小时内，", initVisitorHours), initVisitorHours, 2);
        configs.add(riskConfig);
        riskConfig = createRiskConfig(param.getUserId(),  "uidCount",
                StrUtil.format("游客注册的渠道数<{}", initVisitorRidCount), initVisitorRidCount, 3);
        configs.add(riskConfig);
        String templateId = IdUtil.getSnowflakeNextIdStr();
        YtRiskTemplate template = new YtRiskTemplate(templateId, "游客注册限制",
                StrUtil.format("{}小时内，游客注册的渠道数<{}", initVisitorHours, initVisitorHours),
                appId + "-333", agentId, 2, appId,
                currentDate, loginUser.getUserId(), null, null,
                1, 1, 1);
        riskMapper.insertTemplate(template);
        bindTempConfig(loginUser, template, configs);
        //风控模版关联应用
        riskMapper.relativeApp(appId, param.getAppName(), template.getTemplateId(), loginUser.getNickName(), loginUser.getUserId());
    }

    private void addTemp323(AppParam param, MiddleUserInfo loginUser) {
        // 风控规则 {}小时内登录渠道数超过{}
        String appId = param.getAppId();
        String agentId = param.getUserId();
        List<YtRiskConfig> configs = new ArrayList<>();
        YtRiskConfig riskConfig = createRiskConfig(param.getUserId(), "hours",
                StrUtil.format("{}小时内", initVisitorHours), initVisitorHours, 2);
        configs.add(riskConfig);
        riskConfig = createRiskConfig(param.getUserId(), "hours",
                StrUtil.format("游客登录渠道数<{}", initVisitorHours), initVisitorHours, 3);
        configs.add(riskConfig);
        String templateId = IdUtil.getSnowflakeNextIdStr();
        YtRiskTemplate template = new YtRiskTemplate(templateId, "游客登录限制",
                StrUtil.format("{}小时内游客登录渠道数<{}", initVisitorHours, initVisitorHours),
                appId + "-323", agentId, 2, appId,
                new Date(), loginUser.getUserId(), null, null,
                1, 1, 1);
        riskMapper.insertTemplate(template);
        // 风控模板关联配置项
        bindTempConfig(loginUser, template, configs);
        //风控模版关联应用
        riskMapper.relativeApp(appId, param.getAppName(), template.getTemplateId(), loginUser.getNickName(), loginUser.getUserId());
    }

    private void addTemp344(AppParam param, MiddleUserInfo loginUser) {
        // 风控规则 开屏广告、横幅、原生（信息流）总预估收益<{}
        String appId = param.getAppId();
        String agentId = param.getUserId();
        List<YtRiskConfig> configs = new ArrayList<>();
        YtRiskConfig riskConfig = createRiskConfig(param.getUserId(), "revenueLimit",
                StrUtil.format("开屏广告、横幅、原生（信息流）总预估收益<{},", initVisitorRevenueLimit), initVisitorRevenueLimit, 4);
        configs.add(riskConfig);
        String templateId = IdUtil.getSnowflakeNextIdStr();
        Integer enabled = 2 == param.getAppType() ? 0 : 1; // IOS默认关闭风控
        YtRiskTemplate template = new YtRiskTemplate(templateId, "游客用户总预估收益限制",
                StrUtil.format("开屏广告、横幅、原生（信息流）总预估收益<{},", initVisitorRevenueLimit),
                appId + "-344", agentId, 2, appId,
                new Date(), loginUser.getUserId(), null, null,
                enabled, 1, 1);
        riskMapper.insertTemplate(template);
        // 风控模板关联配置项
        bindTempConfig(loginUser, template, configs);
        //风控模版关联应用
        riskMapper.relativeApp(appId, param.getAppName(), template.getTemplateId(), loginUser.getNickName(), loginUser.getUserId());
    }

    private void addTemp345(AppParam param, MiddleUserInfo loginUser) {
        // 风控规则 开屏广告、横幅、原生（信息流）总ecpm<{}
        String appId = param.getAppId();
        String agentId = param.getUserId();
        List<YtRiskConfig> configs = new ArrayList<>();
        YtRiskConfig riskConfig = createRiskConfig(param.getUserId(), "ecpmLimit",
                StrUtil.format("开屏广告、横幅、原生（信息流）总ecpm<{},", initVisitorEcpmLimit), initVisitorEcpmLimit, 4);
        configs.add(riskConfig);
        String templateId = IdUtil.getSnowflakeNextIdStr();
        YtRiskTemplate template = new YtRiskTemplate(templateId, "游客用户总ecpm限制",
                StrUtil.format("开屏广告、横幅、原生（信息流）总ecpm<{},", initVisitorEcpmLimit),
                appId + "-345", agentId, 2, appId,
                new Date(), loginUser.getUserId(), null, null,
                0, 1, 1);
        riskMapper.insertTemplate(template);
        // 风控模板关联配置项
        bindTempConfig(loginUser, template, configs);
        //风控模版关联应用
        riskMapper.relativeApp(appId, param.getAppName(), template.getTemplateId(), loginUser.getNickName(), loginUser.getUserId());
    }

    private void addTemp768(AppParam param, MiddleUserInfo loginUser) {
        // {}小时内，获得奖励的激励视频数>{}
        String appId = param.getAppId();
        String agentId = param.getUserId();
        Date currentDate = new Date();
        List<YtRiskConfig> configs = new ArrayList<>();
        YtRiskConfig riskConfig;
        riskConfig = createRiskConfig(agentId, "hourCount",
                StrUtil.format("{}小时内，", initHourCount), initHourCount, 2);
        configs.add(riskConfig);
        riskConfig = createRiskConfig(agentId, "hourTaskLimit",
                StrUtil.format("获得奖励的激励视频数>{}", initHourTaskLimit), initHourTaskLimit, 3);
        configs.add(riskConfig);
        String templateId = IdUtil.getSnowflakeNextIdStr();
        Integer enabled = 2 == param.getAppType() ? 0 : 1; // IOS默认关闭风控
        YtRiskTemplate template = new YtRiskTemplate(templateId,"小时区间任务数完成限制",
                StrUtil.format("{}小时内，获得奖励的激励视频数>{}", initHourCount, initHourTaskLimit),
                appId + "-768", agentId, 2, appId,
                currentDate, loginUser.getUserId(),null, null,
                enabled,1,1);
        riskMapper.insertTemplate(template);
        // 风控模板关联配置项
        bindTempConfig(loginUser, template, configs);
        //风控模版关联应用
        riskMapper.relativeApp(appId, param.getAppName(), template.getTemplateId(), loginUser.getNickName(), loginUser.getUserId());
    }

    private void addTemp767(AppParam param, MiddleUserInfo loginUser) {
        // 风控规则 {}月内，获得奖励的激励视频数>{}
        String appId = param.getAppId();
        String agentId = param.getUserId();
        Date currentDate = new Date();
        List<YtRiskConfig> configs = new ArrayList<>();
        YtRiskConfig riskConfig;
        riskConfig = createRiskConfig(agentId, "monthCount",
                StrUtil.format("{}月内", initMonthCount), initMonthCount, 2);
        configs.add(riskConfig);
        riskConfig = createRiskConfig(agentId, "monthTaskLimit",
                StrUtil.format("获得奖励的激励视频数>{}", initMonthTaskLimit), initMonthTaskLimit, 3);
        configs.add(riskConfig);
        String templateId = IdUtil.getSnowflakeNextIdStr();
        Integer enabled = 2 == param.getAppType() ? 0 : 1; // IOS默认关闭风控
        YtRiskTemplate template = new YtRiskTemplate(templateId,"月区间任务完成数限制",
                StrUtil.format("{}月内，获得奖励的激励视频数>{}", initMonthCount, initMonthTaskLimit),
                appId + "-767", agentId, 2, appId,
                currentDate, loginUser.getUserId(),null, null,
                enabled,1,1);
        riskMapper.insertTemplate(template);
        // 风控模板关联配置项
        bindTempConfig(loginUser, template, configs);
        //风控模版关联应用
        riskMapper.relativeApp(appId, param.getAppName(), template.getTemplateId(), loginUser.getNickName(), loginUser.getUserId());
    }

    private void addTemp766(AppParam param, MiddleUserInfo loginUser) {
        // 风控规则：当用户完成广告类型 激励视频  {}个 数时，获取近期{} * {} 条收益（平均取整）平均值 ，低于预设值 {} 时，
        String appId = param.getAppId();
        String agentId = param.getUserId();
        Date currentDate = new Date();
        List<String> configIds = new ArrayList<>();
        YtRiskConfig riskConfig;
        riskConfig = createRiskConfig(agentId, "adCompletedCount",
                StrUtil.format("当日用户获得{}个获得奖励的激励视频，"),initAdCompletedCount, 2);
        configIds.add(riskConfig.getConfigId());
        riskConfig = createRiskConfig(agentId, "firstCount",
                StrUtil.format("最后{}个获得奖励的激励视频", initFirstCount),  initFirstCount, 2);
        configIds.add(riskConfig.getConfigId());
        riskConfig = createRiskConfig(agentId, "averageRevenue",
                StrUtil.format("平均收益<{}", initAverageRevenue),  initAverageRevenue, 4);
        configIds.add(riskConfig.getConfigId());
        String templateId = IdUtil.getSnowflakeNextIdStr();
        String templateContent = StrUtil.format("当日用户获得{}个获得奖励的激励视频，最后{}个获得奖励的激励视频平均收益<{}",
                initAdCompletedCount, initFirstCount, initAverageRevenue);
        Integer enabled = 2 == param.getAppType() ? 0 : 1; // IOS默认关闭风控
        YtRiskTemplate template = new YtRiskTemplate(templateId,"成本收益限制", templateContent,
                appId + "-766", agentId, 2, appId,
                currentDate, loginUser.getUserId(),null, null,
                enabled,1,1);
        riskMapper.insertTemplate(template);
        YtRiskTemplateConfig templateConfig;
        for (String itemId : configIds) {
            templateConfig = new YtRiskTemplateConfig(templateId, itemId, loginUser.getUserId(), loginUser.getNickName(), currentDate);
            riskMapper.insertTempConfig(templateConfig);
        }
        //风控模版关联应用
        riskMapper.relativeApp(appId, param.getAppName(), template.getTemplateId(), loginUser.getNickName(), loginUser.getUserId());
    }


    private void addTemp746(AppParam param, MiddleUserInfo loginUser) {
        String appId = param.getAppId();
        String agentId = param.getUserId();
        List<String> configIds = new ArrayList<>();
        String configId = IdUtil.getSnowflakeNextIdStr();
        configIds.add(configId);
        YtRiskConfig config = new YtRiskConfig(configId,agentId,"rewardCount","当日前2条获得奖励的激励视频",1,"2",2);
        riskMapper.insertConfigItem(config);
        configId = IdUtil.getSnowflakeNextIdStr();
        configIds.add(configId);
        config = new YtRiskConfig(configId,agentId,"income","总收益为<"+initRevenue,1,initRevenue,4);
        riskMapper.insertConfigItem(config);
        String templateId = IdUtil.getSnowflakeNextIdStr();
        YtRiskTemplateConfig templateConfig;
        for (String itemId : configIds) {
            templateConfig = new YtRiskTemplateConfig(templateId,itemId,loginUser.getUserId(),loginUser.getNickName(),new Date());
            riskMapper.insertTempConfig(templateConfig);
        }
        Integer enabled = 2 == param.getAppType() ? 0 : 1; // IOS默认关闭风控
        YtRiskTemplate template = new YtRiskTemplate(templateId,"最低收益限制",
                "当日前2条获得奖励的激励视频,总收益为<"+initRevenue,appId+"-746",agentId,
                2,appId,new Date(),loginUser.getUserId(),null,
                null,enabled,1,1);
        riskMapper.insertTemplate(template);
        //风控模版关联应用
        riskMapper.relativeApp(appId,param.getAppName(),template.getTemplateId(),
                loginUser.getNickName(),loginUser.getUserId());
    }

    private void addTemp742(AppParam param, MiddleUserInfo loginUser) {
        String appId = param.getAppId();
        String agentId = param.getUserId();
        List<String> configIds = new ArrayList<>();
        String configId = IdUtil.getSnowflakeNextIdStr();
        configIds.add(configId);
        YtRiskConfig config = new YtRiskConfig(configId,agentId,"firstAdCount","当日前4条激励视频",1,"4",2);
        riskMapper.insertConfigItem(config);
        configId = IdUtil.getSnowflakeNextIdStr();
        configIds.add(configId);
        config = new YtRiskConfig(configId,agentId,"haveCount","有2条",1,"2",2);
        riskMapper.insertConfigItem(config);
        configId = IdUtil.getSnowflakeNextIdStr();
        configIds.add(configId);
        config = new YtRiskConfig(configId,agentId,"ecpm","ecpm值为<"+initEcpm,1,initEcpm,4);
        riskMapper.insertConfigItem(config);
        String templateId = IdUtil.getSnowflakeNextIdStr();
        YtRiskTemplateConfig templateConfig;
        for (String itemId : configIds) {
            templateConfig = new YtRiskTemplateConfig(templateId,itemId,loginUser.getUserId(),loginUser.getNickName(),new Date());
            riskMapper.insertTempConfig(templateConfig);
        }
        Integer enabled = 2 == param.getAppType() ? 0 : 1; // IOS默认关闭风控
        YtRiskTemplate template = new YtRiskTemplate(templateId,"激励视频ecpm值控制",
                "当日前4条激励视频,有2条,ecpm值为<"+initEcpm,appId+"-742",agentId,
                2,appId,new Date(),loginUser.getUserId(),null,
                null,enabled,1,1);
        riskMapper.insertTemplate(template);
        //风控模版关联应用
        riskMapper.relativeApp(appId,param.getAppName(),template.getTemplateId(),
                loginUser.getNickName(),loginUser.getUserId());
    }

    /**
     * 处理数据库数据变更操作
     */
    private void changeDataAction(AppParam param, String userId) {
        YtApp app = new YtApp();
        BeanUtil.copyProperties(param, app);
        if(CharSequenceUtil.isNotBlank(param.getAppId())){
            apkMapper.updateOne(app);
        }else{
            app.setAppId(IdUtil.fastSimpleUUID());
            app.setUserId(userId);
            app.setEnabled(1);
            app.setCreateTime(new Date());
            apkMapper.insertOne(app);
        }
    }
}
