package cn.com.ctop.job.bytedance.handler;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.Project;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IProjectService;
import cn.com.ctop.common.module.service.ISendMessageService;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.toutiao.modules.material.entity.ByteDanceAdvertisePlan;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceAdvertisePlanService;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceCreativeService;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class BytedanceMonitoringLinksCheckJob {
    @Autowired
    private IUserAllocationService allocationService;
    @Autowired
    private IByteDanceAdvertisePlanService advertisePlanService;
    @Autowired
    private IByteDanceCreativeService creativeService;
    @Autowired
    private ISendMessageService sendMessageService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ICtopOauthTokenService tokenService;

    @XxlJob("bytedanceMonitoringLinksCheckJob")
    public void execute() throws Exception{
        List<Project> projects = projectService.listByMediaType(3,1);
        if(null==projects||projects.isEmpty()){
            return ;
        }
        for (Project project:projects) {
            List<UserAllocation>allocations = allocationService.getByParams(project.getId(),null,0);
            if(null==allocations||allocations.isEmpty()){
                continue;
            }
            for(UserAllocation allocation:allocations){
                CtopOauthToken token = tokenService.getTokenByAccountId(allocation.getAccountId());
                List<ByteDanceAdvertisePlan> plans = advertisePlanService.getAllPlans(allocation.getAccountId(), DateUtils.formatDate(new Date()));
                if(null!=plans&&!plans.isEmpty()){
                    for (ByteDanceAdvertisePlan plan:plans) {
                        Map<String, Object> creativeDetail = creativeService.getCreativeDetail(token, plan.getId());
                        if(null!=creativeDetail.get("data")){
                            JSONObject data = (JSONObject) creativeDetail.get("data");
                            checkMonitorLink(data,plan,allocation);
                        }
                    }
                }
            }
        }
        XxlJobHelper.log("监测链接检查完成");
    }

    private void checkMonitorLink(JSONObject data, ByteDanceAdvertisePlan plan, UserAllocation allocation) {
        String downloadUrl = plan.getDownloadUrl();
        boolean errorflag = false;
        String errorMsg = "";
        String token = plan.getName().split("-")[0];
        if(null!=token&& "衍生计划".equals(token)){
            token = plan.getName().split("-")[1];
        }
        String tokenInfo = "surl_token="+token;
        String appType = plan.getAppType();

        if(null!=downloadUrl){
            if(null!=appType&& "APP_IOS".equals(appType)){
//                if(!downloadUrl.equals("https://apps.apple.com/cn/app/id1468454200")){
                if(!downloadUrl.contains("https://apps.apple.com/cn/app")){
                    errorMsg+= "应用下载链接填写异常;";
                    errorflag = true;
                }
            }
            if(null!=appType&& "APP_ANDROID".equals(appType)){
                if(!downloadUrl.contains(token)){
                    errorMsg+= "应用下载链接填写异常;";
                    errorflag = true;
                }
            }
        }
        //展示监测链接
        String trackUrl = data.getString("trackUrl");
        if(null!=trackUrl&&!"".equals(trackUrl.trim())){
            if(!trackUrl.contains(tokenInfo)){
                errorMsg+= "展示监测链接填写异常;";
                errorflag = true;
            }
        }
        //点击监测链接
        String actionTrackUrl = data.getString("actionTrackUrl");
        if(null!=actionTrackUrl&&!"".equals(actionTrackUrl.trim())){
            if(null!=appType&& "APP_IOS".equals(appType)){
                if(!actionTrackUrl.contains(tokenInfo)||!actionTrackUrl.contains("app_platform=ios")){
                    errorMsg+= "点击监测链接填写异常;";
                    errorflag = true;
                }
            }
            if(null!=appType&& "APP_ANDROID".equals(appType)){
                if(!actionTrackUrl.contains(tokenInfo)||!actionTrackUrl.contains("tt/")){
                    errorMsg+= "点击监测链接填写异常;";
                    errorflag = true;
                }
            }
        }
        //视频有效播放监测链接
        String videoPlayEffectiveTrackUrl = data.getString("videoPlayEffectiveTrackUrl");
        if(null!=videoPlayEffectiveTrackUrl&&!"".equals(videoPlayEffectiveTrackUrl.trim())){
            if(!videoPlayEffectiveTrackUrl.contains(tokenInfo)){
                errorMsg+= "视频有效播放监测链接填写异常;";
                errorflag = true;
            }
        }
        if(errorflag){
            sendMessage(allocation,"警告：账户:"+allocation.getAuthName()+"(id:"+allocation.getAccountId()+")下的广告计划:"+plan.getName()+"(id:"+plan.getId()+")"+"监测链接异常>>"+errorMsg);
        }
    }
    private void sendMessage(UserAllocation allocation, String errorMsg) {
        sendMessageService.sendMessage(allocation.getUserId(),errorMsg);
    }
}
