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

import cn.com.ctop.common.module.utils.*;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouDailyReportTask;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouDailyReportTaskMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouDailyReportTaskService;
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.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;

    @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)) {
                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);
                    Thread.sleep(1 * 1000);
                    reportDailyCreativeMapper.formatCreativeDailyReportData(task.getAccountId(), task.getStatDate());
                }
            }

            task.setTaskStatus(4);
        } catch (Exception e) {
            e.printStackTrace();
            task.setTaskStatus(5);
        }
        task.setUpdateTime(new Date());
        this.updateById(task);
    }


}
