package com.xxl.job.executor.batch.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.executor.batch.entity.KuaiShouDailyReportTask;
import com.xxl.job.executor.batch.entity.KuaiShouHistoryReportTask;
import com.xxl.job.executor.batch.entity.vo.KuaiShouReportDailyMaterialVo;
import com.xxl.job.executor.batch.entity.vo.VideoGetvo;
import com.xxl.job.executor.batch.mapper.KuaiShouHistoryReportTaskMapper;
import com.xxl.job.executor.batch.mapper.KuaiShouReportDailyMaterialMapper;
import com.xxl.job.executor.batch.service.IKuaiShouDailyReportTaskService;
import com.xxl.job.executor.batch.service.IKuaiShouHistoryReportTaskService;
import com.xxl.job.executor.common.entity.CtopOauthToken;
import com.xxl.job.executor.common.service.ICtopOauthTokenService;
import com.xxl.job.executor.constant.KuaishouInterfaceConstant;
import com.xxl.job.executor.report.entity.KuaiShouReportDailyMaterial;
import com.xxl.job.executor.report.mapper.*;
import com.xxl.job.executor.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 快手历史数据任务记录
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-03-09
 */
@Slf4j
@Service
public class KuaiShouHistoryReportTaskServiceImpl extends ServiceImpl<KuaiShouHistoryReportTaskMapper, KuaiShouHistoryReportTask> implements IKuaiShouHistoryReportTaskService {
    @Value("${jeecg.path.report-history}")
    private String downloadPath;
    static List<Integer> historyTypeList;
    static List<Integer> dailyTypeList;
    @Autowired
    private ICtopOauthTokenService ctopOauthTokenService;
    @Autowired
    private KuaishouReportDailyAccountMapper reportDailyAccountMapper;
    @Autowired
    private KuaishouReportDailyCampaignMapper reportDailyCampaignMapper;
    @Autowired
    private KuaishouReportDailyGroupMapper reportDailyGroupMapper;
    @Autowired
    private KuaishouReportDailyCreativeMapper reportDailyCreativeMapper;
    @Autowired
    private IKuaiShouDailyReportTaskService dailyReportTaskService;
    @Autowired
    private KuaiShouReportDailyMaterialMapper kuaishouReportDailyMaterialMapper;
    @Autowired
    private KuaishouReportDailyImageMapper kuaishouReportDailyImageMapper;


    @Override
    public void createTask(Long accountId, String token, String startDate, String endDate, String taskType) {
        if (Check.isNull(accountId) || Check.isNull(token)) {
            log.error("token或accountId为空");
            return;
        }
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.ASYNC_TASK_CREAT;
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token);
            JSONObject param = new JSONObject();
            param.put("advertiser_id", accountId);
            JSONObject taskParams = new JSONObject();
            taskParams.put("start_date", startDate);
            taskParams.put("end_date", endDate);

            if (null != taskType && taskType.equals(CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_DAILY)) {
                if (Check.isNull(dailyTypeList)) {
                    getDailyTypeList();
                }
                for (int i = 0; i < dailyTypeList.size(); i++) {
                    Integer type = dailyTypeList.get(i);
                    String taskName = accountId + "_" + type + "_" + System.currentTimeMillis();
                    param.put("task_name", taskName);
                    taskParams.put("view_type", type);
                    param.put("task_params", taskParams);

                    String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    if (!Check.isNull(resultJson)) {
                        Integer code = resultJson.getInteger("code");
                        if (code == 0) {
                            JSONObject dataJson = resultJson.getJSONObject("data");
                            KuaiShouDailyReportTask dailyReportTask = new KuaiShouDailyReportTask();
                            dailyReportTask.setAccountId(accountId);
                            dailyReportTask.setStatDate(endDate);
                            dailyReportTask.setTaskId(dataJson.getString("task_id"));
                            dailyReportTask.setViewType(type);
                            dailyReportTask.setTaskStatus(0);
                            dailyReportTask.setTaskName(taskName);
                            dailyReportTaskService.save(dailyReportTask);
                        } else {
                            log.error("快手分天报表请求失败，accountId:{},返回数据:{}", accountId, resultJson);
                        }
                    }
                }
            } else {
                if (Check.isNull(historyTypeList)) {
                    getHistoryTypeList();
                }
                for (int i = 0; i < historyTypeList.size(); i++) {
                    Integer type = historyTypeList.get(i);
                    String taskName = accountId + "_" + type + "_" + System.currentTimeMillis();
                    param.put("task_name", taskName);
                    taskParams.put("view_type", type);
                    param.put("task_params", taskParams);
                    String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    log.info("请求状态返回数据:{}", resultJson);
                    if (!Check.isNull(resultJson)) {
                        Integer code = resultJson.getInteger("code");
                        if (code == 0) {
                            JSONObject dataJson = resultJson.getJSONObject("data");
                            KuaiShouHistoryReportTask reportTask = new KuaiShouHistoryReportTask();
                            reportTask.setAccountId(accountId);
                            reportTask.setStartDate(startDate);
                            reportTask.setEndDate(endDate);
                            reportTask.setTaskId(dataJson.getString("task_id"));
                            reportTask.setViewType(type);
                            reportTask.setTaskStatus(0);
                            reportTask.setTaskName(taskName);
                            this.save(reportTask);
                        } else {
                            log.error("快手历史报表请求失败，accountId:{},返回数据:{}", accountId, resultJson);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取任务列表
     */
    @Override
    public void getTaskList() {
        log.info("开始历史数据文件检查下载");
        QueryWrapper<KuaiShouHistoryReportTask> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.eq("task_status", 0);
        taskQueryWrapper.orderByDesc("create_time");
        List<KuaiShouHistoryReportTask> taskList = this.list(taskQueryWrapper);
        if (!Check.isNull(taskList)) {
            for (KuaiShouHistoryReportTask task : taskList) {
                CtopOauthToken token = ctopOauthTokenService.getTokenByAccountId(task.getAccountId());
                if (!Check.isNull(token)) {
                    String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.ASYNC_TASK_LIST;
                    Map<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/json");
                    headers.put("Access-Token", token.getAccessToken());
                    JSONObject param = new JSONObject();
                    param.put("advertiser_id", task.getAccountId());
                    JSONArray taskIds = new JSONArray();
                    taskIds.add(task.getTaskId());
                    param.put("task_ids", taskIds);
                    String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    log.info("请求状态返回数据:{}", resultJson);
                    if (!Check.isNull(resultJson)) {
                        Integer code = resultJson.getInteger("code");
                        if (code == 0) {
                            JSONObject dataJson = resultJson.getJSONObject("data");
                            if (!Check.isNull(dataJson)) {
                                JSONArray details = dataJson.getJSONArray("details");
                                if (!Check.isNull(details)) {
                                    for (int i = 0; i < details.size(); i++) {
                                        JSONObject detailJson = details.getJSONObject(i);
                                        if (!Check.isNull(detailJson)) {
                                            Integer taskStatus = detailJson.getInteger("task_status");
                                            if (taskStatus == 2) {
                                                loadFile(token.getAccessToken(), task);
                                            } else if (taskStatus == 3) {
                                                task.setTaskStatus(3);
                                                this.updateById(task);
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            log.error("快手获取任务列表返回错误，accountId：{}，返回结果：{}", task.getAccountId(), resultJson);
                        }
                    }
                }
            }
        }
    }


    private void loadFile(String token, KuaiShouHistoryReportTask task) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.ASYNC_TASK_DOWNLOAD;
            String fileName = task.getAccountId() + "_" + task.getViewType() + ".csv";
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("advertiser_id", task.getAccountId());
            requestMap.put("task_id", task.getTaskId());
            String localPath = LoadFileUtil.downloadByUrl(requestMap, downloadPath, url, token, fileName);
            if (!Check.isNull(localPath)) {
                Map<String, Object> deleteMap = new HashMap<>();
                deleteMap.put("account_id", task.getAccountId());

                if (task.getViewType() == 1) {
                    reportDailyAccountMapper.deleteByMap(deleteMap);
                    reportDailyAccountMapper.loadAccountDailyReport(task.getAccountId(), localPath);
                } else if (task.getViewType() == 2) {
                    reportDailyCampaignMapper.deleteByMap(deleteMap);
                    reportDailyCampaignMapper.loadCampaignDailyReport(task.getAccountId(), localPath);

                } else if (task.getViewType() == 3) {
                    reportDailyGroupMapper.deleteByMap(deleteMap);
                    reportDailyGroupMapper.loadGroupDailyReport(task.getAccountId(), localPath);

                } else if (task.getViewType() == 4) {
                    reportDailyCreativeMapper.deleteByMap(deleteMap);
                    reportDailyCreativeMapper.loadCreativeDailyReport(task.getAccountId(), localPath);

                } else if (task.getViewType() == 10) {
                    reportDailyCreativeMapper.deleteByAccountId(task.getAccountId());
                    reportDailyCreativeMapper.loadProgramCreativeDailyReport(task.getAccountId(), localPath);

                } else if (task.getViewType() == 5) {
                    kuaishouReportDailyMaterialMapper.deleteByMap(deleteMap);
                    kuaishouReportDailyMaterialMapper.loadMaterialDailyReport(task.getAccountId(), localPath);
                    Thread thread = new Thread() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1 * 500L);
                                getMd5(null, task.getAccountId());
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                    };
                    thread.start();
                } else if (task.getViewType() == 7) {
                    kuaishouReportDailyImageMapper.deleteByMap(deleteMap);
                    //封面报表
                    kuaishouReportDailyImageMapper.loadImageDailyReport(task.getAccountId(), localPath);
                    //清洗数据
                    kuaishouReportDailyImageMapper.updateImageReportCode();
                    kuaishouReportDailyImageMapper.updateImageReportUserId();
                    kuaishouReportDailyImageMapper.updateImageReportRealname();
                }


            }
            task.setTaskStatus(4);

        } catch (Exception e) {
            e.printStackTrace();
            task.setTaskStatus(5);
        }
        this.updateById(task);

    }


    private void getHistoryTypeList() {

        historyTypeList = new ArrayList<>();
        historyTypeList.add(1);
        historyTypeList.add(2);
        historyTypeList.add(3);
        historyTypeList.add(4);
        historyTypeList.add(5);
        historyTypeList.add(7);
        historyTypeList.add(10);


    }

    private void getDailyTypeList() {
        dailyTypeList = new ArrayList<>();
        dailyTypeList.add(2);
        dailyTypeList.add(3);
        dailyTypeList.add(4);
        dailyTypeList.add(5);
        dailyTypeList.add(7);
        dailyTypeList.add(10);
    }


    static ExecutorService executorService = Executors.newFixedThreadPool(30);

    @Override
    public void getMd5(String statDate, Long accountId) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                List<KuaiShouReportDailyMaterialVo> photoList = kuaishouReportDailyMaterialMapper.getPhotoList(accountId, statDate);
                if (!Check.isNull(photoList)) {
                    for (KuaiShouReportDailyMaterialVo materialVo : photoList) {
                        Long photoId = materialVo.getPhotoId();
                        VideoGetvo videoGetvo = kuaishouReportDailyMaterialMapper.getVideoGetByPhotoId(photoId);
                        if (!Check.isNull(videoGetvo)) {
                            QueryWrapper<KuaiShouReportDailyMaterial> updateQueryWrapper = new QueryWrapper<>();
                            updateQueryWrapper.eq("photo_id", photoId);
                            if (!Check.isNull(statDate)) {
                                updateQueryWrapper.eq("stat_date", statDate);
                            }

                            updateQueryWrapper.isNull("signature");
                            KuaiShouReportDailyMaterial material = new KuaiShouReportDailyMaterial();
                            material.setSignature(videoGetvo.getSignature());
                            material.setChannelType(videoGetvo.getChannelType());
                            kuaishouReportDailyMaterialMapper.update(material, updateQueryWrapper);
                            log.info("修改成功：photoId:{},accountId:{}", photoId, accountId);
                        }

                    }
                }
            }
        });

    }

    @Override
    public void getMd5V2(String statDate) {
        List<KuaiShouReportDailyMaterialVo> photoList = kuaishouReportDailyMaterialMapper.getPhotoListByDate(statDate);
        if (!Check.isNull(photoList)) {
            for (KuaiShouReportDailyMaterialVo materialVo : photoList) {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        Long photoId = materialVo.getPhotoId();
                        VideoGetvo videoGetvo = kuaishouReportDailyMaterialMapper.getVideoGetByPhotoId(photoId);
                        if (!Check.isNull(videoGetvo)) {
                            QueryWrapper<KuaiShouReportDailyMaterial> updateQueryWrapper = new QueryWrapper<>();
                            updateQueryWrapper.eq("photo_id", photoId);
                            if (!Check.isNull(statDate)) {
                                updateQueryWrapper.eq("stat_date", statDate);
                            }
                            KuaiShouReportDailyMaterial material = new KuaiShouReportDailyMaterial();
                            material.setSignature(videoGetvo.getSignature());
                            material.setChannelType(videoGetvo.getChannelType());
                            kuaishouReportDailyMaterialMapper.update(material, updateQueryWrapper);
                        }
                    }
                });
            }
        }


    }


}
