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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.*;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouDailyReportTask;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouHistoryReportTask;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouHistoryReportTaskMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouDailyReportTaskService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouHistoryReportTaskService;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyAccountMapper;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyCampaignMapper;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyCreativeMapper;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyGroupMapper;
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 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;

/**
 * 快手历史数据任务记录
 *
 * @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;

    @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(startDate);
                            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)) {
                if (task.getViewType() == 1) {
                    reportDailyAccountMapper.loadAccountDailyReport(task.getAccountId(), localPath);
                } else if (task.getViewType() == 2) {
                    reportDailyCampaignMapper.loadCampaignDailyReport(task.getAccountId(), localPath);

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

                } else if (task.getViewType() == 4) {
                    reportDailyCreativeMapper.loadCreativeDailyReport(task.getAccountId(), localPath);
                    reportDailyCreativeMapper.formatCreativeDailyReportData(task.getAccountId(), null);
                }
            }
            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);
    }

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

}
