
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.MailLogMapper;
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.ai.entity.AiKuaishouAdvertiserStrategy;
import cn.com.ctop.kuaishou.modules.ai.entity.AiKuaishouUnitLevelOperationRecord;
import cn.com.ctop.kuaishou.modules.ai.mapper.AiKuaishouUnitLevelOperationRecordMapper;
import cn.com.ctop.kuaishou.modules.ai.service.IAiKuaishouAdvertiserStrategyService;
import cn.com.ctop.kuaishou.modules.ai.service.IAiKuaishouCreateCreativeService;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCreative;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouProgramCreative;
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.material.service.IEtlKuaishouVideoInfoService;
import cn.com.ctop.kuaishou.modules.report.entity.KuaiShouProjectData;
import cn.com.ctop.kuaishou.modules.report.service.IKuaiShouDailyAgentService;
import cn.com.ctop.kuaishou.modules.report.service.IKuaiShouProjectDataService;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouAudienceReportDailyService;
import cn.com.ctop.manage.modules.material.service.IMaterialUploadService;
import cn.com.ctop.toutiao.modules.link.service.IETLReportBytedanceVideoService;
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.entity.BytedanceCheckReportTaskInfo;
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 com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
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.jeecg.modules.ctop.entity.TransferAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
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;

/**
 * @author jeecg-boot
 */

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {
    @Resource
    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;
    static ExecutorService executorService = Executors.newFixedThreadPool(10);
    static ExecutorService suzhaoService = Executors.newFixedThreadPool(5);
    @Autowired
    private IKuaiShouDailyAgentService dailyAgentService;
    @Autowired
    private ICtopOauthTokenService ctopOauthTokenService;
    @Autowired
    private IBindAccountAuthService bindAccountAuthService;
    @Resource
    private UserAllocationMapper allocationMapper;
    @Autowired
    private IBytedanceReportService bytedanceReportService;
    @Autowired
    private IUserAllocationService allocationService;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaiShouProjectDataService kuaiShouProjectDataService;
    @Autowired
    private IKuaiShouReportDailyMaterialService kuaiShouReportDailyMaterialService;
    @Autowired
    private IKuaiShouCreativeService creativeService;
    @Autowired
    private IKuaiShouGroupService groupService;
    @Autowired
    private MailLogMapper mailLogMapper;
    @Autowired
    private CorpWexinUtils corpWexinUtils;
    @Autowired
    private IBatchService batchService;
    static ExecutorService videoService = Executors.newFixedThreadPool(8);
    @Autowired
    private IMaterialUploadService materialUploadService;
    @Autowired
    private IKuaishouProgramCreativeService kuaishouProgramCreativeService;
    @Autowired
    private IEtlKuaishouVideoInfoService etlKuaishouVideoInfoService;
    @Autowired
    private IByteDanceAdvertiserDataService advertiserDataService;
    @Autowired
    private IReportService reportService;
    @Autowired
    private IBytedanceEffectVideoInfoService effectVideoInfoService;
    @Autowired
    public IBytedanceInterfaceService bytedanceInterfaceService;
    @Autowired
    private IKuaiShouCommentService kuaiShouCommentService;
    @Autowired
    IBytedanceVideoReportService bytedanceVideoReportService;
    @Autowired
    IETLReportBytedanceVideoService etlReportBytedanceVideoService;
    @Autowired
    private IKuaishouAudienceReportDailyService kuaishouAudienceReportDailyService;
    static ExecutorService executorServic1e = Executors.newFixedThreadPool(5);
    @Autowired
    private IKuaiShouDailyReportTaskService dailyReportTaskService;

    @Value("${xxl-job.requestUrl}")
    private String jobUrl;

    @GetMapping(value = "/cleanData")
    public void cleanData() {
        List<String> dateList = videoGetService.getDateList();
        for (int i = 0; i < dateList.size(); i++) {
            String s = dateList.get(i);
            etlKuaishouVideoInfoService.etlKuaishouVideoInfo(s);
        }
    }

    @Autowired
    private IMailLogService mailLogService;

    @GetMapping(value = "/getProgramCreative")
    public void getProgramCreative() {
        try {
            TransferAccount transferAccountEntity = new TransferAccount();
            transferAccountEntity.setAccountId(30862452L);
            //根据账户ID获取总监
            JSONObject accountJson = mailLogMapper.getAccountInfo(transferAccountEntity.getAccountId());
            BigDecimal cost = new BigDecimal(0);
            if (!Check.isNull(accountJson)) {
                Integer mediaId = accountJson.getInteger("mediaId");
                if (!Check.isNull(mediaId)) {
                    if (mediaId == 1) {
                        cost = mailLogMapper.getBytedanceCost(transferAccountEntity.getAccountId());
                    }
                    if (mediaId == 2) {
                        cost = mailLogMapper.getKuaishouCost(transferAccountEntity.getAccountId());
                    }
                }
                if (cost.compareTo(BigDecimal.ZERO) > 0) {
                    String leaderId = accountJson.getString("leaderId");
                    mailLogService.sendLeaderWeChat("1111", 1, "113dee46c7df464da78c07a985e92cd1", transferAccountEntity.getAccountId(), "b07f2bdd0f914f1dab2b4e841764911f", "f6a6843879c949618e4a859140c8a127", cost);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping(value = "/updateProgramCreative")
    public void updateProgramCreative() {
        List<Long> list = new ArrayList();
        list.add(10173366L);
        list.add(10173375L);
        list.add(10298910L);
        list.add(10299210L);
        list.add(10299221L);
        list.add(10299241L);
        for (int i = 0; i < list.size(); i++) {
            Long accountId = list.get(i);
            CtopOauthToken token = oauthTokenService.getTokenByAccountId(accountId);
            QueryWrapper<KuaishouProgramCreative> creativeQueryWrapper = new QueryWrapper<>();
            creativeQueryWrapper.eq("account_id", accountId);
            creativeQueryWrapper.lt("creative_create_time", "2021-07-11 00:00:00");
            List<KuaishouProgramCreative> proList = kuaishouProgramCreativeService.list(creativeQueryWrapper);
            if (Check.isNull(proList)) {
                continue;
            }
            for (KuaishouProgramCreative programCreative : proList) {
                Long unitId = programCreative.getUnitId();
                if (Check.isNull(unitId)) {
                    continue;
                }
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String updateUrl = "https://ad.e.kuaishou.com/rest/openapi/v2/creative/advanced/program/update";
                            Map<String, String> headers = new HashMap<>();
                            headers.put("Content-Type", "application/json");
                            headers.put("Access-Token", token.getAccessToken());
                            Map<String, Object> param = new HashMap<>();
                            param.put("advertiser_id", token.getAccountId());
                            param.put("unit_id", unitId);

                            String replaceUrll = "https://uri6.com/tkio/Yj6773a?imei=__IMEI2__&androidid=__ANDROIDID2__&oaid=__OAID__&mac=__MAC__&ip=__IP__&ry_adcreative_id=__CID__&ry_adplan_id=__DID__&ry_adplan_name=__DNAME__&ry_adgroup_id=__AID__&callback=__CALLBACK__&csite=__CSITE__&accountid=__ACCOUNTID__&ua=__UA__&os=__OS__&noredirect=true";
                            param.put("click_url", replaceUrll);
                            String result = HttpUtils.httpPostRequest(updateUrl, param, headers);
                            JSONObject resultJson = JSONObject.parseObject(result);
                            Integer code = resultJson.getInteger("code");
                            if (code == 0) {
                                log.info("修改成功,accountId:{},unitId:{}", token.getAccountId(), unitId);
                                QueryWrapper<KuaishouProgramCreative> programCreativeQueryWrapper = new QueryWrapper<>();
                                programCreativeQueryWrapper.eq("account_id", accountId);
                                programCreativeQueryWrapper.eq("unit_id", unitId);
                                kuaishouProgramCreativeService.remove(programCreativeQueryWrapper);

                            } else {
                                log.info("修改失败,accountId:{},unitId:{}，原因：{}", token.getAccountId(), unitId, resultJson.getString("message"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }


    @GetMapping(value = "/campaignList")
    public void campaignList() {
        List<Long> list = new ArrayList();
        list.add(9549277L);
        list.add(9635234L);
        list.add(9767697L);
        list.add(9767717L);
        list.add(9549313L);

        for (int i = 0; i < list.size(); i++) {
            Long accountId = list.get(i);
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            // kuaishouInterfaceService.getCampaignList(oauthToken, null, null);
            videoService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        //   kuaishouInterfaceService.getCampaignList(oauthToken, null, null);
                        kuaishouInterfaceService.getGroupList(oauthToken, null, null);
                        //     kuaishouInterfaceService.getCreativeList(oauthToken, null, null);
                        Thread.sleep(1500);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        }

    }


    @GetMapping(value = "/creativeList")
    public void creativeList() {
        List<Long> list = new ArrayList();
        list.add(10108671L);


        for (int i = 0; i < list.size(); i++) {
            Long accountId = list.get(i);
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);


            suzhaoService.submit(new Runnable() {
                @Override
                public void run() {
                    kuaishouInterfaceService.getCreativeList(oauthToken, null, null);
                }
            });
            try {
                Thread.sleep(400L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }


    @GetMapping(value = "/updateUnit")
    public void updateUnit() throws Exception {
        List<Long> list = new ArrayList();
        list.add(9556344L);
        list.add(9743738L);


        for (int i = 0; i < list.size(); i++) {
            Long accountId = list.get(i);
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
            groupQueryWrapper.eq("account_id", accountId);
            List<KuaiShouGroup> list1 = groupService.list(groupQueryWrapper);
            for (KuaiShouGroup group : list1) {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject json = new JSONObject();
                            json.put("unitId", group.getUnitId());
                            json.put("cpaBid", 18 * 1000);
                            //     json.put("gender", "2");
                            batchService.updateUnit(json, oauthToken);
                            Thread.sleep(1500);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });


            }


        }


    }

    @GetMapping(value = "/updateCreative")
    public void updateCreative() {
        List<Long> list = new ArrayList();
        list.add(10173366L);
        list.add(10173375L);
        list.add(10298910L);
        list.add(10299210L);
        list.add(10299221L);
        list.add(10299241L);

        for (int i = 0; i < list.size(); i++) {
            Long accountId = list.get(i);
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            QueryWrapper<KuaiShouCreative> creativeQueryWrapper = new QueryWrapper<>();
            creativeQueryWrapper.eq("account_id", accountId);
            creativeQueryWrapper.eq("status", 52);
            creativeQueryWrapper.lt("creative_create_time", "2021-07-11 00:00:00");
            List<KuaiShouCreative> creativeList = creativeService.list(creativeQueryWrapper);
            if (Check.isNull(creativeList)) {
                continue;
            }
            for (KuaiShouCreative creative : creativeList) {
                QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
                groupQueryWrapper.eq("unit_id", creative.getUnitId());
                groupQueryWrapper.last("limit 1");
                KuaiShouGroup one = groupService.getOne(groupQueryWrapper);
                if (Check.isNull(one)) {
                    continue;
                }
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject json = new JSONObject();
                            json.put("creativeId", creative.getCreativeId());
                            String url = "https://uri6.com/tkio/Yj6773a?imei=__IMEI2__&androidid=__ANDROIDID2__&oaid=__OAID__&mac=__MAC__&ip=__IP__&ry_adcreative_id=__CID__&ry_adplan_id=__DID__&ry_adplan_name=__DNAME__&ry_adgroup_id=__AID__&callback=__CALLBACK__&csite=__CSITE__&accountid=__ACCOUNTID__&ua=__UA__&os=__OS__&noredirect=true";

                            if (creative.getCreativeMaterialType() == 1) {
                                json.put("clickTrackUrl", url);
                            } else if (creative.getCreativeMaterialType() == 4) {
                                json.put("impressionUrl", url);
                                json.put("clickTrackUrl", url);

                            }
                            JSONObject jsonObject = batchService.updateCreative(json, oauthToken);
                            log.info("修改创意返回信息accountId:{},creative:{},结果：{}", creative.getAccountId(), creative.getCreativeId(), jsonObject);
                            Thread.sleep(1000L);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }


        }
    }


    @GetMapping("/testSend")
    public void testSend(String userId) {

        JSONObject weChatId = mailLogMapper.getWChatIdByUserId(userId);
        if (weChatId.isEmpty()) {
            log.error(String.format("User WeChat not found. userId =%s", userId));
            //TODO 通知管理员添加邮箱
        } else {
            corpWexinUtils.sendMessageByWeChatId(weChatId, "hahahahahahah");
        }
    }

    @GetMapping("/uploadVideo")
    public String uploadVideo(Long projectId) {
        //  832
        JSONArray idList = materialInfoService.getIdListByProject(832L);
        JSONArray accountArray = new JSONArray();
        accountArray.add(9549277L);
        accountArray.add(9635234L);
        accountArray.add(9767697L);
        accountArray.add(9825207L);
        materialUploadService.uploadAccount("2", idList, accountArray, "2e3b982046a44b5faadaa77a7c0da114", true);
        return "success";
    }

    @GetMapping("/cleanNewlyData")
    public void cleanNewlyData(String startDate, String endDate) throws ParseException {


        String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
        String yesterday = DateUtils.getAnotherDay("yyyy-MM-dd", nowDate, -1);
        //1:查询当日数据
        QueryWrapper<KuaiShouProjectData> queryWrapper = new QueryWrapper();
        queryWrapper.eq("project_status", 0);
        List<KuaiShouProjectData> list = kuaiShouProjectDataService.list(queryWrapper);
        if (Check.isNull(list)) {
            return;
        }
        for (KuaiShouProjectData projectData : list) {
            Long projectId = projectData.getProjectId();
            if (Check.isNull(projectId)) {
                continue;
            }
            QueryWrapper<UserAllocation> allocationQueryWrapper = new QueryWrapper<>();
            allocationQueryWrapper.eq("project_id", projectId);
            allocationQueryWrapper.eq("account_status", 0);
            List<UserAllocation> accountIds = allocationService.list(allocationQueryWrapper);
            if (Check.isNull(accountIds)) {
                continue;
            }
            for (UserAllocation allocation : accountIds) {
                CtopOauthToken token = tokenService.getTokenByAccountId(allocation.getAccountId());
                if (Check.isNull(token)) {
                    continue;
                }

                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        kuaiShouReportDailyMaterialService.getMaterialReportByAccountIdAndStatDate(token.getAccountId(), token.getAccessToken(), yesterday, yesterday, "HOURLY", 1);

                        //  hourlyGroupService.getAdvertiserGroupReportHourly(token.getAccountId(), token.getAccessToken(), yesterday, yesterday);
                    }
                });
            }
        }


    }

    @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(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 || "".equals(params.trim())) {
            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 = "/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);
            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();
                        }
                    }
                });
            }
        }
    }


    @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 = "/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 = "/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 = "/getHistoryData")
    public String getHistoryData(String startDate, String endDate) {
        Result<String> result = new Result<>();
        try {
            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(), startDate, endDate, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_HISTORY);
                }

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


    @GetMapping(value = "/getHistoryDataByAccountId")
    public String getHistoryDataByAccountId(Long accountId, String startDte, String endDate) {
        Result<String> result = new Result<>();
        try {
            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(), startDte, endDate, 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 = "/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("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();
        }
    }


    @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;
    }


    @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("/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() {
        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;
    }


    @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;
    }


    @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-03-01", "yyyy-MM-dd"), DateUtils.parseDate("2021-03-31", "yyyy-MM-dd"), CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }


    /**
     * 勿动勿删，煜一人群报表数据拉取接口。
     *
     * @param
     * @return void
     * @throws
     * @author ZHAOXA
     *//*

    @PostMapping(value = "/getAudienceData")
    public Result getAudienceData(@RequestBody JSONObject request) throws Exception {
        Long accountId = request.getLong("accountId");
        Long planId = request.getLong("planId");
        Long unitId = request.getLong("unitId");
        String type = request.getString("type");
        String startTime = request.getString("startTime");
        String endTime = request.getString("endTime");
        if (Check.isNull(accountId) || Check.isNull(planId) || Check.isNull(unitId) || Check.isNull(type) || Check.isNull(endTime) || Check.isNull(startTime)) {
            return Result.error("缺少参数");
        }
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        List<String> dayList = new ArrayList<>();
        if (startTime.equals(endTime)) {
            dayList.add(startTime);
        } else {
            dayList = DateUtils.getDays(startTime, endTime);
        }
        int page = 1;
        int pageSize = 2000;
        dayList.forEach(date -> executorServic1e.submit(() -> {
            try {
                kuaishouAudienceReportDailyService.crowdAnalysisReport(token, date, type, planId, unitId, page, pageSize);
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error("获取人群消息异常", e);
            }
        }));
        return Result.ok("success");
    }

    static CountDownLatch countDownLatch = null;
    @Resource
    AiKuaishouUnitLevelOperationRecordMapper kuaishouUnitLevelOperationRecordMapper;

    @GetMapping(value = "/getAudienceDataNew")
    public void getAudienceData(@RequestParam(required = false, defaultValue = "2019-01-01") String date) throws Exception {
        int page = 1;
        int pageSize = 2000;
        if (date.equals("2019-01-01")) {
            date = DateUtils.formatDate(DateUtils.addDay(DateUtils.getNowDate(), -1), "yyyy-MM-dd");
        }
        List<CtopOauthToken> tokens = tokenService.getByProjectId(458L);    //淘特项目
        for (CtopOauthToken token : tokens) {
            Date startDate = DateUtils.addDay(DateUtils.getNowDate(), -1);
            if (startDate.after(token.getAccessTokenExpiresIn())) {   //过期跳过
                continue;
            }
            Date enDate = DateUtils.addDay(startDate, -30);
            List<AiKuaishouUnitLevelOperationRecord> planIdsAndUnitIds = kuaishouUnitLevelOperationRecordMapper.selectAllByAccountIdAndDate(token.getAccountId(), enDate, startDate);
            if (Check.isNull(planIdsAndUnitIds)) {
                continue;
            }
            countDownLatch = new CountDownLatch(planIdsAndUnitIds.size());
            String finalDate = date;
            planIdsAndUnitIds.forEach(planIdAndUnitId -> executorService.submit(() -> {
                try {
                    // province: 省级地域分布, city: 地级地域分布,gender: 性别分布,ageSegment: 年龄分布clientId: 系统分布 businessInterestTags: 商业兴趣分布
                    kuaishouAudienceReportDailyService.crowdAnalysisReport2(token, finalDate, "province", planIdAndUnitId.getCampaignId(), planIdAndUnitId.getUnitId(), page, pageSize);
                    kuaishouAudienceReportDailyService.crowdAnalysisReport2(token, finalDate, "city", planIdAndUnitId.getCampaignId(), planIdAndUnitId.getUnitId(), page, pageSize);
                    kuaishouAudienceReportDailyService.crowdAnalysisReport2(token, finalDate, "gender", planIdAndUnitId.getCampaignId(), planIdAndUnitId.getUnitId(), page, pageSize);
                    kuaishouAudienceReportDailyService.crowdAnalysisReport2(token, finalDate, "clientId", planIdAndUnitId.getCampaignId(), planIdAndUnitId.getUnitId(), page, pageSize);
                    kuaishouAudienceReportDailyService.crowdAnalysisReport2(token, finalDate, "ageSegment", planIdAndUnitId.getCampaignId(), planIdAndUnitId.getUnitId(), page, pageSize);
                    kuaishouAudienceReportDailyService.crowdAnalysisReport2(token, finalDate, "businessInterestTags", planIdAndUnitId.getCampaignId(), planIdAndUnitId.getUnitId(), page, pageSize);
                } catch (Exception e) {
                } finally {
                    countDownLatch.countDown();
                }
            }));
            countDownLatch.await();
        }
    }

    @Autowired
    private IAiKuaishouAdvertiserStrategyService strategyService;
    @Autowired
    private IAiKuaishouCreateCreativeService createCreativeService;

    @GetMapping("testCreateCreative")
    public Map<String, Object> testCreateCreative(Long accountId, Integer createType) {
        Map<String, Object> result = new HashMap<>();
        AiKuaishouAdvertiserStrategy strategy = strategyService.getByAccountId(accountId);
        if (strategy == null) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        createCreativeService.autoCreateCreative(strategy, createType, 150L);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @GetMapping("testProgramCreative")
    public Map<String, Object> testProgramCreative(Long accountId, Integer createType) {
        Map<String, Object> result = new HashMap<>();
        AiKuaishouAdvertiserStrategy strategy = strategyService.getByAccountId(accountId);
        if (strategy == null) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        createCreativeService.autoCreateProgramCreative(strategy, createType, 150L);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @GetMapping("testCreateCreativeLimit")
    public Map<String, Object> testCreateCreativeLimit(Long accountId, Integer hour) throws ParseException {
        Map<String, Object> result = new HashMap<>();
        AiKuaishouAdvertiserStrategy strategy = strategyService.getByAccountId(accountId);
        if (strategy == null) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        createCreativeService.customCreativeSupplement(strategy, hour);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @Autowired
    private IBytedanceCheckReportTaskInfoService checkReportTaskInfoService;

    @GetMapping("testInitCheckDataTask")
    public Map<String, Object> testInitCheckDataTask(String date) throws ParseException {
        Map<String, Object> result = new HashMap<>();
        checkReportTaskInfoService.initTask(date);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }


    @GetMapping("testCheckCost")
    public Map<String, Object> testCheckCost(String date) throws ParseException {
        Map<String, Object> result = new HashMap<>();
        List<BytedanceCheckReportTaskInfo> taskInfos = checkReportTaskInfoService.getListByParams(null, "2021-06-01", 0);
        if (null != taskInfos && !taskInfos.isEmpty()) {
            for (BytedanceCheckReportTaskInfo taskInfo : taskInfos) {
                checkReportTaskInfoService.checkCost(taskInfo);
            }
        }
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @GetMapping("checkCostData")
    public void checkCostData(String date) {
        //1:初始化
        checkReportTaskInfoService.initTask(date);
        //2: checkCost
        List<BytedanceCheckReportTaskInfo> taskInfos = checkReportTaskInfoService.getListByParams(null, date, 0);
        if (null != taskInfos && !taskInfos.isEmpty()) {
            for (BytedanceCheckReportTaskInfo task : taskInfos) {
                checkReportTaskInfoService.checkCost(task);
            }
            log.info("{}:数据获取完成", date);
        }
    }

    @GetMapping("refreshReportData")
    public void refreshReportData() throws Exception {
        //1：查询异常任务数据
        List<BytedanceCheckReportTaskInfo> taskInfos = checkReportTaskInfoService.getListByParams(null, null, 50001);
        if (null != taskInfos && !taskInfos.isEmpty()) {
            taskInfos.forEach(taskInfo -> {
                try {
                    checkReportTaskInfoService.reloadData(taskInfo);
                    checkReportTaskInfoService.checkCost(taskInfo);
                } catch (Exception e) {
                }
            });
            log.info("数据更新完成");
        }
    }
*/
    @GetMapping("checkUnitBid")
    public Result checkUnitBid(Long accountId) throws Exception {
        Date nowDate = new Date();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        kuaishouInterfaceService.getGroupList(token, nowDate, nowDate);
        return Result.ok("success");
    }
}

