package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.entity.*;
import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
import cn.com.ctop.common.module.service.*;
import cn.com.ctop.common.module.utils.*;
import cn.com.ctop.common.module.vo.ResFileDTO;
import cn.com.ctop.kuaishou.modules.batch.service.*;
import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouWebInterfaceService;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceAdvertiserDataService;
import cn.com.ctop.toutiao.modules.material.service.IBytedanceEffectVideoInfoService;
import cn.com.ctop.toutiao.modules.report.service.IBytedancePlanDailyReportService;
import cn.com.ctop.toutiao.modules.report.service.IBytedancePlanHourlyReportService;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceReportService;
import cn.com.ctop.toutiao.modules.report.service.IReportService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.quartz.JobExecutionException;
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.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.jeecg.common.util.DateUtils.getAnotherDay;

/**
 * @author jeecg-boot
 */
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {
    @Autowired
    private CtopOauthTokenMapper tokenMapper;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private IMaterialCutFrameService cutFrameService;
    @Autowired
    IKuaiShouVideoGetService videoGetService;
    @Autowired
    private IKuaishouWebInterfaceService kuaishouWebInterfaceService;
    @Autowired
    private CtopOauthTokenMapper oauthTokenMapper;
    @Autowired
    private IKuaiShouHistoryReportTaskService historyReportTaskService;
    @Autowired
    private IMaterialInfoService materialInfoService;
    @Autowired
    private IMaterialParameterService parameterService;
    @Autowired
    private IMaterialAscriptionService ascriptionService;
    @Autowired
    private IMaterialTagService tagService;
    @Autowired
    private IMaterialImageInfoService iMaterialImageInfoService;
    @Autowired
    private IBytedanceReportService bytedanceReportService;
    @Autowired
    private IKuaishouInterfaceService2 kuaishouInterfaceService2;

    static ExecutorService executorService = Executors.newFixedThreadPool(15);
    static ExecutorService videoService = Executors.newFixedThreadPool(5);
    static ExecutorService suzhaoService = Executors.newFixedThreadPool(5);



    @GetMapping(value = "/getCut")
    public void getCut() {
        QueryWrapper<MaterialInfo> materialInfoQueryWrapper = new QueryWrapper<>();
        materialInfoQueryWrapper.like("cover_url", "ctop-media.oss-cn-beijing.aliyuncs.com");
        List<MaterialInfo> list = materialInfoService.list(materialInfoQueryWrapper);
        if (!Check.isNull(list)) {
            for (MaterialInfo materialInfo : list) {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = materialInfo.getCoverUrl();
                            if (!Check.isNull(url)) {
                                InputStream imageStream = LoadFileUtil.getFileStream(url);
                                if (!Check.isNull(imageStream)) {
                                    ResFileDTO jpg = CosUtils.uploadDetailInputStreamV2(imageStream, materialInfo.getCode() + ".jpg", "jpg", 0L, "zeroImage/");
                                    String fileUrl = jpg.getFileUrl();
                                    materialInfo.setCoverUrl(fileUrl);
                                    boolean b = materialInfoService.saveOrUpdate(materialInfo);
                                    if (b) {
                                        log.info("修改成功,videoCode:{}", materialInfo.getCode());
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
        // InputStream in, String fileName, String fileType, long fileSize, String fileSavePath


    }







    @GetMapping(value = "/t")
    public String test() {
        Result<String> result = new Result<>();
        try {
            String requestId = UUID.randomUUID().toString();
            String img = kuaishouWebInterfaceService.qrLogin(requestId);
            if (img != null) {
                result.setSuccess(true);
                result.setResult(img);
            } else {
                result.setSuccess(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }


    @GetMapping(value = "/getSuZhao")
    public void getSuZhao() throws JobExecutionException {
        try {
            //1:查询当日数据
            QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("media_id", 2);
            queryWrapper.orderByDesc("create_time");
            List<CtopOauthToken> tokens = tokenService.list(queryWrapper);
            if (null == tokens || tokens.size() <= 0) {
                log.info("定时获取快手数据异常：未获取到可用的token");
                return;
            }

            tokens.forEach(token -> {
                suzhaoService.submit(new Runnable() {
                    @Override
                    public void run() {
                        //1: 获取广告主信息数据
                        log.info("获取素造素材:accountId:{}", token.getAccountId());
                        kuaishouInterfaceService.getSuZaoList(token.getAccessToken(), token.getAccountId(), 1, null, null);
                    }
                });
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @GetMapping(value = "/getAccountList")
    public void getAccountList(String startDate, String endDate) throws JobExecutionException {
        Thread thread = new Thread() {
            @Override
            public void run() {
                SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date start = sim.parse(startDate);
                    Date end = sim.parse(endDate);
                    //1:查询当日数据
                    List<CtopOauthToken> tokens = tokenService.selectKuaiShouToken();
                    if (null == tokens || tokens.size() <= 0) {
                        log.info("定时获取快手数据异常：未获取到可用的token");
                        return;
                    }

                    executorService = Executors.newFixedThreadPool(3);
                    tokens.forEach(token -> {
                        executorService.submit(new Runnable() {
                            @Override
                            public void run() {
                                //1: 获取广告主信息数据
                                kuaishouInterfaceService.getAdvertiserReportDaily(token, start, end);
                            }
                        });
                    });
                } catch (ParseException e) {
                    e.printStackTrace();
                }


            }
        };
        thread.start();

    }


    @GetMapping(value = "/getVideo")
    public String getVideo(String startDate, String endDate) throws IOException {
        try {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
                    tokenQueryWrapper.eq("media_id", 2);
                    List<CtopOauthToken> list = tokenService.list(tokenQueryWrapper);
                    list.forEach(token -> {
                        videoService.submit(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    kuaishouInterfaceService.getSuZaoList(token.getAccessToken(), token.getAccountId(), 1, null, null);
                                    kuaishouInterfaceService.getVideoList(token, null, null);
                                    Thread.sleep(5000);
                                     /*String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
                                    String videoEndDate = DateUtils.addDay(nowDate, -180);
                                   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                    Date end = simpleDateFormat.parse(nowDate);
                                    Date start = simpleDateFormat.parse(videoEndDate);
                                    List<Date> dates = DateUtils.findDates(start, end);
                                    for (int i = 0; i < dates.size(); i++) {
                                        String formatDate = simpleDateFormat.format(dates.get(i));
                                        kuaishouInterfaceService.getImageList(token, formatDate);
                                        Thread.sleep(500);
                                    }*/

                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                }
                            }
                        });
                    });
                    log.info("快手物料数据同步完成");
                }
            };
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Success";
    }


    @GetMapping(value = "/getVideoByAccountId")
    public String getVideoByAccountId(Long accountId) throws IOException {
        try {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
                    tokenQueryWrapper.eq("media_id", 2);
                    tokenQueryWrapper.eq("account_id", accountId);
                    CtopOauthToken one = tokenService.getOne(tokenQueryWrapper);
                    try {
                        kuaishouInterfaceService.getSuZaoList(one.getAccessToken(), one.getAccountId(), 1, null, null);
                        kuaishouInterfaceService.getVideoList(one, null, null);
                        String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
                        String videoEndDate = DateUtils.addDay(nowDate, -180);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        Date end = simpleDateFormat.parse(nowDate);
                        Date start = simpleDateFormat.parse(videoEndDate);
                        List<Date> dates = DateUtils.findDates(start, end);
                        for (int i = 0; i < dates.size(); i++) {
                            String formatDate = simpleDateFormat.format(dates.get(i));

                            kuaishouInterfaceService.getImageList(one, formatDate);
                            Thread.sleep(100);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                    log.info("快手物料数据同步完成");
                }
            };
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Success";
    }


    @GetMapping(value = "/createCutTask")
    public String createCutTask(String startDate, String endDate) throws IOException {
        List<MaterialInfo> materialInfos = materialInfoService.getListByDate(startDate, endDate);
        if (!Check.isNull(materialInfos)) {
            for (MaterialInfo materialInfo : materialInfos) {
                if (!Check.isNull(materialInfo)) {
                    String code = materialInfo.getCode();
                    QueryWrapper<MaterialParameter> parameterQueryWrapper = new QueryWrapper<>();
                    parameterQueryWrapper.eq("material_id", code);
                    parameterQueryWrapper.last("limit 1");
                    MaterialParameter materialParameter = parameterService.getOne(parameterQueryWrapper);
                    if (!Check.isNull(materialParameter)) {
                        cutFrameService.getCutFrame(materialInfo.getUrl(), code, materialParameter.getSecond(), materialParameter.getHeight(), materialParameter.getWidth());

                    }
                }
            }
        }
        return "Success";
    }


    @GetMapping(value = "/getToken")
    public String getToken(Long accountId, String token, String refreshToken, Integer agentType) {
        oauthTokenService.getKuaiShouRefreshToken(accountId, token, refreshToken, agentType);
        return "Success";
    }


    @GetMapping(value = "/getAccountReport")
    public String getAccountReport(Long accountId, String startDate, String endDate) throws ParseException {
        QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
        oauthTokenQueryWrapper.eq("media_id", 2);
        oauthTokenQueryWrapper.eq("account_id", accountId);
        oauthTokenQueryWrapper.last("limit 1");
        CtopOauthToken token = oauthTokenMapper.selectOne(oauthTokenQueryWrapper);
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sim.parse(startDate);
        Date date2 = sim.parse(endDate);
        kuaishouInterfaceService.getAdvertiserReportDaily(token, date1, date2);
        return "Success";
    }


    @GetMapping(value = "/getAccountReportList")
    public String getAccountReportList(String startDate, String endDate) {
        Result<String> result = new Result<>();
        try {
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = sim.parse(startDate);
            Date date2 = sim.parse(endDate);
            QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
            tokenQueryWrapper.eq("media_id", 2);
            List<CtopOauthToken> ctopOauthTokens = oauthTokenMapper.selectList(tokenQueryWrapper);
            if (!Check.isNull(ctopOauthTokens)) {
                for (CtopOauthToken token : ctopOauthTokens) {
                    kuaishouInterfaceService.getAdvertiserReportDaily(token, date1, date2);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }


    @GetMapping(value = "/updateCode")
    public String updateCode() {
        List<MaterialInfo> list = materialInfoService.list();
        for (MaterialInfo info : list) {
            QueryWrapper<MaterialImageInfo> imageInfoQueryWrapper = new QueryWrapper<>();
            imageInfoQueryWrapper.eq("video_id", String.valueOf(info.getId()));
            MaterialImageInfo updateMaterialImageInfo = new MaterialImageInfo();
            updateMaterialImageInfo.setVideoId(info.getCode());
            iMaterialImageInfoService.update(updateMaterialImageInfo, imageInfoQueryWrapper);
            QueryWrapper<MaterialTag> tagQueryWrapper = new QueryWrapper<>();
            tagQueryWrapper.eq("material_id", String.valueOf(info.getId()));
            MaterialTag updateTag = new MaterialTag();
            updateTag.setMaterialId(info.getCode());
            tagService.update(updateTag, tagQueryWrapper);
            QueryWrapper<MaterialAscription> materialAscriptionQuery = new QueryWrapper<>();
            materialAscriptionQuery.eq("material_id", String.valueOf(info.getId()));
            MaterialAscription updateMaterialAscription = new MaterialAscription();
            updateMaterialAscription.setMaterialId(info.getCode());
            ascriptionService.update(updateMaterialAscription, materialAscriptionQuery);
            QueryWrapper<MaterialParameter> parameterQueryWrapper = new QueryWrapper<>();
            parameterQueryWrapper.eq("material_id", String.valueOf(info.getId()));
            MaterialParameter updateMaterialParameter = new MaterialParameter();
            updateMaterialParameter.setMaterialId(info.getCode());
            parameterService.update(updateMaterialParameter, parameterQueryWrapper);
        }
        List<MaterialImageInfo> list1 = iMaterialImageInfoService.list();
        for (MaterialImageInfo imageInfo : list1) {
            QueryWrapper<MaterialParameter> parameterQueryWrapper = new QueryWrapper<>();
            parameterQueryWrapper.eq("material_id", String.valueOf(imageInfo.getId()));
            MaterialParameter updateMaterialParameter = new MaterialParameter();
            updateMaterialParameter.setMaterialId(imageInfo.getCode());
            parameterService.update(updateMaterialParameter, parameterQueryWrapper);
        }

        List<String> codeList = iMaterialImageInfoService.getCodeList();
        if (!Check.isNull(codeList)) {
            for (int i = 0; i < codeList.size(); i++) {
                String code = codeList.get(i);
                QueryWrapper<MaterialImageInfo> materialImageInfoQueryWrapper = new QueryWrapper<>();
                materialImageInfoQueryWrapper.eq("code", code);
                List<MaterialImageInfo> list2 = iMaterialImageInfoService.list(materialImageInfoQueryWrapper);
                if (list2.size() > 1) {
                    for (int j = 0; j < list2.size(); j++) {
                        if (j == 0) {
                            continue;
                        }
                        MaterialImageInfo materialImageInfo = list2.get(j);
                        iMaterialImageInfoService.removeById(String.valueOf(materialImageInfo.getId()));
                    }
                }
            }
        }
        return "SUCCESS";
    }


    @GetMapping(value = "/createTask")
    public String createTask(Long accountId) {
        Result<String> result = new Result<String>();
        try {
            QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
            oauthTokenQueryWrapper.eq("media_id", 2);
            oauthTokenQueryWrapper.eq("account_id", accountId);
            oauthTokenQueryWrapper.last("limit 1");
            CtopOauthToken token = oauthTokenMapper.selectOne(oauthTokenQueryWrapper);
            String endDateStr = DateUtils.getDate("yyyy-MM-dd");
            String startDate = DateUtils.addMonth(endDateStr, -6);
            historyReportTaskService.createTask(token.getAccountId(), token.getAccessToken(), startDate, endDateStr, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_HISTORY);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }


    @GetMapping(value = "/getHistoryData")
    public String getHistoryData() {
        Result<String> result = new Result<>();
        try {
            String endDateStr = DateUtils.getDate("yyyy-MM-dd");
            String startDate = DateUtils.addMonth(endDateStr, -6);
            QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
            tokenQueryWrapper.eq("media_id", 2);
            List<CtopOauthToken> ctopOauthTokens = oauthTokenMapper.selectList(tokenQueryWrapper);
            if (!Check.isNull(ctopOauthTokens)) {
                for (CtopOauthToken token : ctopOauthTokens) {
                    historyReportTaskService.createTask(token.getAccountId(), token.getAccessToken(), startDate, endDateStr, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_HISTORY);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }


    @GetMapping(value = "/getHistoryDataByAccountId")
    public String getHistoryDataByAccountId(Long accountId) {
        Result<String> result = new Result<>();
        try {
            String endDateStr = DateUtils.getDate("yyyy-MM-dd");
            String startDate = DateUtils.addMonth(endDateStr, -6);
            QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
            tokenQueryWrapper.eq("media_id", 2);
            tokenQueryWrapper.eq("account_id", accountId);
            CtopOauthToken ctopOauthTokens = oauthTokenMapper.selectOne(tokenQueryWrapper);
            if (!Check.isNull(ctopOauthTokens)) {
                historyReportTaskService.createTask(ctopOauthTokens.getAccountId(), ctopOauthTokens.getAccessToken(), startDate, endDateStr, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_HISTORY);

            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }


    @GetMapping(value = "/getTaskList")
    public String getTaskList() {
        Result<String> result = new Result<>();
        try {
            QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
            tokenQueryWrapper.eq("media_id", 2);
            historyReportTaskService.getTaskList();
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }

    @GetMapping(value = "/getGroupData")
    public String getGroupData() {


        Date endDate = new Date();
        QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
        tokenQueryWrapper.eq("media_id", 2);
        List<CtopOauthToken> ctopOauthTokens = tokenMapper.selectList(tokenQueryWrapper);
        for (CtopOauthToken token : ctopOauthTokens) {

            for (int i = 0; i < 7; i++) {
                Date getStartDate = DateUtils.addDay(endDate, -i);
                //3：获取广告组信息数据
                kuaishouInterfaceService.getAdvertiserGroupReportHourly(token, getStartDate, getStartDate);
            }
            for (int i = 0; i < 6; i++) {
                Date getStartDate = new Date();
                Date getEndDate = new Date();
                if (i == 0) {
                    getStartDate = DateUtils.addDay(endDate, -175 + i * 30);
                    getEndDate = DateUtils.addDay(endDate, -150 + i * 30);
                } else {
                    getStartDate = DateUtils.addDay(endDate, -180 + i * 30);
                    getEndDate = DateUtils.addDay(endDate, -150 + i * 30);
                }
                //3：获取广告组信息数据
                kuaishouInterfaceService.getAdvertiserGroupReportDaily(token, getStartDate, getEndDate);
            }
        }
        return "Success";
    }


    @GetMapping(value = "/gerCreative")
    public void gerCreative() {
        QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
        oauthTokenQueryWrapper.eq("media_id", 2);
        List<CtopOauthToken> ctopOauthTokens = oauthTokenMapper.selectList(oauthTokenQueryWrapper);
        for (CtopOauthToken token : ctopOauthTokens) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        kuaishouInterfaceService.getCreativeList(token, null, null);
                        //  kuaishouInterfaceService.getVideoList2(token, null, null,1);
                        //3: 获取图片信息数据
                        // kuaishouInterfaceService.getImageList2(token, null, null,1);
                        Thread.sleep(1 * 200);
                        //  kuaishouInterfaceService.getAppList(token.getAccountId(), token.getAccessToken());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    @GetMapping("checkFile")
    public Map<String, Object> checkFile() {
        String nowDate = DateUtils.getDate("yyyy-MM-dd");
        String statDate = getAnotherDay("yyyy-MM-dd", nowDate, -1);
        //  查询快手token
        List<CtopOauthToken> tokens = tokenService.getTokenListByType(CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
        if (null == tokens || tokens.size() <= 0) {
            log.info("定时获取快手数据异常：未获取到可用的token");
        }
        for (CtopOauthToken token : tokens) {
            dailyReportTaskService.getTaskList(token.getAccountId(), token.getAccessToken(), statDate);
        }
        Map<String, Object> result = new HashMap<>();
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @Autowired
    private IKuaiShouDailyReportTaskService dailyReportTaskService;


    @Autowired
    private IKuaiShouCampaignService campaignService;


    @GetMapping("loadBytedanceHistoryData")
    public Map<String, Object> loadBytedanceHistoryData() {
        Map<String, Object> result = new HashMap<>();
        //1:查询所有头条的token数据
        List<CtopOauthToken> tokens = tokenService.getTokenListByType(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE);
        if (null != tokens && tokens.size() > 0) {
            tokens.forEach(token -> {
                //拉取往期数据
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        reportService.loadBytedanceHistoryData(token);
                    }
                });
            });
        }
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }


    @Autowired
    private IUserAllocationService userAllocationService;

    @GetMapping(value = "/getPlanAndGroupByAccount")
    public void getPlanAndGroupByAccount(Long accountId) {
        QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
        oauthTokenQueryWrapper.eq("media_id", 2);
        oauthTokenQueryWrapper.eq("account_id", accountId);
        oauthTokenQueryWrapper.last("limit 1");
        CtopOauthToken token = oauthTokenMapper.selectOne(oauthTokenQueryWrapper);
        try {
            kuaishouInterfaceService.getCampaignList(token, null, null);
            //1：获取全量广告组数据
            kuaishouInterfaceService.getGroupList(token, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping(value = "/getCreativeByAccount")
    public void gerCreative(Long accountId) {
        QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
        oauthTokenQueryWrapper.eq("media_id", 2);
        oauthTokenQueryWrapper.eq("account_id", accountId);
        oauthTokenQueryWrapper.last("limit 1");
        CtopOauthToken token = oauthTokenMapper.selectOne(oauthTokenQueryWrapper);

        try {
            kuaishouInterfaceService.getCreativeList(token, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @Autowired
    private IBytedancePlanDailyReportService planDailyReportService;
    @Autowired
    private ICtopOauthTokenService tokenService;


    @Autowired
    private IByteDanceAdvertiserDataService advertiserDataService;

    @GetMapping("getBytedanceData")
    public Map<String, Object> getBytedanceData() {
        Map<String, Object> result = new HashMap<>();
        //1:查询当日数据
        List<CtopOauthToken> tokens = tokenService.getTokenListByType(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE);
        if (null == tokens || tokens.isEmpty()) {
            log.info("定时获取头条数据异常：为获取到可用的token");
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        tokens.forEach(token -> {
            advertiserDataService.getMaterialList(token);
        });
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @Autowired
    private IReportService reportService;


    @Autowired
    private IBytedancePlanHourlyReportService planHourlyReportService;


    @GetMapping(value = "/AccountReportByAccount")
    public void AccountReportByAccount(Long accountId, String startDateStr, String endDateStr) {
        QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
        oauthTokenQueryWrapper.eq("media_id", 2);
        oauthTokenQueryWrapper.eq("account_id", accountId);
        oauthTokenQueryWrapper.last("limit 1");
        CtopOauthToken token = oauthTokenMapper.selectOne(oauthTokenQueryWrapper);
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date startDate = null;
                    Date endDate = null;
                    try {
                        startDate = simpleDateFormat.parse(startDateStr);
                        endDate = simpleDateFormat.parse(endDateStr);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    kuaishouInterfaceService.getAdvertiserReportDaily(token, startDate, endDate);

                    Thread.sleep(1 * 200);
                    //  kuaishouInterfaceService.getAppList(token.getAccountId(), token.getAccessToken());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @GetMapping(value = "/getAllCreativeList")
    public void getAllCreativeList() {

        try {


            QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
            oauthTokenQueryWrapper.eq("media_id", 2);
            List<CtopOauthToken> ctopOauthTokens = oauthTokenMapper.selectList(oauthTokenQueryWrapper);

            if (!Check.isNull(ctopOauthTokens)) {
                for (CtopOauthToken token : ctopOauthTokens) {
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            if (!Check.isNull(token)) {
                                log.info("获取创意，账号id:{}", token.getAccountId());
                                kuaishouInterfaceService.getCreativeList(token, null, null);
                            }
                        }
                    });

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

    }


    @GetMapping(value = "/getAllGroupList")
    public void getAllGroupList() {

        try {

            QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
            oauthTokenQueryWrapper.eq("media_id", 2);
            List<CtopOauthToken> ctopOauthTokens = oauthTokenMapper.selectList(oauthTokenQueryWrapper);
            if (!Check.isNull(ctopOauthTokens)) {
                for (CtopOauthToken token : ctopOauthTokens) {
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            if (!Check.isNull(token)) {
                                log.info("获取组，账号id:{}", token.getAccountId());
                                kuaishouInterfaceService.getGroupList(token, null, null);
                            }
                        }
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @GetMapping(value = "/KuaishouDailyAccountReportLoadJob")
    public void KuaishouDailyAccountReportLoadJob() {
        Date getDate = DateUtils.addDay(new Date(), -2);
        //1:查询当日数据
        List<CtopOauthToken> tokens = tokenService.selectKuaiShouToken();
        if (null == tokens || tokens.size() <= 0) {
            log.info("定时获取快手数据异常：未获取到可用的token");
            return;
        }

        executorService = Executors.newFixedThreadPool(3);
        tokens.forEach(token -> {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    //1: 获取广告主信息数据
                    kuaishouInterfaceService.getAdvertiserReportDaily(token, getDate, getDate);
                }
            });
        });
    }


    @GetMapping(value = "/BytedanceDailyAsyncJob")
    public void BytedanceDailyAsyncJob() throws ParseException {
        String startDate = "2020-06-01";
        Date getDate = DateUtils.addDay(new Date(), -1);
        String endDate = DateUtils.formatDate(getDate);
        endDate = "2020-06-02";
        log.info("头条广告计划异步任务开始执行，跑的是" + startDate + "~" + endDate + "的数据");

        List<CtopOauthToken> tokens = tokenService.getToutiaoTokenByCreateTime(endDate);
        if (null == tokens || tokens.size() <= 0) {
            log.info("头条获取异步报表数据任务执行失败:未获取到可用的token");
            return;
        }

        //1.创意 2.广告主 3.广告组 4.广告计划
        for (CtopOauthToken token : tokens) {
            bytedanceReportService.bytedanceAsyncTaskCreate(startDate, endDate, token, 1);
            bytedanceReportService.bytedanceAsyncTaskCreate(startDate, endDate, token, 2);
            bytedanceReportService.bytedanceAsyncTaskCreate(startDate, endDate, token, 3);
            bytedanceReportService.bytedanceAsyncTaskCreate(startDate, endDate, token, 4);
        }
    }

    @Autowired
    private IBytedanceEffectVideoInfoService effectVideoInfoService;

    @GetMapping("/bytedance/effectVideo/get")
    public Map<String, Object> effectVideoGet(String date) {
        Map<String, Object> result = new HashMap<>();
        effectVideoInfoService.loadEffectVideo(date);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }



    @GetMapping(value = "/getAppList")
    public void getAppList() throws JobExecutionException {
        try {
            //1:查询当日数据
            QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("media_id", 2);
            queryWrapper.orderByDesc("create_time");
            List<CtopOauthToken> tokens = tokenService.list(queryWrapper);
            if (null == tokens || tokens.size() <= 0) {
                log.info("定时获取快手数据异常：未获取到可用的token");
                return;
            }

            tokens.forEach(token -> {

                kuaishouInterfaceService.getAppList(token.getAccountId(),token.getAccessToken());
                //suzhaoService.submit(new Runnable() {
                //    @Override
                //    public void run() {
                //        //1: 获取广告主信息数据
                //        log.info("获取素造素材:accountId:{}", token.getAccountId());
                //        kuaishouInterfaceService.getSuZaoList(token.getAccessToken(), token.getAccountId(), 1, null, null);
                //    }
                //});
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }




    @GetMapping(value = "/getOperationRecord")
    public Result getOperationRecord(@Param("accountId")Long accountId, @Param("operationTarget")Integer operationTarget, @Param("startDate")String startDate, @Param("endDate")String endDate){
        Result result = new Result();
        try {
            if(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
                result.setSuccess(false);
                result.setMessage("时间参数不能为空");
                return result;
            }

            if(operationTarget == null){
                result.setSuccess(false);
                result.setMessage("类型不能为空");
                return result;
            }

            if(accountId == null){
                //1:查询当日数据
                QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("media_id", 2);
                queryWrapper.orderByDesc("create_time");
                List<CtopOauthToken> tokens = tokenService.list(queryWrapper);
                if (null == tokens || tokens.size() <= 0) {
                    log.error("定时获取快手操作记录数据异常：未获取到可用的token");
                    result.setSuccess(false);
                    result.setMessage("定时获取快手操作记录数据异常：未获取到可用的toke");
                    return result;
                }

                executorService = Executors.newFixedThreadPool(3);
                tokens.forEach(token -> {
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            log.info("获取操作记录开始:accountId:{},startDate:{},endDate:{}", token.getAccountId(), startDate, endDate);
                            kuaishouInterfaceService2.getOperationRecord(token.getAccountId(), token.getAccessToken(), operationTarget, startDate, endDate);
                            log.info("获取操作记录开始:accountId:{}", token.getAccountId());
                     }
                    });
                });
            }else{
                QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("account_id", accountId);
                CtopOauthToken token = tokenService.getOauthTokenByAccountId(String.valueOf(accountId));
                if (null == token) {
                    log.error("定时获取快手操作记录数据异常：未获取到可用的token");
                    result.setSuccess(false);
                    result.setMessage("定时获取快手操作记录数据异常：未获取到可用的toke");
                    return result;
                }
                kuaishouInterfaceService2.getOperationRecord(token.getAccountId(), token.getAccessToken(), operationTarget, startDate, endDate);

            }


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

        return result;
    }


}
