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.mapper.KuaiShouDailyReportTaskMapper;
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.constant.KuaishouInterfaceConstant;
import com.xxl.job.executor.report.mapper.KuaishouReportDailyCampaignMapper;
import com.xxl.job.executor.report.mapper.KuaishouReportDailyCreativeMapper;
import com.xxl.job.executor.report.mapper.KuaishouReportDailyGroupMapper;
import com.xxl.job.executor.report.mapper.KuaishouReportDailyImageMapper;
import com.xxl.job.executor.utils.Check;
import com.xxl.job.executor.utils.HttpUtils;
import com.xxl.job.executor.utils.LoadFileUtil;
import com.xxl.job.executor.utils.PropertiesUtils;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分天记录表
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-03-12
 */
@Slf4j
@Service
public class KuaiShouDailyReportTaskServiceImpl extends ServiceImpl<KuaiShouDailyReportTaskMapper, KuaiShouDailyReportTask> implements IKuaiShouDailyReportTaskService {
    @Value("${jeecg.path.report-daily}")
    private String downloadPath;
    @Autowired
    private KuaishouReportDailyCampaignMapper reportDailyCampaignMapper;
    @Autowired
    private KuaishouReportDailyGroupMapper reportDailyGroupMapper;
    @Autowired
    private KuaishouReportDailyCreativeMapper reportDailyCreativeMapper;
    @Autowired
    private KuaiShouReportDailyMaterialMapper kuaishouReportDailyMaterialMapper;
    @Autowired
    private IKuaiShouHistoryReportTaskService kuaiShouHistoryReportTaskService;
    @Autowired
    private KuaishouReportDailyImageMapper kuaishouReportDailyImageMapper;

    @Override
    public void formatCreativeDailyReportData(Long accountId, String statDate) {
        reportDailyCreativeMapper.formatCreativeDailyReportData(accountId, statDate);
    }

    /**
     * 获取任务列表
     */
    @Override
    public void getTaskList(Long accountId, String token, String statDate) {
        QueryWrapper<KuaiShouDailyReportTask> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.eq("task_status", 0);
        taskQueryWrapper.eq("account_id", accountId);
        taskQueryWrapper.eq("stat_date", statDate);
        taskQueryWrapper.orderByDesc("create_time");
        List<KuaiShouDailyReportTask> dailyTaskList = this.list(taskQueryWrapper);
        if (!Check.isNull(dailyTaskList)) {
            for (KuaiShouDailyReportTask task : dailyTaskList) {
                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);
                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);
                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, task);
                                        } else if (taskStatus == 3) {
                                            task.setTaskStatus(3);
                                            task.setUpdateTime(new Date());
                                            this.updateById(task);
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        log.error("快手获取任务列表返回错误，accountId：{}，返回结果：{}", task.getAccountId(), resultJson);
                    }
                } else {
                    log.error("快手获取任务列表返回信息为空，accountId：{}", task.getAccountId());
                }
            }
        }
    }


    private void loadFile(String token, KuaiShouDailyReportTask task) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.ASYNC_TASK_DOWNLOAD;
            String fileName = task.getAccountId() + "_" + task.getStatDate() + "_" + 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 + task.getStatDate() + "//", url, token, fileName);
            if (!Check.isNull(localPath)) {
                Map<String, Object> deleteMap = new HashMap<>();
                deleteMap.put("account_id", task.getAccountId());
                deleteMap.put("stat_date", task.getStatDate());
                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.deleteByAccountIdAndStatDate(task.getAccountId(), task.getStatDate());
                    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);
                                kuaiShouHistoryReportTaskService.getMd5(task.getStatDate(), 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);
        }
        task.setUpdateTime(new Date());
        this.updateById(task);
    }

}
