package cn.com.ctop.toutiao.modules.report.controller;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.toutiao.modules.report.entity.BytedanceReportMaterialRetry;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceReportService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@RestController
@RequestMapping("/ctop/report")
public class BytedanceReportController {
    @Autowired
    private IBytedanceReportService bytedanceReportService;
    @Autowired
    private ICtopOauthTokenService tokenService;

    @PostMapping("/kuaiShou/accountReport")
    public Result<JSONObject> getKuaiShouAccountReport(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            JSONObject json = bytedanceReportService.getKuaiShouAccountReport(requestJson);
            result.setResult(json);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }

        return result;

    }


    @PostMapping("/kuaiShou/accountDetailReport")
    public Result<List<JSONObject>> getKuaiShouAccountDetailReport(@RequestBody JSONObject requestJson) {

        Result<List<JSONObject>> result = new Result<>();
        try {
            List<JSONObject> kuaiShouAccounDetailtReport = bytedanceReportService.getKuaiShouAccounDetailtReport(requestJson);
            result.setResult(kuaiShouAccounDetailtReport);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }

        return result;

    }


    @PostMapping("/kuaiShou/getReportList")
    public Result<List<JSONObject>> getReportList(@RequestBody JSONObject requestJson) {

        Result<List<JSONObject>> result = new Result<>();
        try {
            List<JSONObject> kuaiShouAccounDetailtReport = bytedanceReportService.getReportList(requestJson);
            result.setResult(kuaiShouAccounDetailtReport);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);

        }
        return result;

    }

    @PostMapping("/bytedance/async")
    public Result<List<JSONObject>> asyncTaskCreate(@RequestParam(name = "startDate")String startDate,
                                                    @RequestParam(name = "endDate")String endDate,
                                                    @RequestParam(name = "type")Integer type) {

        Result<List<JSONObject>> result = new Result<>();
        try {
            log.info("头条获取异步报表数据任务执行开始");
            Long starttime = System.currentTimeMillis();
            List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
            if (null == tokens || tokens.size() <= 0) {
                log.info("头条获取异步报表数据任务执行失败:未获取到可用的token");
                return result;
            }

            for (CtopOauthToken token : tokens) {
                bytedanceReportService.bytedanceAsyncTaskCreate(startDate, endDate, token, type);
            }
            Long endtime = System.currentTimeMillis();
            log.info("头条异步报表数据任务执行结束,执行耗时：{}秒", (endtime - starttime) / 1000);
        } catch (Exception e) {
            log.error("头条获取异步报表数据任务执行报错");
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    @PostMapping("/bytedance/async/taskGet")
    public Result<List<JSONObject>> bytedanceAsyncTaskGet(@RequestBody JSONObject requestJson) {
        Result<List<JSONObject>> result = new Result<>();
        try {
            log.info("头条下载异步报表数据定时任务执行开始");
            Long starttime = System.currentTimeMillis();
            bytedanceReportService.bytedanceAsyncTaskGet();
            Long endtime = System.currentTimeMillis();
            log.info("头条下载异步报表数据定时任务执行结束,执行耗时：{}秒", (endtime - starttime) / 1000);
        } catch (Exception e) {
            log.error("头条下载异步报表数据定时任务执行报错");
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    @GetMapping("/bytedance/bytedanceMaterialReport")
    public Result bytedanceMaterialReport(@RequestParam(name = "startDate") String startDate,
                                          @RequestParam(name = "endDate") String endDate) {
        Result result = new Result<>();
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
            result.error500("开始时间和结束时间不能为空");
            return result;
        }

        try {
            log.info("头条获取素材报表数据任务执行开始");
            Long starttime = System.currentTimeMillis();
            List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
            if (null == tokens || tokens.size() <= 0) {
                log.info("头条获取素材报表数据任务执行失败:未获取到可用的token");
                return result;
            }

            final ExecutorService executorService = Executors.newFixedThreadPool(3);
            tokens.forEach(token -> {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Long days = DateUtils.getDiscrepantDays(startDate, endDate); //间隔天数
                            String start = null;
                            String end = null;
                            for (int i = 0; i <= days; i++) {
                                start = DateUtils.addDay(startDate, i);
                                end = start;
                                //获取头条素材报表数据
                                bytedanceReportService.bytedanceMaterialReport(token, start, end);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                        }
                    }
                });
            });
            ////
            Long endtime = System.currentTimeMillis();
            log.info("头条获取素材报表数据任务执行结束,执行耗时：{}秒", (endtime - starttime) / 1000);
        } catch (Exception e) {
            log.error("头条获取素材报表数据任务执行结失败");
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    @GetMapping("/bytedance/bytedanceMaterialReporRetry")
    public Result bytedanceMaterialReportRetry() {
        log.info("头条获取素材报表失败数据任务重试开始");
        Result result = new Result<>();
        try {
            List<BytedanceReportMaterialRetry> retryList = bytedanceReportService.getRetryList();
            final ExecutorService executorService = Executors.newFixedThreadPool(3);
            retryList.forEach(retry -> {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            CtopOauthToken token = tokenService.getOauthTokenByAccountId(String.valueOf(retry.getAccountId()));
                            log.info("头条素材报表当前accountId为：" + token.getAccountId());
                            bytedanceReportService.bytedanceMaterialReportRetry(token, retry.getStartDate(), retry.getEndDate());
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                        }
                    }
                });
            });
            ////

        } catch (Exception e) {
            log.error("条获取素材报表失败数据任务重试失败");
            e.printStackTrace();
            result.setSuccess(false);
        }

        log.info("头条获取素材报表数据任务重试结束");
        return result;
    }















}
