package org.jeecg.modules.bytedance.advertise.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.bytedance.advertise.dockapi.MarketingService;
import org.jeecg.modules.bytedance.advertise.mapper.MonitorBytedanceActionTrackUrlMapper;
import org.jeecg.modules.bytedance.advertise.service.IAiBytedanceAdvertiserStrategyService;
import org.jeecg.modules.bytedance.advertise.service.IMonitorBytedanceService;
import org.jeecg.modules.bytedance.advertise.vo.MonitorBytedanceAdVo;
import org.jeecg.modules.bytedance.common.entity.BytedanceOperationLog;
import org.jeecg.modules.bytedance.common.entity.CtopOauthToken;
import org.jeecg.modules.bytedance.common.mapper.BytedanceOperationLogMapper;
import org.jeecg.modules.bytedance.common.service.ICtopOauthTokenService;
import org.jeecg.modules.bytedance.common.service.IUserAllocationService;
import org.jeecg.modules.bytedance.common.utils.Check;
import org.jeecg.modules.bytedance.common.utils.CorpWexinUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;

/**
 * 规则账户清洗数据
 * master 2022-01-19-end
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-11-16
 */
@Slf4j
@Service
public class MonitorBytedanceServiceImpl implements IMonitorBytedanceService {
    @Resource
    private MonitorBytedanceActionTrackUrlMapper monitorBytedanceActionTrackUrlMapper;

    @Resource
    private IAiBytedanceAdvertiserStrategyService aiBytedanceAdvertiserStrategyService;

    @Resource
    private IUserAllocationService userAllocationService;

    @Resource
    private MarketingService marketingServiceImpl;

    @Resource
    private ICtopOauthTokenService tokenService;

    @Resource
    private BytedanceOperationLogMapper bytedanceOperationLogMapper;

    @Resource
    private CorpWexinUtils corpWexinUtils;


    /**
     *
     * @description:新增 第三方监测连接
     *
     * @param monitorBytedanceAdVo
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     * @time: 2022/1/11
     */
    public Result insertAccountTrackUrl(MonitorBytedanceAdVo monitorBytedanceAdVo){
        //账户 查询 第三方监测链接
        List<MonitorBytedanceAdVo> trackUrl = monitorBytedanceActionTrackUrlMapper.getAccountActionTrackUrl(monitorBytedanceAdVo.getAccountId(), null,null);
        if (!Check.isNull(trackUrl)){
            return Result.errorMsg("该账户已配置监测链接，请勿重复设置！");
        }
        monitorBytedanceActionTrackUrlMapper.insertAccountTrackUrl(monitorBytedanceAdVo);

        //添加修改记录
        BytedanceOperationLog bytedanceOperationLog = new BytedanceOperationLog();
        bytedanceOperationLog.setOldData(null);
        bytedanceOperationLog.setNewData(monitorBytedanceAdVo.toString());
        bytedanceOperationLog.setOperationType("头条第三方监测链接-新增");
        bytedanceOperationLog.setOperationContent("账户:"+monitorBytedanceAdVo.getAccountId()+"新增监测链接:"+monitorBytedanceAdVo.getActionTrackUrl());
        bytedanceOperationLog.setCreateById(monitorBytedanceAdVo.getCreateUserId());
        bytedanceOperationLog.setCreateTime(new Date());
        bytedanceOperationLogMapper.insert(bytedanceOperationLog);

        return Result.successMsg("成功",null);
    }


    /**
     *
     * @description: 修改 第三方监测链接
     *
     * @param monitorBytedanceAdVo
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     * @time: 2022/1/11
     */
    @Override
    public Result updAccountActionTrackUrl(MonitorBytedanceAdVo monitorBytedanceAdVo) {
        monitorBytedanceActionTrackUrlMapper.updAccountActionTrackUrl(monitorBytedanceAdVo);
        //添加修改记录
        BytedanceOperationLog bytedanceOperationLog = new BytedanceOperationLog();
        bytedanceOperationLog.setOldData(null);
        bytedanceOperationLog.setNewData(monitorBytedanceAdVo.toString());
        bytedanceOperationLog.setOperationType("头条第三方监测链接-修改");
        bytedanceOperationLog.setOperationContent("账户:"+monitorBytedanceAdVo.getAccountId()+"修改内容。");
        bytedanceOperationLog.setCreateById(monitorBytedanceAdVo.getCreateUserId());
        bytedanceOperationLog.setCreateTime(new Date());
        bytedanceOperationLogMapper.insert(bytedanceOperationLog);
        return Result.successMsg("修改成功", null);
    }

    /**
     *
     * @description: 监测预警-查询
     *
     * @param accountId
     * @param warningFlag
     * @param operatorUserIds
     * @param pageNum
     * @param pageSize
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     * @time: 2022/1/11
     */
    @Override
    public Result selectAccountActionTrackUrlList(String accountId, String warningFlag, Set<String> operatorUserIds,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<MonitorBytedanceAdVo> list = monitorBytedanceActionTrackUrlMapper.getAccountActionTrackUrl(accountId,warningFlag,operatorUserIds);
        PageInfo<MonitorBytedanceAdVo> pageInfo = new PageInfo<MonitorBytedanceAdVo>(list);
        return Result.successMsg("查询成功",pageInfo);
    }




























    /**
     * @description: 监测预警-点击监测链接
     * @param
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     * @time: 2022/01/12
     */
    public Result monitorBytedanceActionTrackUrl(String accountId){
        //查询 配置的点击监测链接
        List<MonitorBytedanceAdVo> accountList = monitorBytedanceActionTrackUrlMapper.getAccountActionTrackUrl(accountId,"1",null);
        if(Check.isNull(accountList)){
            log.info("====accountId:{}======暂无账户配置第三方点击监测链接信息=====",accountId);
            return Result.successMsg("=======accountId:"+accountId+"===暂无账户配置第三方点击监测链接信息=====",null);
        }
        for (MonitorBytedanceAdVo accountInfo : accountList) {
            //校验 拉取后台计划 监测链接
            //根据账户 查询头条计划中的 点击监测链接
            List<MonitorBytedanceAdVo> actionTrackUrlList = monitorBytedanceActionTrackUrlMapper.getBytedancPlanActionTrackUrl(Long.valueOf(accountInfo.getAccountId()));
            if(Check.isNull(actionTrackUrlList)){
                log.info("accountId:=={}====暂无计划信息============",accountInfo.getAccountId());
                continue;
                //return Result.successMsg("accountId:=={"+accountInfo.getAccountId()+"}====暂无计划信息============。",null);
            }
            List<String> planList = new ArrayList<>();
            for (MonitorBytedanceAdVo actiontrackUrl : actionTrackUrlList) {
                //配置中的 点击监测链接 ！= 创建计划中的 点击监测链接
                if (!StringUtils.equals(accountInfo.getActionTrackUrl(),actiontrackUrl.getActionTrackUrl())){
                    //关停计划
                    CtopOauthToken token = tokenService.getTokenByAccountId(Long.valueOf(accountInfo.getAccountId()));
                    marketingServiceImpl.updPlanStatus(token, Arrays.asList(Long.valueOf(actiontrackUrl.getPlanId())),"disable");
                    log.info("accountId:=={}==计划id:{}=====第三方点击监测链接不一致,计划已【关停】============",accountInfo.getAccountId(),actiontrackUrl.getPlanId());
                    planList.add(actiontrackUrl.getPlanId());
                }
            }
            if (!Check.isNull(planList) && planList.size() > 0){
                //发送预警消息
                accountInfo.setPlanIdList(planList);
                sendEnterpriseWeiXinMessage(accountInfo);
                log.info("accountId:=={}==计划id:{}=====第三方点击监测链接不一致,已发送企业微信通知============",accountInfo.getAccountId(),accountInfo.getPlanIdList());
            }
        }
        return Result.successMsg("成功。",null);
    }


    /**
     * 发送 点击监测链接 预警消息
     */
    public void sendEnterpriseWeiXinMessage(MonitorBytedanceAdVo accountInfo){
        String message =  "{0}，您好！您所运营的账户：{1}，其中的广告计划id:{2}，监测链接设置有误，已关停请及时修改！";
        //发送微信通知
        JSONObject jsonObject =  monitorBytedanceActionTrackUrlMapper.getWChatIdByUserId(accountInfo.getOperateUserid());
        String msg = MessageFormat.format(message,accountInfo.getOperateUserName(),String.valueOf(accountInfo.getAccountId()),String.join("，",accountInfo.getPlanIdList()));
        corpWexinUtils.sendMessageByWeChatId(jsonObject,msg);
    }



    /**
     *
     * @description: 自动投放中 账户自动创建时 校验第三方监测链接
     *
     * @param token
     * @param accountId 账户id
     * @param converId 转化目标id
     * @param planId 计划id
     * @return: void
     * @author: zianY
     * @time: 2022/1/13
     */
    public void trackUrlContrast(CtopOauthToken token,String accountId,String converId,String planId){
        //校验 账户自动投放配置中 监测链接
        //查询 链接配置
        List<MonitorBytedanceAdVo> monitorBytedanceAdVos = monitorBytedanceActionTrackUrlMapper.getAccountActionTrackUrl(String.valueOf(accountId),"1",null);
        if (!Check.isNull(monitorBytedanceAdVos)){
            MonitorBytedanceAdVo bytedanceAdVo = monitorBytedanceAdVos.get(0);
            // 账户id  和 转化id 查询 第三方监测链接
            Result resultConvert = aiBytedanceAdvertiserStrategyService.readToolConvertInfo(accountId,converId);
            if (resultConvert.isSuccess()){
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(resultConvert.getResult());
                String action_track_url = jsonObject.getString("action_track_url");
                //自动投放账户配置中的链接 ！= 监测链接配置
                if (!StringUtils.equals(action_track_url,bytedanceAdVo.getActionTrackUrl())){
                    //关停计划
                    marketingServiceImpl.updPlanStatus(token, Arrays.asList(Long.valueOf(planId)),"disable");
                    //发送预警消息
                    sendEnterpriseWeiXinMessage(bytedanceAdVo);
                    log.info("accountId:=={}==目标转化id:{}=====自动投创建====第三方点击监测链接与自动投放配置不一致,已发送企业微信通知============",bytedanceAdVo.getAccountId(),bytedanceAdVo.getConvertId());
                }
            }
            log.info("accountId:=={}==目标转化id:{}=====第三方点击监测链接获取失败",accountId,converId);
        }
        log.info("accountId:=={}==目标转化id为空。",accountId);
    }


}
