package com.xxl.job.executor.report.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.executor.common.entity.CtopOauthToken;
import com.xxl.job.executor.common.service.ICtopOauthTokenService;
import com.xxl.job.executor.report.entity.BytedanceDailyReportTask;
import com.xxl.job.executor.report.entity.BytedanceReportMaterialDaily;
import com.xxl.job.executor.report.entity.BytedanceReportMaterialRetry;
import com.xxl.job.executor.report.entity.BytedanceReportVideoMaterialDaily;
import com.xxl.job.executor.report.mapper.BytedanceDailyReportTaskMapper;
import com.xxl.job.executor.report.mapper.BytedanceReportMaterialDailyMapper;
import com.xxl.job.executor.report.service.IBytedanceDailyReportTaskService;
import com.xxl.job.executor.report.service.IBytedanceReportService;
import com.xxl.job.executor.utils.Check;
import com.xxl.job.executor.utils.DateUtils;
import com.xxl.job.executor.utils.HttpUtils;
import com.xxl.job.executor.utils.LoadFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Primary

public class BytedanceReportServiceImpl implements IBytedanceReportService {

    @Value("${jeecg.path.report-history}")
    private String downloadPath;
    @Autowired
    private BytedanceDailyReportTaskMapper bytedanceDailyReportTaskMapper;

    @Autowired
    private IBytedanceDailyReportTaskService bytedanceDailyReportTaskService;

    @Autowired
    private ICtopOauthTokenService ctopOauthTokenService;

    @Autowired
    private BytedanceReportMaterialDailyMapper bytedanceReportMaterialDailyMapper;

    /////////////////////////////////////////////////////////////////////////////////////////////////
    //创建异步任务
    @Override
    public void bytedanceAsyncTaskCreate(String startDate, String endDate, CtopOauthToken token, Integer type) {
        int diffMonths = DateUtils.calDiffMonth(DateUtils.parseDate(startDate, "yyyy-MM-dd"), DateUtils.parseDate(endDate, "yyyy-MM-dd"));
        if (diffMonths == 0) {
            bytedanceAsyncTaskCreateByMonth(startDate, endDate, token, type);
        } else {
            for (int i = 0; i <= diffMonths; i++) {
                if (i == 0) {
                    Map<String, String> dateMap = DateUtils.getMaxMinDaysOfAddMonth(startDate, "yyyy-MM-dd", i);
                    String end = dateMap.get("endDate");
                    bytedanceAsyncTaskCreateByMonth(startDate, end, token, type);
                } else if (i == diffMonths) {
                    Map<String, String> dateMap = DateUtils.getMaxMinDaysOfAddMonth(startDate, "yyyy-MM-dd", i);
                    String start = dateMap.get("startDate");
                    bytedanceAsyncTaskCreateByMonth(start, endDate, token, type);
                } else {
                    Map<String, String> dateMap = DateUtils.getMaxMinDaysOfAddMonth(startDate, "yyyy-MM-dd", i);
                    String start = dateMap.get("startDate");
                    String end = dateMap.get("endDate");
                    bytedanceAsyncTaskCreateByMonth(start, end, token, type);
                }
            }
        }
    }

    /***
     * 由于异步拉取数据不能跨月，故只能按月循环拉取
     * @param startDate
     * @param endDate
     * @param token
     */
    private void bytedanceAsyncTaskCreateByMonth(String startDate, String endDate, CtopOauthToken token, Integer type) {
        String access_token = token.getAccessToken();
        Long accountId = token.getAccountId();

        // 请求地址
        String open_api_domain = "https://ad.toutiao.com";
        String path = "/open_api/2/async_task/create/";

        String taskName = System.currentTimeMillis() + "";
        // 请求参数
        final Map filtering = new HashMap() {
            {
                put("start_date", startDate);
                put("end_date", endDate);
                if (type == 1) {//创意
                    put("group_by", new String[]{"STAT_GROUP_BY_CREATIVE_ID", "STAT_GROUP_BY_TIME_DAY", "STAT_GROUP_BY_CREATIVE_MATERIAL_MODE"});   //按照创意分组、天分组、创意类型分组查询
                } else if (type == 2) {//广告主
                    put("group_by", new String[]{"STAT_GROUP_BY_ADVERTISER_ID", "STAT_GROUP_BY_TIME_DAY", "STAT_GROUP_BY_PRICING_CATEGORY"});   //按照广告主分组、天分组、广告类型类型分组查询
                } else if (type == 3) {//广告组
                    put("group_by", new String[]{"STAT_GROUP_BY_CAMPAIGN_ID", "STAT_GROUP_BY_TIME_DAY", "STAT_GROUP_BY_CAMPAIGN_TYPE"});  //按照广告组、天、广告组类型分组
                } else {//4广告计划
                    put("group_by", new String[]{"STAT_GROUP_BY_AD_ID", "STAT_GROUP_BY_TIME_DAY", "STAT_GROUP_BY_LANDING_TYPE"});  //按照广告计划、天、推广类型分组
                }
            }
        };
        final Map data = new HashMap() {
            {
                put("advertiser_id", accountId);
                put("task_name", taskName);
                put("task_type", "REPORT");
                put("task_params", filtering);
            }
        };

        JSONObject json = HttpUtils.bytedancePostRequest(access_token, open_api_domain + path, JSONObject.parseObject(JSONObject.toJSONString(data)));
        if (json == null) {
            log.error("请求有误:" + JSONObject.toJSONString(data));
        }

        String jsonString = JSON.toJSONString(json);

        if (!Check.isNull(json)) {
            Integer code = json.getInteger("code");
            if (code != 0) {
                log.error("返回信息错误，错误码为：" + code + ",头条accountId:" + accountId + ",message:" + json.getString("message"));
                return;
            }
            JSONObject dataJson = json.getJSONObject("data");

            //解析数据并入库
            BytedanceDailyReportTask task = new BytedanceDailyReportTask();
            task.setAccountId(accountId);
            task.setTaskCreateTime(dataJson.getDate("create_time") == null ? null : dataJson.getDate("create_time"));
            task.setTaskId(dataJson.getLong("task_id") == null ? null : dataJson.getLong("task_id"));
            task.setTaskName(dataJson.getString("task_name") == null ? null : dataJson.getString("task_name"));
            task.setTaskParams(JSON.toJSONString(dataJson.getJSONObject("task_params")));
            task.setJson(jsonString);
            task.setTaskStatus(dataJson.getString("task_status"));
            task.setTaskType(dataJson.getString("task_type"));
            task.setType(type);
            task.setIsDownload(0);
            task.setStatus(1); //状态1正常 0废弃
            bytedanceDailyReportTaskMapper.insert(task);
        }
    }

    //获取任务列表
    @Override
    public void bytedanceAsyncTaskGet() {
        QueryWrapper<BytedanceDailyReportTask> taskQueryWrapper = new QueryWrapper<>();
        //查询三种状态的信息--任务已创建、任务执行中、任务处理中
        taskQueryWrapper.eq("is_download", 0);
        //taskQueryWrapper.in("task_status", "ASYNC_TASK_STATUS_CREATED","ASYNC_TASK_STATUS_EXECUTING","ASYNC_TASK_STATUS_EXECUTING_STAGE2");
        taskQueryWrapper.notIn("task_status", "ASYNC_TASK_STATUS_FAILED");
        taskQueryWrapper.orderByDesc("create_time");
        List<BytedanceDailyReportTask> taskList = bytedanceDailyReportTaskService.list(taskQueryWrapper);

        if (!Check.isNull(taskList)) {
            for (BytedanceDailyReportTask task : taskList) {
                CtopOauthToken token = ctopOauthTokenService.getTokenByAccountId(task.getAccountId());

                if (!Check.isNull(token)) {
                    // 请求地址
                    String open_api_domain = "https://ad.toutiao.com";
                    String path = "/open_api/2/async_task/get/";

                    String access_token = token.getAccessToken();
                    Long accountId = task.getAccountId();
                    final Long advertiser_id = accountId;

                    // 请求参数
                    final Map filtering = new HashMap() {
                        {
                            put("task_ids", new Long[]{task.getTaskId()});
                            put("task_name", task.getTaskName());
                        }
                    };
                    Map data = new HashMap() {
                        {
                            put("advertiser_id", advertiser_id);
                            put("filtering", filtering);
                        }
                    };

                    JSONObject json = HttpUtils.bytedanceGetRequest(access_token, open_api_domain + path, JSONObject.parseObject(JSONObject.toJSONString(data)));
                    if (json == null) {
                        log.error("请求有误:" + JSONObject.toJSONString(data));
                    }

                    try {
                        String jsonString = JSON.toJSONString(json);
                        //log.info("返回json为" + jsonString);

                        if (!Check.isNull(json)) {
                            Integer code = json.getInteger("code");
                            if (code != 0) {
                                log.info("获取任务列表返回信息错误，错误码为：" + code + ",头条accountId:" + accountId + "taskId:" + task.getTaskId());
                                continue;
                            }

                            JSONObject jsonData = json.getJSONObject("data");
                            if (Check.isNull(jsonData)) {
                                log.error("获取任务列表返回信息data内容为空");
                            }
                            JSONArray jsonArrayay = jsonData.getJSONArray("list");

                            for (int i = 0; i < jsonArrayay.size(); i++) {
                                JSONObject detailJson = jsonArrayay.getJSONObject(i);
                                if (!Check.isNull(detailJson)) {
                                    String taskStatus = detailJson.getString("task_status");

                                    if ("ASYNC_TASK_STATUS_COMPLETED".equals(taskStatus)) {
                                        bytedanceAsyncTaskDownload(task, token, task.getType());
                                        task.setIsDownload(1);
                                    }
                                    task.setTaskStatus(taskStatus);
                                    bytedanceDailyReportTaskMapper.updateById(task);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //下载任务结果   type 1.creative 2.account 3.campaign 4.plan
    private void bytedanceAsyncTaskDownload(BytedanceDailyReportTask task, CtopOauthToken token, Integer type) {
        // 请求地址
        String open_api_domain = "https://ad.toutiao.com";
        String path = "/open_api/2/async_task/download/";

        String url = open_api_domain + path;
        String fileName = task.getAccountId() + "_" + "type" + type + "_" + task.getTaskId() + "_" + System.currentTimeMillis() + ".csv";
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("advertiser_id", task.getAccountId());
        requestMap.put("task_id", task.getTaskId());
        String localPath = LoadFileUtil.downloadByUrl(requestMap, downloadPath, url, token.getAccessToken(), fileName);
        if (type == 1) {
            //素材异步报表
            bytedanceDailyReportTaskMapper.loadBytedanceDailyCreativeFileAsync(localPath);
        } else if (type == 2) {
            //账户异步报表
            bytedanceDailyReportTaskMapper.loadBytedanceDailyAccountFileAsync(localPath);
        } else if (type == 3) {
            //campaign异步报表
            bytedanceDailyReportTaskMapper.loadBytedanceDailyCampaignFileAsync(localPath);
        } else if (type == 4) {
            //plan异步报表
            bytedanceDailyReportTaskMapper.loadBytedanceDailyPlanFileAsync(localPath);
        } else {
            log.error("异步报表类型传入错误,task_id:" + task.getTaskId() + ";类型：" + type);
        }
    }

    /////////////////////////////////////////////////////////\
    //素材报表
    @Override
    public int bytedanceMaterialReportRetry(Integer type, CtopOauthToken token, String startDate, String endDate) {
        Long accountId = token.getAccountId();
        log.info("头条素材报表重试开始 当前accountId：{}  {}~{},type:{}" , accountId, startDate,endDate,type);
        Integer page = 1;
        Integer pageSize = 100;
        Integer code = null;
        if(type == 1){
            code = bytedanceMaterialReportByPage(page, pageSize, token, accountId, startDate, endDate);

        }else if(type == 2){
            code = bytedanceVideoMaterialReportByPage(page, pageSize, token, accountId, startDate, endDate);
        }

        BytedanceReportMaterialRetry retry = new BytedanceReportMaterialRetry();
        retry.setAccountId(accountId);
        retry.setStartDate(startDate);
        retry.setEndDate(endDate);
        retry.setStatusCode(code);
        retry.setType(type);
        if (code != 200 && code != 1) {
            retry.setStatus(0);
            bytedanceReportMaterialDailyMapper.replaceMaterialRetry(retry);
        } else {
            retry.setStatus(1);
            bytedanceReportMaterialDailyMapper.replaceMaterialRetry(retry);
        }
        log.info("头条素材报表重试结束 当前accountId：{}  {}~{},type:{},code:{}" , accountId, startDate,endDate,type,code);
        return code;
    }
    @Override
    public int bytedanceMaterialReport(CtopOauthToken token, String startDate, String endDate) {
        Long accountId = token.getAccountId();
        log.info("头条素材报表开始 当前accountId：{}  {}~{}" , accountId, startDate,endDate);
        Integer page = 1;
        Integer pageSize = 100;
        int code = bytedanceMaterialReportByPage(page, pageSize, token, accountId, startDate, endDate);
        if (code != 200 && code != 1) {
            BytedanceReportMaterialRetry retry = new BytedanceReportMaterialRetry();
            retry.setAccountId(accountId);
            retry.setStatus(0);
            retry.setStartDate(startDate);
            retry.setEndDate(endDate);
            retry.setStatusCode(code);
            retry.setType(1);
            bytedanceReportMaterialDailyMapper.replaceMaterialRetry(retry);
        }
        bytedanceReportMaterialDailyMapper.updateImageReportCode();
        bytedanceReportMaterialDailyMapper.updateImageReportProjectId();
        bytedanceReportMaterialDailyMapper.updateImageReportProjectName();
        bytedanceReportMaterialDailyMapper.updateImageReportPlaneId();
        bytedanceReportMaterialDailyMapper.updateImageReportPlaneName();
        log.info("头条素材报表结束 当前accountId为：{}  {}~{}" , accountId, startDate,endDate);
        return code;
    }

    private int bytedanceMaterialReportByPage(Integer page, Integer pageSize, CtopOauthToken token, Long accountId, String startDate, String endDate) {
        String access_token = token.getAccessToken();

        // 请求地址
        String open_api_domain = "https://ad.oceanengine.com";
        String path = "/open_api/2/report/integrated/get/";

        // 请求参数
        Map data = new HashMap() {
            {
                put("advertiser_id", accountId);
                put("start_date", startDate);
                put("end_date", endDate);
                put("page", page);
                put("page_size", pageSize);
                put("group_by", new String[]{"STAT_GROUP_BY_MATERIAL_ID", "STAT_GROUP_BY_INVENTORY", "STAT_GROUP_BY_IMAGE_MODE", "STAT_GROUP_BY_TIME_DAY"});
            }
        };

        JSONObject json = HttpUtils.bytedanceGetRequest(access_token, open_api_domain + path, JSONObject.parseObject(JSONObject.toJSONString(data)));
        if (json == null) {
            log.error("返回为空，请求有误:" + JSONObject.toJSONString(data));
            return -2;
        }

        int returnCode = 200;
        try {
            Integer code = json.getInteger("code");
            if (code != 0) {
                log.error("获取任务列表返回信息错误，错误码为：" + code + ",头条accountId:" + accountId + ";返回json为" + json + "请求为：" + JSONObject.toJSONString(data));
                return -1;
            }

            JSONObject jsonData = json.getJSONObject("data");
            if (Check.isNull(jsonData)) {
                log.error("获取任务列表返回信息data内容为空,头条accountId:" + accountId + ";返回json为" + json + "请求为：" + JSONObject.toJSONString(data));
                return -1;
            }
            JSONObject pageInfo = jsonData.getJSONObject("page_info");
            Integer totalPage = pageInfo.getInteger("total_page");
            Integer currentPage = pageInfo.getInteger("page");

            JSONArray jsonArrayay = jsonData.getJSONArray("list");
            if (jsonArrayay.size() == 0) {
                log.info("accountId:" + accountId + "；没有数据。总页数为：" + totalPage + "当前页数为：" + currentPage);
                return 1;
            }

            List<BytedanceReportMaterialDaily> bytedanceReportMaterialDailyList = new ArrayList<>();
            List<BytedanceReportMaterialDaily> bytedanceReportImageDailyList = new ArrayList<>();
            for (int i = 0; i < jsonArrayay.size(); i++) {
                BytedanceReportMaterialDaily daily = new BytedanceReportMaterialDaily();
                daily.setAccountId(accountId);
                JSONObject detailJson = jsonArrayay.getJSONObject(i);
                if (!Check.isNull(detailJson)) {
                    JSONObject dimensions = detailJson.getJSONObject("dimensions");
                    daily.setImageMode(dimensions.getString("image_mode"));
                    daily.setMaterialId(dimensions.getLong("material_id"));
                    daily.setInventory(dimensions.getString("inventory"));
                    daily.setStatDatetime(dimensions.getDate("stat_datetime") == null ? null : DateUtils.formatDate(dimensions.getDate("stat_datetime"), "yyyy-MM-dd"));
                    JSONObject metrics = detailJson.getJSONObject("metrics");
                    daily.setActivePayAmount(metrics.getInteger("active_pay_amount"));
                    daily.setValidPlayCost(metrics.getBigDecimal("valid_play_cost"));
                    daily.setPlay75FeedBreak(metrics.getInteger("play_75_feed_break"));
                    daily.setNextDayOpen(metrics.getInteger("next_day_open"));
                    daily.setAdvancedCreativeCouponAddition(metrics.getInteger("advanced_creative_coupon_addition"));
                    daily.setConvertMaterial(metrics.getInteger("convert"));
                    daily.setActivePayCost(metrics.getBigDecimal("active_pay_cost"));
                    daily.setInAppCart(metrics.getInteger("in_app_cart"));
                    daily.setPlay25FeedBreak(metrics.getInteger("play_25_feed_break"));
                    daily.setConsultEffective(metrics.getInteger("consult_effective"));
                    daily.setViewMaterial(metrics.getInteger("view"));
                    daily.setDownload(metrics.getInteger("download"));
                    daily.setCpa(metrics.getBigDecimal("cpa"));
                    daily.setCpc(metrics.getBigDecimal("cpc"));
                    daily.setLocationClick(metrics.getInteger("location_click"));
                    daily.setPhoneConfirm(metrics.getInteger("phone_confirm"));
                    daily.setIesMusicClick(metrics.getInteger("ies_music_click"));
                    daily.setPlayOverRate(metrics.getBigDecimal("play_over_rate"));
                    daily.setWifiPlay(metrics.getInteger("wifi_play"));
                    daily.setShopping(metrics.getInteger("shopping"));
                    daily.setQq(metrics.getInteger("qq"));
                    daily.setCtr(metrics.getBigDecimal("ctr"));
                    daily.setCpm(metrics.getBigDecimal("cpm"));
                    daily.setWifiPlayRate(metrics.getBigDecimal("wifi_play_rate"));
                    daily.setLikeMaterial(metrics.getInteger("like"));
                    daily.setPlay50FeedBreak(metrics.getInteger("play_50_feed_break"));
                    daily.setActivePayRate(metrics.getBigDecimal("active_pay_rate"));
                    daily.setActiveCost(metrics.getBigDecimal("active_cost"));
                    daily.setActive(metrics.getInteger("active"));
                    daily.setGameAddictionCost(metrics.getBigDecimal("game_addiction_cost"));
                    daily.setGameAddiction(metrics.getInteger("game_addiction"));
                    daily.setActiveRate(metrics.getBigDecimal("active_rate"));
                    daily.setClick(metrics.getInteger("click"));
                    daily.setPlayDuration_10s(metrics.getInteger("play_duration_10s"));
                    daily.setAdvancedCreativePhoneClick(metrics.getInteger("advanced_creative_phone_click"));
                    daily.setDownloadStart(metrics.getInteger("download_start"));
                    daily.setHomeVisited(metrics.getInteger("home_visited"));
                    daily.setPhone(metrics.getInteger("phone"));
                    daily.setPhoneEffective(metrics.getInteger("phone_effective"));
                    daily.setInAppPay(metrics.getInteger("in_app_pay"));
                    daily.setGameAddictionRate(metrics.getBigDecimal("game_addiction_rate"));
                    daily.setNextDayOpenCost(metrics.getBigDecimal("next_day_open_cost"));
                    daily.setIesChallengeClick(metrics.getInteger("ies_challenge_click"));
                    daily.setTotalPlay(metrics.getInteger("total_play"));
                    daily.setActiveRegisterRate(metrics.getBigDecimal("active_register_rate"));  //头条返回的是 *100 以后的值。。。。
                    daily.setAverageVideoPlay(metrics.getBigDecimal("average_video_play"));
                    daily.setDownloadFinishCost(metrics.getBigDecimal("download_finish_cost"));
                    daily.setPlayDuration_3s(metrics.getInteger("play_duration_3s"));
                    daily.setActiveRegisterCost(metrics.getBigDecimal("active_register_cost"));
                    daily.setShowMaterial(metrics.getInteger("show"));
                    daily.setNextDayOpenRate(metrics.getBigDecimal("next_day_open_rate"));
                    daily.setMapSearch(metrics.getInteger("map_search"));
                    daily.setButton(metrics.getInteger("button"));
                    daily.setPlayDurationSum(metrics.getInteger("play_duration_sum"));
                    daily.setPlay100FeedBreak(metrics.getInteger("play_100_feed_break"));
                    daily.setAdvancedCreativeCounselClick(metrics.getInteger("advanced_creative_counsel_click"));
                    daily.setConvertRate(metrics.getBigDecimal("convert_rate"));
                    daily.setDownloadFinishRate(metrics.getBigDecimal("download_finish_rate"));
                    daily.setConsult(metrics.getInteger("consult"));
                    daily.setShareMaterial(metrics.getInteger("share"));
                    daily.setVote(metrics.getInteger("vote"));
                    daily.setValidPlay(metrics.getInteger("valid_play"));
                    daily.setInstallFinishRate(metrics.getBigDecimal("install_finish_rate"));
                    daily.setRedirect(metrics.getInteger("redirect"));
                    daily.setPayCount(metrics.getInteger("pay_count"));
                    daily.setAdvancedCreativeFormClick(metrics.getInteger("advanced_creative_form_click"));
                    daily.setCost(metrics.getBigDecimal("cost"));
                    daily.setPhoneConnect(metrics.getInteger("phone_connect"));
                    daily.setCoupon(metrics.getInteger("coupon"));
                    daily.setDownloadStartRate(metrics.getBigDecimal("download_start_rate"));
                    daily.setDownloadFinish(metrics.getInteger("download_finish"));
                    daily.setWechat(metrics.getInteger("wechat"));
                    daily.setCouponSinglePage(metrics.getInteger("coupon_single_page"));
                    daily.setInstallFinish(metrics.getInteger("install_finish"));
                    daily.setLottery(metrics.getInteger("lottery"));
                    daily.setPlayOver(metrics.getInteger("play_over"));
                    daily.setInAppOrder(metrics.getInteger("in_app_order"));
                    daily.setDownloadStartCost(metrics.getBigDecimal("download_start_cost"));
                    daily.setFollow(metrics.getInteger("follow"));
                    daily.setMessage(metrics.getInteger("message"));
                    daily.setInAppDetailUv(metrics.getInteger("in_app_detail_uv"));
                    daily.setPlayDuration(metrics.getInteger("play_duration"));
                    daily.setForm(metrics.getInteger("form"));
                    daily.setValidPlayRate(metrics.getBigDecimal("valid_play_rate"));
                    daily.setAveragePlayTimePerPlay(metrics.getBigDecimal("average_play_time_per_play"));
                    daily.setConvertShowRate(metrics.getBigDecimal("convert_show_rate"));
                    daily.setInstallFinishCost(metrics.getBigDecimal("install_finish_cost"));
                    daily.setCommentMaterial(metrics.getInteger("comment"));
                    daily.setInAppUv(metrics.getInteger("in_app_uv"));
                    daily.setRegister(metrics.getInteger("register"));
                    daily.setConvertCost(metrics.getBigDecimal("convert_cost"));
                    if("CREATIVE_IMAGE_MODE_VIDEO".equals(daily.getImageMode())|| "CREATIVE_IMAGE_MODE_VIDEO_VERTICAL".equals(daily.getImageMode())|| "CREATIVE_IMAGE_MODE_UNION_SPLASH_VIDEO".equals(daily.getImageMode())){
                        bytedanceReportMaterialDailyList.add(daily);
                    }else if("CREATIVE_IMAGE_MODE_SMALL".equals(daily.getImageMode())|| "CREATIVE_IMAGE_MODE_LARGE".equals(daily.getImageMode())|| "CREATIVE_IMAGE_MODE_GROUP".equals(daily.getImageMode())|| "CREATIVE_IMAGE_MODE_GIF".equals(daily.getImageMode())|| "CREATIVE_IMAGE_MODE_LARGE_VERTICAL".equals(daily.getImageMode())|| "TOUTIAO_SEARCH_AD_IMAGE".equals(daily.getImageMode())|| "SEARCH_AD_SMALL_IMAGE".equals(daily.getImageMode())|| "CREATIVE_IMAGE_MODE_UNION_SPLASH".equals(daily.getImageMode())){
                        bytedanceReportImageDailyList.add(daily);
                    }
                }
            }
            if(!bytedanceReportMaterialDailyList.isEmpty()){
                bytedanceReportMaterialDailyMapper.replaceIntoBatch(bytedanceReportMaterialDailyList);
            }
            if(!bytedanceReportImageDailyList.isEmpty()){
                bytedanceReportMaterialDailyMapper.replaceImageBatch(bytedanceReportImageDailyList);
            }
            if (currentPage >= totalPage) {
                log.info("头条素材报表当前accountId为：{}  {}~{}，接口数据拉取成功" , accountId, startDate,endDate);
                return 1;
            } else {
                int pageCode = bytedanceMaterialReportByPage(page + 1, pageSize, token, accountId, startDate, endDate);
                return pageCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("头条报表其他错误，accountId:" + accountId + "，json：" + JSONObject.toJSONString(data));
            returnCode = -3;
        }
        return returnCode;
    }

    @Override
    public List<BytedanceReportMaterialRetry> getRetryList() {
        return bytedanceReportMaterialDailyMapper.getRetryList();
    }


    /**
     * 头条视频素材报表
     * @param token
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public int bytedanceVideoMaterialReport(CtopOauthToken token, String startDate, String endDate) {
        Long accountId = token.getAccountId();
        log.info("头条素材报表当前accountId为：{}  {}~{},开始" , accountId, startDate,endDate);
        Integer page = 1;
        Integer pageSize = 100;
        int code = bytedanceVideoMaterialReportByPage(page, pageSize, token, accountId, startDate, endDate);
        if (code != 200 && code != 1) {
            BytedanceReportMaterialRetry retry = new BytedanceReportMaterialRetry();
            retry.setAccountId(accountId);
            retry.setStatus(0);
            retry.setStartDate(startDate);
            retry.setEndDate(endDate);
            retry.setStatusCode(code);
            retry.setType(2);  //1素材报表重试，2视频素材报表重试
            bytedanceReportMaterialDailyMapper.replaceMaterialRetry(retry);
        }
        log.info("头条素材报表当前accountId为：{}  {}~{}，结束" , accountId, startDate,endDate);
        return code;
    }

    private int bytedanceVideoMaterialReportByPage(Integer page, Integer pageSize, CtopOauthToken token, Long accountId, String startDate, String endDate) {
        // 请求地址
        String url = "https://ad.oceanengine.com/open_api/2/report/video/get/";
        // 请求参数
        Map data = new HashMap();
        data.put("advertiser_id", accountId);
        data.put("start_date", startDate);
        data.put("end_date", endDate);
        data.put("page", page);
        data.put("page_size", pageSize);
        data.put("group_by", new String[]{"STAT_GROUP_BY_MATERIAL_ID", "STAT_GROUP_BY_TIME_DAY"});

        JSONObject json = HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, JSONObject.parseObject(JSONObject.toJSONString(data)));
        if (json == null) {
            log.error("返回为空，请求有误:" + JSONObject.toJSONString(data));
            return -2;
        }

        try {
            Integer code = json.getInteger("code");
            if (code != 0) {
                log.error("获取任务列表返回信息错误，错误码为：" + code + ",头条accountId:" + accountId + ";返回json为：" + json + "请求为：" + JSONObject.toJSONString(data));
                return -1;
            }
            JSONObject jsonData = json.getJSONObject("data");
            if (Check.isNull(jsonData)) {
                log.error("获取任务列表返回信息data内容为空,头条accountId:" + accountId + ";返回json为：" + json + "请求为：" + JSONObject.toJSONString(data));
                return -1;
            }
            JSONObject pageInfo = jsonData.getJSONObject("page_info");
            Integer totalPage = pageInfo.getInteger("total_page");
            Integer currentPage = pageInfo.getInteger("page");
            JSONArray jsonArrayay = jsonData.getJSONArray("list");
            if (jsonArrayay.size() == 0) {
                log.info("accountId:" + accountId + "；没有数据。总页数为：" + totalPage + "当前页数为：" + currentPage);
                return 1;
            }
            List<BytedanceReportVideoMaterialDaily> bytedanceReportVideoMaterialDailyList = new ArrayList<>();
            for (int i = 0; i < jsonArrayay.size(); i++) {
                JSONObject detailJson = jsonArrayay.getJSONObject(i);
                if (!Check.isNull(detailJson)) {
                    BytedanceReportVideoMaterialDaily daily = new BytedanceReportVideoMaterialDaily(detailJson, accountId);
                    bytedanceReportVideoMaterialDailyList.add(daily);
                }
            }
            bytedanceReportMaterialDailyMapper.replaceIntoVideoMaterialBatch(bytedanceReportVideoMaterialDailyList);
            if (currentPage >= totalPage) {
                log.info("头条视频素材报表当前accountId为：{}  {}~{}，接口数据拉取成功" , accountId, startDate,endDate);
                return 1;
            } else {
                return bytedanceVideoMaterialReportByPage(page + 1, pageSize, token, accountId, startDate, endDate);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("头条视频素材报表其他错误，accountId:" + accountId + "，json：" + json + "请求为：" + JSONObject.toJSONString(data));
            return  -3;
        }
    }

}
