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.BytedanceReportPlayableRetry;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceInterfaceService;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceReportService;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * Created by JQ.bi on 2020.6.5
 */
@Slf4j
@RestController
@RequestMapping("/ctop/bytedance/report")
public class BytedanceInterfaceController {

    @Autowired
    private IBytedanceReportService bytedanceReportService;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IBytedanceInterfaceService bytedanceInterfaceService;


    /**
     * 头条试玩报表--单个accountId拉取数据
     * @param startDate
     * @param endDate
     * @return
     */
    @GetMapping("/bytedancePlayableReportByAccountId")
    public Result bytedancePlayableReportByAccountId(@RequestParam(name = "startDate") String startDate,
                                                          @RequestParam(name = "endDate") String endDate,
                                                          @RequestParam(name = "accountId") Long accountId) {
        Result result = new Result<>();
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)||accountId==null){
            result.error500("开始时间，结束时间和账户id不能为空");
            return result;
        }
        try {
            log.info("头条获取单个账户视频素材报表数据任务执行开始");
            Long starttime = System.currentTimeMillis();
            CtopOauthToken token = tokenService.getOauthTokenByAccountId(String.valueOf(accountId));
            if (null == token ) {
                log.info("头条获取单个账户视频素材报表数据任务执行失败:未获取到可用的token");
                return result;
            }

            //间隔天数
            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;
                //获取头条素材报表数据
                bytedanceInterfaceService.bytedancePlayableReport(token, start, end);
            }

            Long endtime = System.currentTimeMillis();
            log.info("头条获取视频素材报表数据任务执行结束,执行耗时：{}秒", (endtime - starttime) / 1000);
        } catch (Exception e) {
            log.error("头条获取视频素材报表数据任务执行结失败");
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    //头条试玩报表
    @GetMapping("/bytedancePlayableReport")
    public Result bytedancePlayableReport(@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(8);
            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;
                                        //获取头条试玩报表数据
                                        bytedanceInterfaceService.bytedancePlayableReport(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("/bytedancePlayableReporRetry")
    public Result bytedancePlayableReporRetry() {
        log.info("头条获取试玩报表失败数据任务重试开始");
        Result result = new Result<>();
        try {
            List<BytedanceReportPlayableRetry> retryList = bytedanceInterfaceService.getRetryList();
            final ExecutorService executorService = Executors.newFixedThreadPool(3);
            retryList.forEach(retry -> {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Integer type = retry.getType();
                            String startDate = retry.getStartDate();
                            String endDate = retry.getEndDate();
                            Long accountId = retry.getAccountId();
                            CtopOauthToken token = tokenService.getOauthTokenByAccountId(String.valueOf(accountId));

                            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;
                                //获取头条素材报表数据
                                bytedanceInterfaceService.bytedancePlayableReportRetry(type, token, start, end);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            });
            ////

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

        return result;
    }

}
