package cn.com.ctop.kuaishou.modules.clean.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
import cn.com.ctop.common.module.service.ISysRoleExtService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouUpdateService;
import cn.com.ctop.kuaishou.modules.clean.entity.KuaiShouAccountCleanLogInfo;
import cn.com.ctop.kuaishou.modules.clean.entity.KuaiShouAccountCleanTemplateInfo;
import cn.com.ctop.kuaishou.modules.clean.mapper.KuaishouAccountCleanTemplateMapper;
import cn.com.ctop.kuaishou.modules.clean.service.KuaiShouAccountCleanService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description: 快手-账户清理
 * @Author: zzy
 * @Date: 2021-07-20
 * @Version: V1.0
 */
@Service
@Slf4j
public class KuaiShouAccountCleanServiceImpl implements KuaiShouAccountCleanService {
    @Resource
    KuaishouAccountCleanTemplateMapper kuaishouAccountCleanTemplateMapper;

    @Resource
    private ISysRoleExtService sysRoleService;

    @Resource
    CtopOauthTokenMapper ctopOauthTokenMapper;

    @Resource
    IKuaiShouUpdateService iKuaiShouUpdateService;

    /**
     * 创建规则模板
     *
     * @param kuaiShouAccountCleanTemplateInfo
     * @return
     */
    @Override
    public Result createCleanTemplate(KuaiShouAccountCleanTemplateInfo kuaiShouAccountCleanTemplateInfo) {
        Result result = new Result();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        Random rand = new Random();
        int id = 100000 + rand.nextInt(99900000);
        //设置6-8位数字
        kuaiShouAccountCleanTemplateInfo.setId(String.valueOf(id));
        //设置应用媒体 固定写死
        kuaiShouAccountCleanTemplateInfo.setAppliedMedia("快手");
        //未绑定账户  设置暂停状态
        kuaiShouAccountCleanTemplateInfo.setStatus(String.valueOf(1));
        //设置创建日期
        kuaiShouAccountCleanTemplateInfo.setCreateTime(sd.format(new Date()));
        try {
            kuaishouAccountCleanTemplateMapper.saveAccountCleanTemplate(kuaiShouAccountCleanTemplateInfo);
            result.success("创建模板成功");
        } catch (Exception e) {
            log.info("保存模板失败:{}", e.toString());
            result.error500("创建模板失败");
        }
        return result;
    }

    /**
     * 查询模板列表
     *
     * @param templateId 模板id  createUser创建人
     * @return
     */
    @Override
    public Result getTemplateList(String templateId, String createUser, String userId, String pageNum, String pageSize) {
        Result result = new Result();
        PageHelper pageHelper = new PageHelper();
        List<KuaiShouAccountCleanTemplateInfo> templateList = new ArrayList<>();
        try {
            //查询当前登录人角色
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            if (roleCode != null && roleCode.equals("admin")) {
                //管理员查询全部
                templateList = kuaishouAccountCleanTemplateMapper.getTemplateList(templateId, createUser, null);
            } else {
                //其他角色查询自己拥有的
                templateList = kuaishouAccountCleanTemplateMapper.getTemplateList(templateId, createUser, userId);
            }
            PageInfo pageInfo = new PageInfo(templateList);
            result.success("查询成功");
            result.setResult(pageInfo);
        } catch (Exception e) {
            log.info("查询失败:{}", e.toString());
            result.error500("查询失败");
        }
        return result;
    }

    /**
     * 预览模板
     *
     * @param templateId 模板id
     * @return
     */
    @Override
    public Result previewTemplate(String templateId) {
        Result result = new Result();
        try {
            KuaiShouAccountCleanTemplateInfo infoById = kuaishouAccountCleanTemplateMapper.getInfoById(templateId);
            result.success("查询成功");
            result.setResult(infoById);
        } catch (Exception e) {
            log.info("查询失败:{}", e.toString());
            result.error500("查询失败");
        }
        return result;
    }

    /**
     * 推送模板
     *
     * @param templateId 模板id，accountId 账户id
     * @return
     */
    @Override
    public Result pushTemplate(String templateId, String accountId) {
        Result result = new Result();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        try {
            //查询模板关联个数
            int accountAssociatedSize = kuaishouAccountCleanTemplateMapper.getAccountAssociatedSize(accountId);
            //无关联模板 推送模板
            if (accountAssociatedSize == 0) {
                kuaishouAccountCleanTemplateMapper.savePushTemplateAssociated(templateId, accountId, sd.format(new Date()));
                //修改模板状态，改为开启
                kuaishouAccountCleanTemplateMapper.updateTemplateStatus(templateId, "0");
                result.success("推送成功");
            } else {
                result.success("推送失败，此账户已关联模板");
            }
        } catch (Exception e) {
            log.info("推送失败:{}", e.toString());
            result.error500("推送失败");
        }
        return result;
    }

    /**
     * 修改模板
     *
     * @param kuaiShouAccountCleanTemplateInfo
     * @return
     */
    @Override
    public Result updateTemplate(KuaiShouAccountCleanTemplateInfo kuaiShouAccountCleanTemplateInfo) {
        Result result = new Result();
        try {
            if (!StringUtil.isBlank(kuaiShouAccountCleanTemplateInfo.getId())) {
                kuaishouAccountCleanTemplateMapper.updateTemplate(kuaiShouAccountCleanTemplateInfo);
                result.success("修改成功");
            } else {
                result.success("id不能为空");
            }
        } catch (Exception e) {
            log.info("修改失败:{}", e.toString());
            result.error500("修改失败");
        }
        return result;
    }

    /**
     * 开启/暂停模板
     *
     * @param templateId 模板id   status状态  0-开始   1-暂停
     * @return
     */
    @Override
    public Result updateTemplateStatus(String templateId, String status) {
        Result result = new Result();
        String message = "修改";
        if (status.equals("0")) {
            message = "开启";
        }
        if (status.equals("1")) {
            message = "关闭";
        }
        try {
            //修改模板状态
            kuaishouAccountCleanTemplateMapper.updateTemplateStatus(templateId, status);
            result.success(message + "成功");
        } catch (Exception e) {
            log.info(message + "失败:{}", e.toString());
            result.error500(message + "失败");
        }
        return result;
    }

    /**
     * 解除模板绑定
     *
     * @param templateId 模板id，accountId 账户id
     * @return
     */
    @Override
    public Result removeBinding(String templateId, String accountId) {
        Result result = new Result();
        try {
            kuaishouAccountCleanTemplateMapper.removeBinding(templateId, accountId);
            result.success("解除绑定成功");
        } catch (Exception e) {
            log.info("解除绑定失败:{}", e.toString());
            result.error500("解除绑定失败");
        }
        return result;
    }

    @Override
    public Result getCleanUpLog(String userName, String accountId, String pageNum, String pageSize) {
        Result result = new Result();
        try {
            PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            List<KuaiShouAccountCleanLogInfo> cleanUpLog = kuaishouAccountCleanTemplateMapper.getCleanUpLog(userName, accountId);
            PageInfo pageInfo = new PageInfo(cleanUpLog);
            result.success("查询成功");
            result.setResult(pageInfo);
        } catch (Exception e) {
            log.info("查询失败:{}", e.toString());
            result.error500("查询失败");
        }
        return result;
    }

    /**
     * 查询个人清理模板列表
     *
     * @param accountId 账户id  userName运营名称  userId当前登录人id
     * @return
     */
    @Override
    public Result getMyselfTemplateList(String accountId, String userName, String userId, String pageNum, String pageSize) {
        Result result = new Result();
        PageHelper pageHelper = new PageHelper();
        List<KuaiShouAccountCleanTemplateInfo> templateList = new ArrayList<>();
        try {
            //查询当前登录人角色
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            if (roleCode != null && roleCode.equals("admin")) {
                //管理员查询全部
                templateList = kuaishouAccountCleanTemplateMapper.getMyselfTemplateList(accountId, userName, null);
            } else {
                //其他角色查询自己拥有的
                templateList = kuaishouAccountCleanTemplateMapper.getMyselfTemplateList(accountId, userName, userId);
            }
            PageInfo pageInfo = new PageInfo(templateList);
            result.success("查询成功");
            result.setResult(pageInfo);
        } catch (Exception e) {
            log.info("查询失败:{}", e.toString());
            result.error500("查询失败");
        }
        return result;
    }

    /**
     * 根据清理模板清理账户
     *
     * @param
     * @return
     */
    @Override
    public Result cleanAccount() {
        Result result = new Result();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map optimizationObjectiveMap = new HashMap();
        //优化目标 activation:激活数 bclick:行为数  formSize :表单数 pay:付费  roi:首日roi   evocativeApplication:唤起应用
        // effectiveClues:有效线索 creditApp:授信-APP creditGrant:授信-落地页  finishedPieceApp:完件数-APP  finishedPieceGrant:完件数-落地页  registered:注册
        optimizationObjectiveMap.put("180", "activation");
        optimizationObjectiveMap.put("53", "formSize");
        optimizationObjectiveMap.put("190", "pay");
        optimizationObjectiveMap.put("324", "evocativeApplication");
        optimizationObjectiveMap.put("396", "registered");
        try {
            //查询需要执行的规则模板
            List<KuaiShouAccountCleanTemplateInfo> templateListBystatus = kuaishouAccountCleanTemplateMapper.getTemplateListBystatus();
            if (!templateListBystatus.isEmpty()) {
                templateListBystatus.stream().forEach(ob -> {
                    AtomicInteger count= new AtomicInteger();
                    if (ob.getAccountId() != null) {
                        StringBuilder unitIds = new StringBuilder();
                        //获取各项优化目标
                        List<String> optimizationObjectiveList = Arrays.asList(ob.getOptimizationObjective().split(","));
                        //获取清理时间范围
                        String cleanTime = ob.getCleanTime();
                        //计算最早清理时间
                        Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
                        calendar.add(Calendar.DATE, -Integer.parseInt(cleanTime));
                        String startDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
                        AtomicReference<Boolean> falg = new AtomicReference<>(true);
                        //查询改账户下所有组
                        List<Map> groupByAccount = kuaishouAccountCleanTemplateMapper.getGroupByAccount(ob.getAccountId());
                        if (!groupByAccount.isEmpty()) {
                            groupByAccount.stream().forEach(obj -> {
                                if (obj.get("unitId") != null && obj.get("type") != null) {
                                    String unitId = Long.toString((Long) obj.get("unitId")) ;
                                    //OCPM
                                    String type = Integer.toString((Integer) obj.get("type")) ;
                                    if(optimizationObjectiveMap.get(type)!=null){
                                        String optimizationObjective= (String) optimizationObjectiveMap.get(type);
                                        //查询组是否符合清理规则
                                        String groupMessage = kuaishouAccountCleanTemplateMapper.getGroupMessage(ob, optimizationObjective, startDate,unitId);
                                        if(groupMessage!=null){
                                            count.getAndIncrement();
                                            //符合清理规则清理
                                            //获取Token
                                            CtopOauthToken ctopOauthToken = ctopOauthTokenMapper.selectByAccountId(Long.parseLong(ob.getAccountId()));
                                            if (ctopOauthToken != null) {
                                                //修改广告组状态
                                                Map<String, Object> resultMap = iKuaiShouUpdateService.updateUnitStatus(ctopOauthToken.getAccessToken(), Long.parseLong(ob.getAccountId()), Long.parseLong(unitId), Integer.parseInt(ob.getPerformOperations()), null);
                                                Boolean resultFlag = (Boolean) resultMap.get("success");
                                                //判断有没有失败
                                                if (resultFlag) {
                                                    //清理成功
                                                    unitIds.append(unitId).append(",");
                                                    log.info("组"+unitId+"已被清理");
                                                }else {
                                                    //清理失败
                                                    log.info("组"+unitId+"清理失败:{}",resultMap.get("message"));
                                                    falg.set(false);
                                                }
                                            }
                                        }
                                    }

                                }
                            });
                        }


                        if (count.get()>0 && falg.get()) {
                            //修改成功插入日志记录
                            KuaiShouAccountCleanLogInfo kuaiShouAccountCleanLogInfo = new KuaiShouAccountCleanLogInfo();
                            //设置账户id
                            kuaiShouAccountCleanLogInfo.setAccountId(ob.getAccountId());
                            // 1-投放、2-暂停、3-删除
                            kuaiShouAccountCleanLogInfo.setOperationType(ob.getPerformOperations());
                            //设置运营
//                            Map<String, String> map = kuaishouAccountCleanTemplateMapper.getUserNameByAccountId(ob.getAccountId());
//                            String authName = "";
//                            if (map != null) {
//                                kuaiShouAccountCleanLogInfo.setUserName(map.get("userName"));
//                                authName = map.get("authName");
//                            }
                            //设置时间
                            kuaiShouAccountCleanLogInfo.setCreateTime(sd.format(new Date()));
                            //操作类型
                            String operationType = null;
                            if (ob.getPerformOperations().equals("2")) {
                                operationType = "暂停";
                            }
                            if (ob.getPerformOperations().equals("3")) {
                                operationType = "删除";
                            }
                            //执行信息
                            String textMessage = "清理规则执行:  账户:" + ob.getAccountId() + ", 授权名称: " + ob.getCreateUser() + ",推广组:" + unitIds + "已经被清理规则" + operationType;
                            kuaiShouAccountCleanLogInfo.setExecutiveInformation(textMessage);
                            kuaiShouAccountCleanLogInfo.setTemplateId(ob.getId());
                            kuaiShouAccountCleanLogInfo.setCreateTemplateId(ob.getCreateId());
                            kuaiShouAccountCleanLogInfo.setUserName(ob.getCreateUser());
                            kuaishouAccountCleanTemplateMapper.saveCleamLog(kuaiShouAccountCleanLogInfo);
                        }
                    }
                });
            }

            result.success("执行计划成功");
        } catch (Exception e) {
            log.info("执行计划失败:{}", e.toString());
            result.error500("执行计划失败");
        }
        return result;
    }

}
