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.mapper.UserAllocationMapper;
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.crawler.modules.core.entity.CrawlerDouyinMusicTask;
import cn.com.ctop.crawler.modules.core.service.CrawlerDouyinMusicTaskService;
import cn.com.ctop.crawler.modules.douyin.service.DouyinMusicService;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouTemplate;
import cn.com.ctop.kuaishou.modules.batch.service.*;
import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouWebInterfaceService;
import cn.com.ctop.kuaishou.modules.material.entity.KuaishouAccessToken;
import cn.com.ctop.kuaishou.modules.material.entity.KuaishouResultToken;
import cn.com.ctop.kuaishou.modules.report.service.IKuaiShouDailyAgentService;
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.mapper.BytedanceReportMaterialDailyMapper;
import cn.com.ctop.toutiao.modules.report.service.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
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 IKuaiShouHistoryReportTaskService historyReportTaskService;
    @Autowired
    private IMaterialInfoService materialInfoService;
    @Autowired
    private IMaterialParameterService parameterService;
    @Autowired
    private IMaterialAscriptionService ascriptionService;
    @Autowired
    private IMaterialTagService tagService;
    @Autowired
    private IMaterialImageInfoService iMaterialImageInfoService;
    @Autowired
    private IKuaishouInterfaceService2 kuaishouInterfaceService2;
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private DouyinMusicService douyinMusicService;
    @Autowired
    private CrawlerDouyinMusicTaskService crawlerDouyinMusicTaskService;
    @Autowired
    private MusicInfoService musicInfoService;
    @Autowired
    private IKuaiShouHistoryReportTaskService kuaiShouHistoryReportTaskService;

    static ExecutorService executorService = Executors.newFixedThreadPool(15);
    static ExecutorService videoService = Executors.newFixedThreadPool(5);
    static ExecutorService suzhaoService = Executors.newFixedThreadPool(5);
    @Autowired
    private IKuaiShouDailyAgentService dailyAgentService;
    @Autowired
    private IKuaishouTemplateService templateService;
    @Autowired
    private IBytedanceAccountReportTaskRecordService reportTaskRecordService;
    @Resource
    private BytedanceReportMaterialDailyMapper bytedanceReportMaterialDailyMapper;
    @Autowired
    private ICtopOauthTokenService ctopOauthTokenService;

    @Autowired
    private IBindAccountAuthService bindAccountAuthService;
    @Autowired
    private UserAllocationMapper allocationMapper;
    @Autowired
    private IBytedanceReportService bytedanceReportService;

    @Autowired
    private IUserAllocationService allocationService;


    @GetMapping("/getVideoByProjectId")
    public String getVideoByProjectId(Long projectId) {
        QueryWrapper<UserAllocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId);
        List<UserAllocation> list = allocationService.list(queryWrapper);
        for (UserAllocation allocation : list) {
            CtopOauthToken token = tokenService.getTokenByAccountId(allocation.getAccountId());
            kuaishouInterfaceService.getVideoList(token, null, null);
        }
        return "success";
    }


    @GetMapping("/testKuaishou")
    public String kuaishouCallback(@RequestParam("auth_code") String authCode, @RequestParam("state") String state) {
        try {
            JSONObject json = JSONObject.parseObject(state);
            if (Check.isNull(json)) {
                throw new Exception("回调信息为空");
            }
            log.info("快手授权返回信息：{}", json);
            log.info("快手授权返回oauthCode：{}", authCode);
            Integer agentType = json.getInteger("agentType");
            Long appId = json.getLong("appId");
            if (org.apache.commons.lang.StringUtils.isNotBlank(authCode)) {
                KuaishouResultToken accessToken = kuaishouInterfaceService.getAccessToken(authCode, appId);
                if (accessToken.getCode() != 0) {
                    throw new Exception("快手回调token返回错误");
                }
                KuaishouAccessToken token = accessToken.getData();
                if (token != null) {
                    Long accountId = token.getAccountId();
                    if (Check.isNull(accountId)) {
                        return "授权绑定失败！";
                    }
                    Map<String, Object> advertiseBaseInfoMap = kuaishouInterfaceService.advertiserInfo(accountId, token.getAccessToken());
                    if ((Integer) advertiseBaseInfoMap.get("code") != 0) {
                        return "授权绑定失败，失败原因:" + advertiseBaseInfoMap.get("message");
                    }
                    String advertiserId = json.getString("advertiserId");
                    //指定分配人姓名
                    String userName = json.getString("userName");
                    // 媒体类型： 1 头条 2 快手
                    String mediaId = json.getString("mediaId");
                    //创建人
                    String userId = json.getString("userId");
                    Long projectId = json.getLong("projectId");
                    BigDecimal warningProportion = json.getBigDecimal("WarningProportion");
                    BigDecimal warningAmount = json.getBigDecimal("WarningAmount");
                    String systemType = json.getString("systemType");
                    CtopOauthToken topOauthToken = new CtopOauthToken();
                    topOauthToken.setId(String.valueOf(accountId));
                    topOauthToken.setAppId(json.getLong("appId"));
                    topOauthToken.setAccountId(accountId);
                    topOauthToken.setMediaId("2");
                    topOauthToken.setAdvertiserId(advertiserId);
                    topOauthToken.setAgentType(agentType);
                    topOauthToken.setAccessToken(token.getAccessToken());
                    long accessTokenExpireIn = token.getAccessTokenExpiresIn() * 1000L;
                    long now = System.currentTimeMillis();
                    Date accessTokenExpireInDate = new Date(now + accessTokenExpireIn);
                    topOauthToken.setAccessTokenExpiresIn(accessTokenExpireInDate);
                    topOauthToken.setRefreshToken(token.getRefreshToken());
                    long refreshTokenExpireIn = token.getRefreshTokenExpiresIn() * 1000L;
                    Date refreshTokenExpireInDate = new Date(now + refreshTokenExpireIn);
                    topOauthToken.setRefreshTokenExpiresIn(refreshTokenExpireInDate);
                    topOauthToken.setUpdateTime(new Date());
                    ctopOauthTokenService.saveOrUpdate(topOauthToken);
                    QueryWrapper<UserAllocation> userAllocationQueryWrapper = new QueryWrapper<>();
                    userAllocationQueryWrapper.eq("account_id", accountId);
                    userAllocationQueryWrapper.eq("media_id", 2);
                    userAllocationQueryWrapper.orderByDesc("create_time");
                    userAllocationQueryWrapper.last("limit 1");
                    UserAllocation checkUserAllocation = allocationMapper.selectOne(userAllocationQueryWrapper);
                    if (!Check.isNull(checkUserAllocation)) {
                        return "授权失败，该账号已被：" + checkUserAllocation.getUserName() + " 绑定！";
                    }
                    UserAllocation userAllocation = new UserAllocation();
                    userAllocation.setUserName(userName);
                    userAllocation.setUserId(userId);
                    userAllocation.setAdvertiserId(advertiserId);
                    userAllocation.setSystemType(systemType);
                    // 获取快手昵称
                    userAllocation.setAuthName((String) advertiseBaseInfoMap.get("userName"));
                    userAllocation.setMediaId(mediaId);
                    userAllocation.setAccountId(accountId);
                    userAllocation.setProjectId(projectId);
                    userAllocation.setWarningProportion(warningProportion);
                    userAllocation.setWarningAmount(warningAmount);
                    userAllocation.setCreateTime(new Date());
                    userAllocation.setUpdateTime(new Date());
                    allocationMapper.deleteById(userAllocation.getId());
                    Map<String, Object> deleteUserMap = new HashMap<>();
                    deleteUserMap.put("advertiser_id", advertiserId);
                    deleteUserMap.put("account_id", accountId);
                    allocationMapper.deleteByMap(deleteUserMap);
                    int i = allocationMapper.insert(userAllocation);
                    if (i > 0) {
                        log.info("同步分配用户表完成,task_id:{},accountId:{}", state, accountId);
                    }
                    //账号绑定
                    bindAccountAuthService.addBindAccount(accountId, KuaishouInterfaceConstant.LOGIN_TYPE_KUAISHOU, advertiserId);
                    Thread t = new Thread() {
                        @Override
                        public void run() {
                            try {
                                kuaishouInterfaceService.loadKuaishouDataSingle(topOauthToken);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    t.start();
                }
                return "授权绑定成功";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "授权绑定失败！";
    }


    @GetMapping("/getBytedanceMatReport")
    public Map<String, Object> getData() {
        List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
        executorService = Executors.newFixedThreadPool(10);
        CountDownLatch countDownLatch = new CountDownLatch(tokens.size());
        tokens.forEach(record -> executorService.submit(() -> {
            try {
                reportService.getAdvertiserReport(record, DateUtils.parseDate("2021-01-01", "yyyy-MM-dd"), DateUtils.parseDate("2021-01-31", "yyyy-MM-dd"), CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
                log.info("账户数据获取完成：account:{},时间:{}-{}", record.getAccountId(), "2021-01-01", "2020-01-31");
            } catch (Exception e) {

            } finally {
                countDownLatch.countDown();
            }
        }));
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据获取完成");
//        bytedanceReportMaterialDailyMapper.updateImageReportCode();
//        bytedanceReportMaterialDailyMapper.updateImageReportProjectId();
//        bytedanceReportMaterialDailyMapper.updateImageReportProjectName();
//        bytedanceReportMaterialDailyMapper.updateImageReportPlaneId();
//        bytedanceReportMaterialDailyMapper.updateImageReportPlaneName();
        Map<String, Object> result = new HashMap<>();
        ResultMapUtils.setResultMap(new HashMap<>(), StatusCode.COMMON_SUCCESS);
        return result;
    }


    @GetMapping(value = "/updateTemplate")
    public void updateTemplate(Long projectId, String startDate, String endDate) {

        List<Long> list = new ArrayList();
        list.add(7022550L);
        list.add(7409586L);
        list.add(5473041L);
        list.add(5852766L);
        list.add(6962896L);
        list.add(7409919L);
        for (int i = 0; i < list.size(); i++) {
            Long accountId = list.get(i);
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            templateService.getTemplateByAccountId(oauthToken.getAccountId(), oauthToken.getAccessToken(), 1);

            QueryWrapper<KuaishouTemplate> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account_id", accountId);
            List<KuaishouTemplate> list1 = templateService.list(queryWrapper);
            if (!Check.isNull(list1)) {
                for (KuaishouTemplate template : list1) {
                    JSONObject param = new JSONObject();
                    param.put("templateId", template.getTemplateId());
                    param.put("accountId", template.getAccountId());
                    param.put("templateName", template.getTemplateName());
                    param.put("filterConvertedLevel", 5);
                    templateService.updateTemplate(oauthToken.getAccountId(), oauthToken.getAccessToken(), param);

                }

            }


        }


    }


    @GetMapping(value = "/getCreativeByProjectId")
    public void gerCreative(Long projectId, String startDate, String endDate) {

        Result<String> result = new Result<>();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date start = simpleDateFormat.parse(startDate);
            Date end = simpleDateFormat.parse(endDate);
            QueryWrapper<UserAllocation> userAllocationQueryWrapper = new QueryWrapper<>();
            userAllocationQueryWrapper.eq("project_id", projectId);
            List<UserAllocation> list = userAllocationService.list(userAllocationQueryWrapper);
            if (!Check.isNull(list)) {
                for (UserAllocation allocation : list) {
                    Long accountId = allocation.getAccountId();
                    QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
                    tokenQueryWrapper.eq("media_id", 2);
                    tokenQueryWrapper.eq("account_id", accountId);
                    CtopOauthToken token = tokenMapper.selectOne(tokenQueryWrapper);
                    if (!Check.isNull(token)) {
                        suzhaoService.submit(new Runnable() {
                            @Override
                            public void run() {
                                JSONArray arr = new JSONArray();
                                kuaishouInterfaceService.getAdvertiserCreativeReportDaily(token, start, end, arr, arr);

                            }
                        });


                    }
                }

            }


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


    }


    @GetMapping(value = "/agentReport")
    public void agentReport(String startDate, String endDate) {
        dailyAgentService.getAgentReportByPage(startDate, endDate);
    }


    @GetMapping(value = "/dailyReport")
    public void dailyReport() {
        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(), "2020-09-20");
        }
    }

    @GetMapping("getKuaishouPlanHourlyReport")
    public Map<String, Object> getKuaishouPlanHourlyReport(String params) {
        Long start = System.currentTimeMillis();
        Map<String, Object> result = new HashMap<>();
        if (null == params || params.trim().equals("")) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            result.put("message", "COMMON_PARAM_ERROR");
            return result;
        }
        Long accountId = Long.parseLong(params);
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        if (null == token) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            result.put("message", "TOKEN_IS_NULL");
            return result;
        }
        Date getDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH");
        String hour = simpleDateFormat.format(getDate);
        if ("00".equals(hour)) {
            getDate = DateUtils.addDay(getDate, -1);
        }
        //1:查询当日数据
        Date finalGetDate = getDate;
        try {
            kuaishouInterfaceService.getAdvertiserCampaignReportHourly(token, finalGetDate, finalGetDate);
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
            result.put("message", "SUCCESS");
            long end = System.currentTimeMillis();
            log.info("执行时长:{}毫秒", end - start);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_SERVER_ERROR);
            result.put("message", "COMMON_SERVER_ERROR");
            return result;
        }
    }


    @GetMapping(value = "/getMd5")
    public void getMd5() {
        kuaiShouHistoryReportTaskService.getMd5(null, null);

    }

    @GetMapping(value = "/getGroupReport")
    public void getGroupReport() throws ParseException {
        List<CtopOauthToken> tokens = oauthTokenService.selectKuaiShouToken();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse1 = simpleDateFormat.parse("2020-09-12");
        Date parse2 = simpleDateFormat.parse("2020-09-17");
        for (CtopOauthToken token : tokens) {

            suzhaoService.submit(new Runnable() {
                @Override
                public void run() {
                    //1: 获取广告主信息数据
                    kuaishouInterfaceService.getAdvertiserGroupReportDaily(token, parse1, parse2);
                }
            });


        }
    }


    @GetMapping(value = "/syncDouyinMusicAsc")
    public String syncDouyinMusicAsc() {
        QueryWrapper<CrawlerDouyinMusicTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "init").orderByAsc("id").last(" limit 20");

        List<CrawlerDouyinMusicTask> list = crawlerDouyinMusicTaskService.list(queryWrapper);

        while (list != null && list.size() > 0) {
            for (CrawlerDouyinMusicTask crawlerDouyinMusicTask : list) {
                MusicInfo musicInfo = new MusicInfo();
                musicInfo.setExtId(crawlerDouyinMusicTask.getId());
                musicInfo = douyinMusicService.getMusicInfo(musicInfo);
                musicInfoService.save(musicInfo);
                crawlerDouyinMusicTask.setStatus("done");
                crawlerDouyinMusicTaskService.updateById(crawlerDouyinMusicTask);
            }
            list = crawlerDouyinMusicTaskService.list(queryWrapper);
        }
        return "success";
    }

    @GetMapping(value = "/syncDouyinMusic")
    public String syncDouyinMusic() {
        for (int i = 0; i < 10; i++) {
            final int j = i;
            Thread thread = new Thread() {
                @Override
                public void run() {
                    QueryWrapper<CrawlerDouyinMusicTask> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("status", "init").likeLeft("id", j).orderByDesc("id").last(" limit 20");
                    List<CrawlerDouyinMusicTask> list = crawlerDouyinMusicTaskService.list(queryWrapper);
                    while (list != null && list.size() > 0) {
                        log.info("【同步歌曲】第" + j + "线程正在处理：" + list.size() + "条数据");
                        for (CrawlerDouyinMusicTask crawlerDouyinMusicTask : list) {
                            MusicInfo musicInfo = new MusicInfo();
                            musicInfo.setExtId(crawlerDouyinMusicTask.getId());
                            douyinMusicService.getMusicInfo(musicInfo);
                        }
                        list = crawlerDouyinMusicTaskService.list(queryWrapper);
                    }
                }
            };
            thread.start();
        }

        return "success";
    }

    @GetMapping(value = "/parseDouyinMusic")
    public String parseDouyinMusic() {
        for (int i = 0; i < 10; i++) {
            final int j = i;
            Thread thread = new Thread() {
                @Override
                public void run() {
                    QueryWrapper<CrawlerDouyinMusicTask> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("status", "done").likeLeft("id", j).orderByDesc("id").last(" limit 20");
                    List<CrawlerDouyinMusicTask> list = crawlerDouyinMusicTaskService.list(queryWrapper);
                    while (list != null && list.size() > 0) {
                        log.info("【解析分类】第" + j + "线程正在处理：" + list.size() + "条数据");
                        for (CrawlerDouyinMusicTask crawlerDouyinMusicTask : list) {
                            QueryWrapper<MusicInfo> queryWrapper1 = new QueryWrapper<>();
                            queryWrapper1.eq("ext_id", crawlerDouyinMusicTask.getId()).last(" limit 1");
                            MusicInfo musicInfo = musicInfoService.getOne(queryWrapper1);
                            if (musicInfo != null) {
                                douyinMusicService.parseTag(musicInfo);
                            }
                        }
                        list = crawlerDouyinMusicTaskService.list(queryWrapper);
                    }
                }
            };
            thread.start();
        }

        return "success";
    }

    @GetMapping(value = "/testdouyinmusic")
    public String testDouyinMusic() {
        douyinMusicService.getHotMusicList();
        return "success";
    }

    @GetMapping(value = "/getDailyDataByProjectId")
    public String getDailyDataByProjectId(Long projectId, String startDate, String endDate) {
        Result<String> result = new Result<>();
        try {

            QueryWrapper<UserAllocation> userAllocationQueryWrapper = new QueryWrapper<>();
            userAllocationQueryWrapper.eq("project_id", projectId);
            // userAllocationQueryWrapper.eq("account_status", 0);
            List<UserAllocation> list = userAllocationService.list(userAllocationQueryWrapper);
            if (!Check.isNull(list)) {
                for (UserAllocation allocation : list) {
                    Long accountId = allocation.getAccountId();
                    QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
                    tokenQueryWrapper.eq("media_id", 2);
                    tokenQueryWrapper.eq("account_id", accountId);
                    CtopOauthToken ctopOauthTokens = tokenMapper.selectOne(tokenQueryWrapper);
                    if (!Check.isNull(ctopOauthTokens)) {
                        historyReportTaskService.createTask(ctopOauthTokens.getAccountId(), ctopOauthTokens.getAccessToken(), startDate, endDate, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_DAILY);

                    }
                }

            }


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


    @GetMapping(value = "/getHistoryDataByProjectId")
    public String getHistoryDataByProjectId(Long projectId, String startDate, String endDate) {
        Result<String> result = new Result<>();
        try {

            QueryWrapper<UserAllocation> userAllocationQueryWrapper = new QueryWrapper<>();
            userAllocationQueryWrapper.eq("project_id", projectId);
            // userAllocationQueryWrapper.eq("account_status", 0);
            List<UserAllocation> list = userAllocationService.list(userAllocationQueryWrapper);
            if (!Check.isNull(list)) {
                for (UserAllocation allocation : list) {
                    Long accountId = allocation.getAccountId();
                    QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
                    tokenQueryWrapper.eq("media_id", 2);
                    tokenQueryWrapper.eq("account_id", accountId);
                    CtopOauthToken ctopOauthTokens = tokenMapper.selectOne(tokenQueryWrapper);
                    if (!Check.isNull(ctopOauthTokens)) {
                        historyReportTaskService.createTask(ctopOauthTokens.getAccountId(), ctopOauthTokens.getAccessToken(), startDate, endDate, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_HISTORY);

                    }
                }

            }


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


    @GetMapping(value = "/getDailyDataByAccountId")
    public String getDailyDataByAccountId(Long accountId) {
        Result<String> result = new Result<>();
        try {
            String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
            String statDate = DateUtils.getAnotherDay("yyyy-MM-dd", nowDate, -1);
            QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
            tokenQueryWrapper.eq("media_id", 2);
            tokenQueryWrapper.eq("account_id", accountId);
            CtopOauthToken ctopOauthTokens = tokenMapper.selectOne(tokenQueryWrapper);
            if (!Check.isNull(ctopOauthTokens)) {
                historyReportTaskService.createTask(ctopOauthTokens.getAccountId(), ctopOauthTokens.getAccessToken(), statDate, statDate, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_DAILY);

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


    @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 = "/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 = "/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 = tokenMapper.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 = tokenMapper.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 = tokenMapper.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 = tokenMapper.selectList(tokenQueryWrapper);
            if (!Check.isNull(ctopOauthTokens)) {
                for (CtopOauthToken token : ctopOauthTokens) {
                    historyReportTaskService.createTask(token.getAccountId(), token.getAccessToken(), "2020-09-01", "2020-10-01", 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 = tokenMapper.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 = tokenMapper.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;
    }


    @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 = tokenMapper.selectOne(oauthTokenQueryWrapper);
        try {
            // kuaishouInterfaceService.getCampaignList(token, null, null);
            //1：获取全量广告组数据
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = simpleDateFormat.parse("2020-11-11");
            kuaishouInterfaceService.getGroupList(token, parse, parse);
        } 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 = tokenMapper.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 = tokenMapper.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 = tokenMapper.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);
                }
            });
        });
    }

    @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(8);
                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;
                }
                log.info("获取快手操作记录开始:accountId:{},startDate:{},endDate:{}", token.getAccountId(), startDate, endDate);
                kuaishouInterfaceService2.getOperationRecord(token.getAccountId(), token.getAccessToken(), operationTarget, startDate, endDate);
                log.info("获取快手操作记录结束:accountId:{},startDate:{},endDate:{}", token.getAccountId(), startDate, endDate);
            }


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

        return result;
    }

    @Autowired
    public IBytedanceInterfaceService bytedanceInterfaceService;

    @GetMapping(value = "/searchLog")
    public Result searchLog(@Param("accountId") Long accountId, @Param("startDate") String startDate, @Param("endDate") String endDate, @Param("operationTarget") Integer operationTarget) {
        Result result = new Result();

        if (accountId == null) {
            //1:查询当日数据
            QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("media_id", 1);
            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(8);
            tokens.forEach(token -> {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        log.info("获取操作记录开始:accountId:{},startDate:{},endDate:{}", token.getAccountId(), startDate, endDate);
                        bytedanceInterfaceService.searchLog(token.getAccountId(), token, operationTarget, startDate, endDate);
                        log.info("获取快手操作记录结束:accountId:{},startDate:{},endDate:{}", token.getAccountId(), startDate, endDate);
                    }
                });
            });
        } 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;
            }
            log.info("获取快手操作记录开始:accountId:{},startDate:{},endDate:{}", token.getAccountId(), startDate, endDate);
            bytedanceInterfaceService.searchLog(accountId, token, operationTarget, startDate, endDate);
            log.info("获取快手操作记录结束:accountId:{},startDate:{},endDate:{}", token.getAccountId(), startDate, endDate);
        }

        return result;
    }

    @Autowired
    private IKuaiShouCommentService kuaiShouCommentService;

    @GetMapping("deleteComment")
    public Map<String, Object> deleteComment(Long accountId) {
        Map<String, Object> result = new HashMap<>();
        kuaiShouCommentService.shieldComment(accountId);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @GetMapping("loadMatData")
    public Map<String, Object> getData(String startDate, String endDate, Long accountId) {
        Map<String, Object> result = new HashMap<>();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        Date start = DateUtils.parseDate(startDate, "yyyy-MM-dd");
        int days = DateUtils.getdaysOfTwoDate(startDate, endDate) + 1;
        for (int i = 0; i < days; i++) {
            String getDate = DateUtils.formatDate(DateUtils.addDay(start, i));
            bytedanceReportService.bytedanceMaterialReport(token, getDate, getDate);
        }
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @GetMapping("loadAccountData")
    public Map<String, Object> getData(Long accountId) {
        Map<String, Object> result = new HashMap<>();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        reportService.getAdvertiserReport(token, DateUtils.parseDate("2021-01-01", "yyyy-MM-dd"), DateUtils.parseDate("2021-01-31", "yyyy-MM-dd"), CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }
}
