package cn.com.ctop.toutiao.modules.report.service.impl;

import cn.com.ctop.common.module.entity.*;
import cn.com.ctop.common.module.enums.BytedanceConvertType;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
import cn.com.ctop.common.module.service.*;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.common.module.vo.ByteDanceAdvertiserReportDTO;
import cn.com.ctop.toutiao.modules.material.entity.ByteDanceAdvertisePlan;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceAdvertiserDataService;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceCreativeService;
import cn.com.ctop.toutiao.modules.report.entity.*;
import cn.com.ctop.toutiao.modules.report.mapper.BytedanceReportMaterialDailyMapper;
import cn.com.ctop.toutiao.modules.report.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.jeecg.common.util.DateUtils;
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 javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 宋英豪
 */
@Slf4j
@Service
@Primary

public class ReportServiceImpl implements IReportService {
    @Value("${jeecg.path.csv-upload}")
    private String csvUploadPath;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IBytedanceAdvertiserDailyReportService advertiserDailyReportService;
    @Autowired
    private IBytedanceAdvertiserHourlyReportService advertiserHourlyReportService;
    @Autowired
    private IBytedanceCampaignDailyReportService campaignDailyReportService;
    @Autowired
    private IBytedanceCampaignHourlyReportService campaignHourlyReportService;
    @Autowired
    private IBytedancePlanDailyReportService planDailyReportService;
    @Autowired
    private IBytedancePlanHourlyReportService planHourlyReportService;
    @Autowired
    private IBytedanceCreativeDailyReportService creativeDailyReportService;
    @Autowired
    private IBytedanceCreativeHourlyReportService creativeHourlyReportService;
    @Resource
    private BytedanceReportMaterialDailyMapper materialDailyMapper;
    @Autowired
    private IBytedanceReportService bytedanceReportService;
    @Autowired
    private IByteDanceVideoReportDailyService byteDanceVideoReportDailyService;
    @Autowired
    private IByteDanceAdvertiserDataService advertiserDataService;
    @Autowired
    private IBytedanceInterfaceService bytedanceInterfaceService;
    @Resource
    private UserAllocationMapper allocationMapper;

    @Override
    public void getAdvertiserReport(CtopOauthToken token, Date startDate, Date endDate, String bytedanceReportTypePl) {
        var conditions = getReportDTO(token, startDate, endDate, bytedanceReportTypePl);
        getAdvertiserReportByPage(token, conditions, 1);
    }

    private void getAdvertiserReportByPage(CtopOauthToken token, ByteDanceAdvertiserReportDTO conditions, Integer page) {
        conditions.setPage(page);
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(conditions, config));
        JSONObject getObject = getAdvertiserStat(token, jsonObject);
        if(null == getObject){
            XxlJobHelper.log("头条广告主数据获取异常");
            return;
        }
        Integer code = getObject.getInteger("code");
        String message = getObject.getString("message");
        if (null == code || code != 0) {
            XxlJobHelper.log("头条广告主数据获取异常：{}", message);
            return;
        }
        JSONArray dataArray = getObject.getJSONObject("data").getJSONArray("list");
        if (null == dataArray || dataArray.isEmpty()) {
            return;
        }

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject data = dataArray.getJSONObject(i);
            if (null != conditions.getTimeGranularity() && conditions.getTimeGranularity().equals(CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY)) {
                BytedanceAdvertiserHourlyReport hourlyReport = new BytedanceAdvertiserHourlyReport(data);
                advertiserHourlyReportService.saveOrUpdate(hourlyReport);
            } else {
                BytedanceAdvertiserDailyReport dailyReport = new BytedanceAdvertiserDailyReport(data);
                advertiserDailyReportService.saveOrUpdate(dailyReport);
            }
        }
    }

    @Override
    public void getAdvertiserCampaignReport(CtopOauthToken token, Date startDate, Date endDate, String bytedanceReportTypePl) {
        var conditions = getReportDTO(token, startDate, endDate, bytedanceReportTypePl);
        getCampaignReportByPage(token, conditions, 1);
    }

    private void getCampaignReportByPage(CtopOauthToken token, ByteDanceAdvertiserReportDTO conditions, int page) {
        conditions.setPage(page);
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(conditions, config));
        JSONObject getObject = getCampaignStat(token, jsonObject);
        Integer code = getObject.getInteger("code");
        String message = getObject.getString("message");
        if (null == code || code != 0) {
            log.error("广告组报表数据获取异常：{}", message);
            return;
        }
        JSONArray dataArray = getObject.getJSONObject("data").getJSONArray("list");
        if (null == dataArray || dataArray.isEmpty()) {
            log.info("广告组报表信息为空=》accountId:{}", token.getAccountId());
            return;
        }
        for (var i = 0; i < dataArray.size(); i++) {
            var data = dataArray.getJSONObject(i);
            if (null != conditions.getTimeGranularity() && CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY.equals(conditions.getTimeGranularity())) {
                var hourlyReport = new BytedanceCampaignHourlyReport(data, token.getAccountId());
                campaignHourlyReportService.saveOrUpdate(hourlyReport);
            } else {
                var dailyReport = new BytedanceCampaignDailyReport(data, token.getAccountId());
                campaignDailyReportService.saveOrUpdate(dailyReport);
            }
        }
        getCampaignReportByPage(token, conditions, page + 1);
    }


    @Override
    public void getAdvertiserPlanReport(CtopOauthToken token, Date startDate, Date endDate, String bytedanceReportTypePl) {
        var conditions = getReportDTO(token, startDate, endDate, bytedanceReportTypePl);
        getPlanReportByPage(token, conditions, 1);
    }

    @Override
    public void getAdvertiserPlanRuleData(CtopOauthToken token, Date startDate, Date endDate, String bytedanceReportTypePl) {
        var conditions = getReportDTO(token, startDate, endDate, bytedanceReportTypePl);
        getPlanRuleDataByPage(token, conditions, 1);
    }

    private void getPlanRuleDataByPage(CtopOauthToken token, ByteDanceAdvertiserReportDTO conditions, int page) {
        conditions.setPage(page);
        var config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        var jsonObject = JSONObject.parseObject(JSON.toJSONString(conditions, config));

        JSONObject getObject = getAdStat(token, jsonObject);
        if (null == getObject) {
            log.error("广告计划报表数据获取异常=》account：{}；message:{}", token.getAccountId(), "返回数据异常");
            return;
        }
        Integer code = getObject.getInteger("code");
        var message = getObject.getString("message");
        if (null == code || code != 0) {
            log.error("广告计划报表数据获取异常=》account：{}；message:{}", token.getAccountId(), message);
            return;
        }
        var dataArray = getObject.getJSONObject("data").getJSONArray("list");
        if (null == dataArray || dataArray.size() <= 0) {
            return;
        }
        UserAllocation allocation = userAllocationService.getByAccountId(token.getAccountId());
        for (var i = 0; i < dataArray.size(); i++) {
            var data = dataArray.getJSONObject(i);
            var ruleDataPlan = new RuleDataPlan(data, token.getAccountId());
            ruleDataPlan.setAccountName(allocation.getAuthName());
            ByteDanceAdvertisePlan plan = advertiserDataService.getSinglePlanById(token,ruleDataPlan.getId()+"");
            if(null!=plan){
                String status = plan.getToutiaoStatus();
                String optStatus = plan.getOptStatus();
                if(null == optStatus|| "AD_STATUS_DISABLE".equals(optStatus)|| "".equals(optStatus.trim())){
                    continue;
                }
                if(null == status|| "".equals(status.trim())|| "AD_STATUS_DISABLE".equals(status)
                        || "AD_STATUS_DONE".equals(status)|| "AD_STATUS_AUDIT_DENY".equals(status)|| "AD_STATUS_BALANCE_EXCEED".equals(status)
                        || "AD_STATUS_CAMPAIGN_DISABLE".equals(status)|| "AD_STATUS_CAMPAIGN_EXCEED".equals(status)|| "AD_STATUS_DELETE".equals(status)){
                    continue;
                }
                ruleDataPlan.setBudget(plan.getBudget());
                ruleDataPlan.setDownloadUrl(plan.getDownloadUrl());
                ruleDataPlan.setExternalUrl(plan.getExternalUrl());
                ruleDataPlan.setPricing(plan.getPricing());
                ruleDataPlan.setCpaBid(plan.getCpaBid());
                ruleDataPlan.setDeepCpabid(plan.getDeepCpaBid());
                Long convertId = plan.getConvertId();
                if(null!=convertId&&convertId!=0){
                    ruleDataPlan.setConvertId(plan.getConvertId());
                    JSONObject convertTargetObject = readAdConvert(token,plan.getConvertId());
                    if(null != convertTargetObject){
                        ruleDataPlan.setConvertId(BytedanceConvertType.getNum(convertTargetObject.getString("convert_type")));
                        ruleDataPlan.setDeepConvertTarget(convertTargetObject.getString("deep_external_action"));
                    }
                }
                RuleDataTarget target = new RuleDataTarget();
                JSONObject audienceObject = JSONObject.parseObject(plan.getAudience());
                target.setAccountId(token.getAccountId());
                target.setAccountName(allocation.getAuthName());
                target.setDeepBidType(plan.getDeepBidType());
                target.setPlanId(ruleDataPlan.getPlanId());
                target.setId(ruleDataPlan.getPlanId());
                target.setCreateTime(new Date());
                target.setUpdateTime(new Date());
                if(null!=audienceObject.getString("retargeting_tags_exclude")){
                    target.setRetargetingTagsExclude(audienceObject.getString("retargeting_tags_exclude"));
                }
                if(null!=audienceObject.getString("retargeting_tags_include")){
                    target.setRetargetingTagsExclude(audienceObject.getString("retargeting_tags_include"));
                }
                if(null!=audienceObject.getString("retargeting_tags_include")){
                    target.setRetargetingTagsInclude(audienceObject.getString("retargeting_tags_include"));
                }
                target.setHideIfConverted(plan.getHideIfConverted());
                target.setHideIfExists(plan.getHideIfExists());

                //target.setInventoryType(plan.getInventoryType());
                if(null!=audienceObject.getString("city")){
                    target.setDistrict(audienceObject.getString("city"));
                }
                if(null!=audienceObject.getString("gender")){
                    target.setGender(audienceObject.getString("gender"));
                }
                if(null!=audienceObject.getString("age")){
                    target.setAge(audienceObject.getString("age"));
                }
                if(null!=audienceObject.getString("exclude_flow_package")){
                    target.setExcludeFlowPackage(audienceObject.getString("exclude_flow_package"));
                }
//		this.flowPackage = audience.getString("flow_package");
                if(null!=audienceObject.getString("platform")){
                    target.setPlatform(audienceObject.getString("platform"));
                }
                target.setDeepBidType(plan.getDeepBidType());
                target.setScheduleTime(plan.getScheduleTime());

                ruleDataTargetService.saveOrUpdate(target);
                Map<String, Object> creativeDetail = creativeService.getCreativeDetail(token, plan.getId());
                if(null!=creativeDetail.get("data")){
                    JSONObject detail = (JSONObject) creativeDetail.get("data");
                    formatCreativeData(detail,allocation,ruleDataPlan);
                }
            }
            ruleDataPlanService.saveOrUpdate(ruleDataPlan);
        }
        getPlanRuleDataByPage(token, conditions, page + 1);
    }

    private void formatCreativeData(JSONObject detail, UserAllocation allocation, RuleDataPlan plan) {
        //广告来源
        String source = detail.getString("source");
        Integer isPresentedVideo = detail.getInteger("isPresentedVideo");
        JSONArray creatives = detail.getJSONArray("creatives");
        if(null!=creatives&&!creatives.isEmpty()){
            for(int i=0;i<creatives.size();i++){
                JSONObject data = creatives.getJSONObject(i);
                Long creativeId = data.getLong("creative_id");
                if(null!=creativeId){
                    String title = data.getString("title");
                    RuleDataCreative dataCreative = new RuleDataCreative();
                    dataCreative.setId(creativeId);
                    dataCreative.setCreativeId(creativeId);
                    dataCreative.setCreativeTitle(title);
                    dataCreative.setPlanId(plan.getId());
                    dataCreative.setPlanName(plan.getPlanName());
                    dataCreative.setAccountId(allocation.getAccountId());
                    dataCreative.setAccountName(allocation.getAuthName());
                    dataCreative.setSource(source);
                    dataCreative.setPresentedVideo(isPresentedVideo);
                    dataCreative.setCreateTime(new Date());
                    dataCreative.setUpdateTime(new Date());
                    ruleDataCreativeService.saveOrUpdate(dataCreative);
                }
            }
        }
    }

    @Override
    public JSONObject readAdConvert(CtopOauthToken token, Long convertId) {
        String url = "https://ad.oceanengine.com/open_api/2/tools/ad_convert/read/";
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("convert_id", convertId);
        JSONObject result = HttpUtils.bytedanceGetRequest(token.getAccessToken(),url,params);
        Integer code = result.getInteger("code");
        String message = result.getString("message");
        if (null == code || code != 0) {
            log.error("获取转化数据异常=》account：{}；convertId：{}；message:{}", token.getAccountId(), convertId,message);
            return  null;
        }
        return result.getJSONObject("data");
    }


    @Autowired
    private IByteDanceCreativeService creativeService;
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private IRuleDataPlanService ruleDataPlanService;
    @Autowired
    private IRuleDataTargetService ruleDataTargetService;
    @Autowired
    private IRuleDataCreativeService ruleDataCreativeService;

    private void getPlanReportByPage(CtopOauthToken token, ByteDanceAdvertiserReportDTO conditions, int page) {
        conditions.setPage(page);
        var config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        var jsonObject = JSONObject.parseObject(JSON.toJSONString(conditions, config));

        JSONObject getObject = getAdStat(token, jsonObject);
        if (null == getObject) {
            log.error("广告计划报表数据获取异常=》account：{}；message:{}", token.getAccountId(), "返回数据异常");
            return;
        }
        Integer code = getObject.getInteger("code");
        var message = getObject.getString("message");
        if (null == code || code != 0) {
            log.error("广告计划报表数据获取异常=》account：{}；message:{}", token.getAccountId(), message);
            return;
        }
        var dataArray = getObject.getJSONObject("data").getJSONArray("list");
        if (null == dataArray || dataArray.size() <= 0) {
            return;
        }
        List<BytedancePlanHourlyReport> hourlyReports = new ArrayList<>();
        List<BytedancePlanDailyReport> dailyReports = new ArrayList<>();
        for (var i = 0; i < dataArray.size(); i++) {
            var data = dataArray.getJSONObject(i);
            if (null != conditions.getTimeGranularity() && CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY.equals(conditions.getTimeGranularity())) {
                var hourlyReport = new BytedancePlanHourlyReport(data, token.getAccountId());
                String adName = hourlyReport.getAdName();
                String[] tags = adName.split("-");
                hourlyReport.setChannelCode(tags[0]);
                hourlyReports.add(hourlyReport);
            } else {
                var dailyReport = new BytedancePlanDailyReport(data, token.getAccountId());
                //获取计划详情
                dailyReports.add(dailyReport);
            }
        }

        if (null != conditions.getTimeGranularity() && CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY.equals(conditions.getTimeGranularity())) {
            planHourlyReportService.replaceBatch(hourlyReports);
        } else {
            planDailyReportService.replaceBatch(dailyReports);
        }

        getPlanReportByPage(token, conditions, page + 1);
    }

    @Override
    public void getAdvertiserCreativeReport(CtopOauthToken token, Date startDate, Date endDate, String bytedanceReportTypePl) {
        var conditions = getReportDTO(token, startDate, endDate, bytedanceReportTypePl);
        getCreativeReportByPage(token, conditions, 1);
    }


    public JSONObject getMaterialReport(CtopOauthToken token, String startDate, String endDate, Integer pageNum) {
        // 请求地址
        String url = "https://ad.oceanengine.com/open_api/2/report/integrated/get/";
        // 请求参数
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("start_date", startDate);
        params.put("end_date", endDate);
        params.put("page", pageNum);
        params.put("page_size", 100);
        JSONArray groupBy = new JSONArray();
        groupBy.add("STAT_GROUP_BY_MATERIAL_ID");
        groupBy.add("STAT_GROUP_BY_TIME_DAY");
        groupBy.add("STAT_GROUP_BY_INVENTORY");
        groupBy.add("STAT_GROUP_BY_IMAGE_MODE");
        params.put("group_by", groupBy);
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, params);
    }

    @Autowired
    private IBytedanceReportMaterialRetryService retryService;

    @Override
    public void getMaterialReportByPage(CtopOauthToken token, String startDate, String endDate, Integer pageNum) {
        JSONObject getObject = getMaterialReport(token, startDate, endDate, pageNum);
        if (null == getObject) {
            BytedanceReportMaterialRetry reportMaterialRetry = new BytedanceReportMaterialRetry();
            reportMaterialRetry.setAccountId(token.getAccountId());
            reportMaterialRetry.setStartDate(startDate);
            reportMaterialRetry.setStartDate(endDate);
            reportMaterialRetry.setStatus(0);
            retryService.save(reportMaterialRetry);
            log.error("素材报表请求数据null=>accountId:{};startDate:{};endDate:{}", token.getAccountId(), startDate, endDate);
            return;
        }

        Integer code = getObject.getInteger("code");
        String message = getObject.getString("message");
        if (null == code || code != 0) {
            log.error("素材报表数据获取异常：{}", message);
            return;
        }
        JSONArray dataArray = getObject.getJSONObject("data").getJSONArray("list");
        if (null == dataArray || dataArray.size() <= 0) {
            return;
        }
        List<BytedanceReportMaterialDaily> dailyReports = new ArrayList<>();
        for (var i = 0; i < dataArray.size(); i++) {
            var data = dataArray.getJSONObject(i);
            var dailyReport = new BytedanceReportMaterialDaily(data, token.getAccountId());
            dailyReports.add(dailyReport);
        }
        materialDailyMapper.replaceIntoBatch(dailyReports);
        Integer totalNum = getObject.getJSONObject("data").getJSONObject("page_info").getInteger("total_page");
        if (null != totalNum && totalNum > pageNum) {
            getMaterialReportByPage(token, startDate, endDate, pageNum + 1);
        }
    }


    @Override
    public void loadBytedanceHistoryData(CtopOauthToken token) {
        try {
            String beginDateStr = allocationMapper.getUserAllocation(token.getAccountId()).getAuthBeginTime();
            beginDateStr = Check.isNull(beginDateStr) ? DateUtils.formatDate(DateUtils.addDay(new Date(),-180),"yyyy-MM-dd") : beginDateStr;
            Date beginDate = DateUtils.parseDate(beginDateStr,DateUtils.WEB_FORMAT);
            Date endDate2 = DateUtils.addDay(new Date(),-1);
            while (!beginDate.after(endDate2)){
                beginDate = DateUtils.addDay(beginDate,1);
    //        for (int i = 1; i < 180; i++) {
    //            Date getDate = DateUtils.addDay(new Date(),1);
                this.getAdvertiserCreativeReport(token, beginDate, beginDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
                this.getAdvertiserPlanReport(token, beginDate, beginDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
                this.getAdvertiserReport(token, beginDate, beginDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
    //        }

            }


            advertiserDataService.getMaterialList(token);
            log.info("获取历史素材报表：accountId：{}", token.getAccountId());
//            String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
//            String endDate = DateUtils.addDay(nowDate, -180);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            Date end = simpleDateFormat.parse(nowDate);
//            Date start = simpleDateFormat.parse(endDate);
//            List<Date> dates = DateUtils.findDates(start, end);

            beginDate = DateUtils.parseDate(beginDateStr,DateUtils.WEB_FORMAT);
            while (!beginDate.after(endDate2)){
                beginDate = DateUtils.addDay(beginDate,1);
                String formatDate = simpleDateFormat.format(beginDate);
                //试玩报表
                bytedanceInterfaceService.bytedancePlayableReport(token,formatDate,formatDate);
                //
                //素材报表
                int code = bytedanceReportService.bytedanceMaterialReport(token, formatDate, formatDate);
                //如果成功的话跑视频清洗数据方法，失败会进入重试库，重试成功后再清洗数据
                if (code == 200 || code == 1) {
                    byteDanceVideoReportDailyService.videoInfoListByAccountId(formatDate, formatDate, token.getAccountId());
                }

            }
//            for (int i = 0; i < dates.size(); i++) {
//                String formatDate = simpleDateFormat.format(dates.get(i));
//                //试玩报表
//                bytedanceInterfaceService.bytedancePlayableReport(token,formatDate,formatDate);
//                //
//                //素材报表
//                int code = bytedanceReportService.bytedanceMaterialReport(token, formatDate, formatDate);
//                //如果成功的话跑视频清洗数据方法，失败会进入重试库，重试成功后再清洗数据
//                if (code == 200 || code == 1) {
//                    byteDanceVideoReportDailyService.videoInfoListByAccountId(formatDate, formatDate, token.getAccountId());
//                }
//
//                //
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getAdvertiserReport(BytedanceAccountReportTaskRecord record, String bytedanceReportTypeDaily) {
        CtopOauthToken token  = tokenService.getTokenByAccountId(record.getAccountId());
        if(null==token){
            return;
        }
        var conditions = getTaskReportDTO(token, record.getStartDate(), record.getEndDate(), bytedanceReportTypeDaily);
        getAdvertiserReportByPageV2(token, conditions,record);
    }

    @Autowired
    private IBytedanceAccountReportTaskRecordService recordService;

    private void getAdvertiserReportByPageV2(CtopOauthToken token, ByteDanceAdvertiserReportDTO conditions,BytedanceAccountReportTaskRecord record) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(conditions, config));
        JSONObject getObject = getAdvertiserStat(token, jsonObject);
        if(null == getObject){
            XxlJobHelper.log("头条广告主数据获取异常");
            return;
        }
        Integer code = getObject.getInteger("code");
        String message = getObject.getString("message");
        if (null == code || code != 0) {
            XxlJobHelper.log("头条广告主数据获取异常：{}", message);
            return;
        }
        JSONArray dataArray = getObject.getJSONObject("data").getJSONArray("list");
        if (null == dataArray || dataArray.isEmpty()) {
            record.setStatus(100);
            record.setUpdateTime(new Date());
            recordService.updateById(record);
            return;
        }

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject data = dataArray.getJSONObject(i);
            if (null != conditions.getTimeGranularity() && conditions.getTimeGranularity().equals(CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY)) {
                BytedanceAdvertiserHourlyReport hourlyReport = new BytedanceAdvertiserHourlyReport(data);
                advertiserHourlyReportService.saveOrUpdate(hourlyReport);
            } else {
                BytedanceAdvertiserDailyReport dailyReport = new BytedanceAdvertiserDailyReport(data);
                advertiserDailyReportService.saveOrUpdate(dailyReport);
            }
        }
        record.setStatus(100);
        record.setUpdateTime(new Date());
        recordService.updateById(record);
    }

    private ByteDanceAdvertiserReportDTO getReportDTO(CtopOauthToken token, Date startDate, Date endDate, String bytedanceReportTypePl) {
        var conditions = new ByteDanceAdvertiserReportDTO();
        conditions.setAdvertiserId(token.getAccountId());
        conditions.setStartDate(DateUtils.formatDate(startDate));
        conditions.setEndDate(DateUtils.formatDate(endDate));
        conditions.setPageSize(1000);
        conditions.setTimeGranularity(bytedanceReportTypePl);
        return conditions;
    }

    private ByteDanceAdvertiserReportDTO getTaskReportDTO(CtopOauthToken token, String startDate, String endDate, String bytedanceReportTypePl) {
        var conditions = new ByteDanceAdvertiserReportDTO();
        conditions.setAdvertiserId(token.getAccountId());
        conditions.setStartDate(startDate);
        conditions.setEndDate(endDate);
        conditions.setPageSize(1000);
        conditions.setPage(1);
        conditions.setTimeGranularity(bytedanceReportTypePl);
        return conditions;
    }


    private void getCreativeReportByPage(CtopOauthToken token, ByteDanceAdvertiserReportDTO conditions, int page) {
        conditions.setPage(page);
        var config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        var jsonObject = JSONObject.parseObject(JSON.toJSONString(conditions, config));
        var getObject = getCreativeStat(token, jsonObject);
        var code = getObject.getInteger("code");
        var message = getObject.getString("message");
        if (null == code || code != 0) {
            log.error("广告创意报表数据获取异常：{}", message);
            return;
        }
        JSONArray dataArray = getObject.getJSONObject("data").getJSONArray("list");
        if (null == dataArray || dataArray.size() <= 0) {
            return;
        }
        List<BytedanceCreativeHourlyReport> hourlyReports = new ArrayList<>();
        List<BytedanceCreativeDailyReport> dailyReports = new ArrayList<>();
        for (var i = 0; i < dataArray.size(); i++) {
            var data = dataArray.getJSONObject(i);
            if (null != conditions.getTimeGranularity() && CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY.equals(conditions.getTimeGranularity())) {
                var hourlyReport = new BytedanceCreativeHourlyReport(data, token.getAccountId());
                hourlyReports.add(hourlyReport);
            } else {
                var dailyReport = new BytedanceCreativeDailyReport(data, token.getAccountId());
                Long creativeId = dailyReport.getCreativeId();
                String signature = creativeHourlyReportService.getSignatureByCreativeId(creativeId);
                if (!Check.isNull(signature)) {
                    dailyReport.setSignature(signature);
                }
                dailyReports.add(dailyReport);
            }
        }

        if (null != conditions.getTimeGranularity() && CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY.equals(conditions.getTimeGranularity())) {
            creativeHourlyReportService.replaceBatch(hourlyReports);
        } else {
            creativeDailyReportService.replaceBatch(dailyReports);
        }
        getCreativeReportByPage(token, conditions, page + 1);
    }

    @Override
    public Map<String, Object> getAgentReport(JSONObject conditions) {
        Long accountId = conditions.getLong("accountId");
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId + "");
        JSONObject getObject = getCreativeStat(token, conditions);
        return getObject;
    }

    /**
     * 获取广告创意报表信息
     *
     * @param token
     * @param conditions
     * @return
     */
    public JSONObject getCreativeStat(CtopOauthToken token, JSONObject conditions) {
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_creative_get");
        JSONArray groupBy = new JSONArray();
        groupBy.add("STAT_GROUP_BY_FIELD_ID");
        groupBy.add("STAT_GROUP_BY_FIELD_STAT_TIME");
        conditions.put("group_by", groupBy);
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, conditions);
    }

    /**
     * 获取广告计划报表信息
     *
     * @param token
     * @param conditions
     * @return
     */
    private JSONObject getAdStat(CtopOauthToken token, JSONObject conditions) {
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_report_get");
        JSONArray groupBy = new JSONArray();
        groupBy.add("STAT_GROUP_BY_FIELD_ID");
        groupBy.add("STAT_GROUP_BY_FIELD_STAT_TIME");


        JSONObject status = new JSONObject();
        status.put("status","AD_STATUS_ALL");


        conditions.put("filtering",status);
        conditions.put("group_by", groupBy);
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, conditions);
    }

    /**
     * 获取广告组报表信息
     *
     * @param token
     * @param conditions
     * @return
     */
    public JSONObject getCampaignStat(CtopOauthToken token, JSONObject conditions) {
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_report_get");
        JSONArray groupBy = new JSONArray();
        groupBy.add("STAT_GROUP_BY_FIELD_ID");
        groupBy.add("STAT_GROUP_BY_FIELD_STAT_TIME");
        conditions.put("group_by", groupBy);
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, conditions);
    }

    /**
     * 获取广告主报表信息
     *
     * @param token
     * @param conditions
     * @return
     */
    public JSONObject getAdvertiserStat(CtopOauthToken token, JSONObject conditions) {
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_advertiser_report_get");
        JSONArray groupBy = new JSONArray();
        groupBy.add("STAT_GROUP_BY_FIELD_ID");
        groupBy.add("STAT_GROUP_BY_FIELD_STAT_TIME");
        conditions.put("group_by", groupBy);
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, conditions);
    }
}
