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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.toutiao.modules.report.entity.*;
import cn.com.ctop.toutiao.modules.report.mapper.BytedanceMatReportTaskCheckInfoMapper;
import cn.com.ctop.toutiao.modules.report.mapper.BytedanceReportMapper;
import cn.com.ctop.toutiao.modules.report.mapper.BytedanceReportMaterialDailyMapper;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceAccountReportTaskRecordService;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceReportService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service
@Slf4j
public class BytedanceReportServiceImpl implements IBytedanceReportService {
    @Value("${jeecg.path.report-history}")
    private String downloadPath;
    @Autowired
    private BytedanceReportMapper reportMapper;
    @Autowired
    private BytedanceReportMaterialDailyMapper bytedanceReportMaterialDailyMapper;

    /**
     * 快手-大盘报表
     *
     * @param requestJson
     * @return
     */
    @Override
    public JSONObject getKuaiShouAccountReport(JSONObject requestJson) {
        Integer type = requestJson.getInteger("type");
        JSONObject accountJson = new JSONObject();
        try {
            String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
            String anotherDay = DateUtils.getAnotherDay("yyyy-MM-dd", nowDate, -1);
            if (type == 1) {
                // 今日总消耗
                JSONObject nowJson = reportMapper.selectDayReport(nowDate);
                if (Check.isNull(nowJson)) {
                    return accountJson;
                }
                int maxHour = nowJson.getInteger("maxHour");
                if (maxHour == 0 || Check.isNull(maxHour)) {
                    return accountJson;
                }
                String maxHourStr = String.valueOf(maxHour - 1);
                accountJson = reportMapper.selectSumDayHourlyByHourAndDate(nowDate, maxHourStr);
                accountJson.put("maxHour", maxHour);
                if (!Check.isNull(accountJson)) {
                    JSONObject yesterdayJson = reportMapper.selectSumDayHourlyByHourAndDate(anotherDay, maxHourStr);
                    if (!Check.isNull(yesterdayJson)) {
                        // 今日消耗
                        BigDecimal cost = accountJson.getBigDecimal("cost");
                        // 昨日消耗
                        BigDecimal yesterdayCost = yesterdayJson.getBigDecimal("cost");
                        BigDecimal compareBigDecimal = new BigDecimal(0);
                        // 较昨日增加比例
                        if (yesterdayCost.compareTo(compareBigDecimal) != 0) {
                            BigDecimal costProportion = (cost.subtract(yesterdayCost)).divide(yesterdayCost, 2, RoundingMode.HALF_UP);
                            accountJson.put("costProportion", costProportion);
                        } else {
                            accountJson.put("costProportion", 0);
                        }


                        // 今日封面展示
                        Long photoShow = accountJson.getLong("photoShow");
                        // 昨日封面展示
                        Long yesterdayPhotoShow = yesterdayJson.getLong("photoShow");
                        // 较昨日增加比例
                        if (yesterdayPhotoShow != 0L) {
                            double showProportion = (photoShow.doubleValue() - yesterdayPhotoShow.doubleValue()) / yesterdayPhotoShow.doubleValue();
                            accountJson.put("showProportion", showProportion);
                        } else {
                            accountJson.put("showProportion", 0);
                        }

                        // 今日封面展示
                        Long photoClick = accountJson.getLong("photoClick");
                        // 昨日封面展示
                        Long yesterdayPhotoClick = yesterdayJson.getLong("photoClick");
                        // 较昨日增加比例
                        if (yesterdayPhotoClick != 0L) {
                            double photoClickProportion = (photoClick.doubleValue() - yesterdayPhotoClick.doubleValue()) / yesterdayPhotoClick.doubleValue();
                            accountJson.put("photoClickProportion", photoClickProportion);
                        } else {
                            accountJson.put("photoClickProportion", 0);
                        }

                        Long aClick = accountJson.getLong("aclick");
                        Long yesterdayAClick = yesterdayJson.getLong("aclick");
                        // 较昨日增加比例
                        if (yesterdayAClick != 0L) {
                            double aClickProportion = (aClick.doubleValue() - yesterdayAClick.doubleValue()) / yesterdayAClick.doubleValue();
                            accountJson.put("aClickProportion", aClickProportion);
                        } else {
                            accountJson.put("aClickProportion", 0);
                        }
                    }
                }
            } else if (type == 2) {
                accountJson = reportMapper.selectDayReport(anotherDay);
            } else if (type == 3) {
                String endDate = DateUtils.getAnotherDay("yyyy-MM-dd", anotherDay, -6);
                accountJson = reportMapper.selectByDate(anotherDay, endDate);
            } else if (type == 4) {
                String endDate = DateUtils.getAnotherDay("yyyy-MM-dd", anotherDay, -14);
                accountJson = reportMapper.selectByDate(anotherDay, endDate);
            } else if (type == 5) {
                String endDate = DateUtils.getMonthBefore("yyyy-MM-dd", anotherDay, -1);
                accountJson = reportMapper.selectByDate(anotherDay, endDate);
            } else if (type == 6) {
                String endDate = DateUtils.getMonthBefore("yyyy-MM-dd", anotherDay, -3);
                accountJson = reportMapper.selectByDate(anotherDay, endDate);
            } else if (type == 7) {
                String endDate = DateUtils.getMonthBefore("yyyy-MM-dd", anotherDay, -6);
                accountJson = reportMapper.selectByDate(anotherDay, endDate);
            } else if (type == 8) {
                accountJson = reportMapper.selectAllAccount();
            } else if (type == 9) {
                String startDate = requestJson.getString("startDate");
                String endDate = requestJson.getString("endDate");
                accountJson = reportMapper.selectByDate(startDate, endDate);
            } else if (type == 10) {
                String sign = requestJson.getString("sign");
                String bigDate = requestJson.getString("bigDate");
                String smallDate = requestJson.getString("smallDate");
                JSONObject beComparedJson = new JSONObject();
                JSONObject comparedJson = new JSONObject();

                if ("month".equals(sign)) {
                    Map<String, Object> dateMap = DateUtils.compareDate("yyyy-MM", bigDate, smallDate);
                    beComparedJson = reportMapper.selectMonthReportByDate((String) dateMap.get("smallDate"));
                    comparedJson = reportMapper.selectMonthReportByDate((String) dateMap.get("bigDate"));
                } else if ("day".equals(sign)) {
                    Map<String, Object> dateMap = DateUtils.compareDate("yyyy-MM-dd", bigDate, smallDate);
                    beComparedJson = reportMapper.selectDayReportByDate((String) dateMap.get("smallDate"));
                    comparedJson = reportMapper.selectDayReportByDate((String) dateMap.get("bigDate"));
                }

                if (!Check.isNull(comparedJson)) {
                    BigDecimal cost = comparedJson.getBigDecimal("cost");
                    BigDecimal comparedCost = beComparedJson.getBigDecimal("cost");
                    if (comparedCost.compareTo(new BigDecimal(0)) != 0) {
                        BigDecimal costProportion = (cost.subtract(comparedCost)).divide(comparedCost, 2, RoundingMode.HALF_UP);
                        comparedJson.put("costProportion", costProportion);
                    } else {
                        comparedJson.put("costProportion", 0);
                    }

                    Long photoClick = comparedJson.getLong("photoClick");
                    Long comparedPhotoClick = beComparedJson.getLong("photoClick");
                    if (comparedPhotoClick != 0L) {
                        double photoClickProportion = (photoClick.doubleValue() - comparedPhotoClick.doubleValue()) / comparedPhotoClick.doubleValue();
                        comparedJson.put("photoClickProportion", photoClickProportion);
                    } else {
                        comparedJson.put("photoClickProportion", 0);
                    }

                    Long aClick = comparedJson.getLong("aclick");
                    Long comparedAClick = beComparedJson.getLong("aclick");
                    if (comparedAClick != 0L) {
                        double aClickProportion = (aClick.doubleValue() - comparedAClick.doubleValue()) / comparedAClick.doubleValue();
                        comparedJson.put("comparedAclick", aClickProportion);
                    } else {
                        comparedJson.put("comparedAclick", 0);
                    }
                    Long comparedPhotoShow = beComparedJson.getLong("photoShow");
                    Long photoShow = comparedJson.getLong("photoShow");
                    if (comparedPhotoShow != 0L) {
                        double showProportion = (photoShow.doubleValue() - comparedPhotoShow.doubleValue()) / comparedPhotoShow.doubleValue();
                        comparedJson.put("showProportion", showProportion);
                    } else {
                        comparedJson.put("showProportion", 0);
                    }
                }
                accountJson.put("beCompared", beComparedJson);
                accountJson.put("compared", comparedJson);

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

    @Override
    public List<JSONObject> getKuaiShouAccounDetailtReport(JSONObject requestJson) {
        Integer type = requestJson.getInteger("type");
        List<JSONObject> detail = new ArrayList<>();
        try {
            String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
            String anotherDay = DateUtils.getAnotherDay("yyyy-MM-dd", nowDate, -1);
            if (type == 1) {
                //  今日明细
                List<JSONObject> yesterdayDetail = reportMapper.selectReportDetail(anotherDay);
                for (int i = 0; i < yesterdayDetail.size(); i++) {

                    JSONObject yesterdayJson = yesterdayDetail.get(i);
                    if (!Check.isNull(yesterdayJson)) {
                        String yesterdayStatHour = yesterdayJson.getString("statHour");
                        JSONObject nowJson = reportMapper.selectDayHourlyByHourAndDate(nowDate, yesterdayStatHour);
                        if (!Check.isNull(nowJson)) {
                            nowJson.put("statDate", nowDate);
                            // 今日消耗
                            BigDecimal cost = nowJson.getBigDecimal("cost");
                            // 昨日消耗
                            BigDecimal yesterdayCost = yesterdayJson.getBigDecimal("cost");
                            BigDecimal compareBigDecimal = new BigDecimal(0);
                            // 较昨日增加比例
                            if (yesterdayCost.compareTo(compareBigDecimal) != 0) {
                                BigDecimal costProportion = ((cost.subtract(yesterdayCost))).divide(yesterdayCost, 2, RoundingMode.HALF_UP);
                                nowJson.put("costProportion", costProportion);
                            } else {
                                nowJson.put("costProportion", 0);
                            }

                            // 今日封面展示
                            Long photoShow = nowJson.getLong("photoShow");
                            // 昨日封面展示
                            Long yesterdayPhotoShow = yesterdayJson.getLong("photoShow");
                            // 较昨日增加比例
                            if (yesterdayPhotoShow != 0L) {
                                double showProportion = (photoShow.doubleValue() - yesterdayPhotoShow.doubleValue()) / yesterdayPhotoShow.doubleValue();
                                nowJson.put("showProportion", showProportion);
                            } else {
                                nowJson.put("showProportion", 0);
                            }

                            // 今日封面展示
                            Long photoClick = nowJson.getLong("photoClick");
                            // 昨日封面展示
                            Long yesterdayPhotoClick = yesterdayJson.getLong("photoClick");
                            // 较昨日增加比例
                            if (yesterdayPhotoClick != 0L) {
                                double photoClickProportion = (photoClick.doubleValue() - yesterdayPhotoClick.doubleValue()) / yesterdayPhotoClick.doubleValue();
                                nowJson.put("photoClickProportion", photoClickProportion);
                            } else {
                                nowJson.put("photoClickProportion", 0);
                            }

                            // 今日封面展示
                            Long aClick = nowJson.getLong("aclick");
                            // 昨日封面展示
                            Long yesterdayAClick = yesterdayJson.getLong("aclick");
                            // 较昨日增加比例
                            if (yesterdayAClick != 0L) {
                                double aClickProportion = (aClick.doubleValue() - yesterdayAClick.doubleValue()) / yesterdayAClick.doubleValue();
                                nowJson.put("aClickProportion", aClickProportion);
                            } else {
                                nowJson.put("aClickProportion", 0);
                            }
                            yesterdayJson.put("now", nowJson);
                        }
                    }
                    detail.add(yesterdayJson);
                }
            } else if (type == 2) {
                detail = reportMapper.selectReportDetail(anotherDay);
            } else if (type == 3) {
                String endDate = DateUtils.getAnotherDay("yyyy-MM-dd", anotherDay, -6);
                detail = reportMapper.selectDayDetailByDate(anotherDay, endDate);
            } else if (type == 4) {
                String endDate = DateUtils.getAnotherDay("yyyy-MM-dd", anotherDay, -14);
                detail = reportMapper.selectDayDetailByDate(anotherDay, endDate);
            } else if (type == 5) {
                String endDate = DateUtils.getMonthBefore("yyyy-MM-dd", anotherDay, -1);
                detail = reportMapper.selectDayDetailByDate(anotherDay, endDate);
            } else if (type == 6) {
                String endDate = DateUtils.getMonthBefore("yyyy-MM-dd", anotherDay, -3);
                detail = reportMapper.selectDayDetailByDate(anotherDay, endDate);
            } else if (type == 7) {
                String endDate = DateUtils.getMonthBefore("yyyy-MM-dd", anotherDay, -6);
                detail = reportMapper.selectDayDetailByMonth(anotherDay, endDate);
            } else if (type == 8) {
                detail = reportMapper.selectAllDayDetailByMonth();
            } else if (type == 9) {
                String startDate = requestJson.getString("startDate");
                String endDate = requestJson.getString("endDate");
                detail = reportMapper.selectDayDetailByDate(startDate, endDate);

            } else if (type == 10) {
                String sign = requestJson.getString("sign");
                String bigDate = requestJson.getString("bigDate");
                String smallDate = requestJson.getString("smallDate");
                List<JSONObject> comparedArr = new ArrayList<>();
                String comparedDate = "";
                if ("month".equals(sign)) {
                    Map<String, Object> dateMap = DateUtils.compareDate("yyyy-MM", bigDate, smallDate);
                    comparedDate = (String) dateMap.get("smallDate");
                    comparedArr = reportMapper.selectDayDetailsByMonth((String) dateMap.get("bigDate"));
                } else if ("day".equals(sign)) {
                    Map<String, Object> dateMap = DateUtils.compareDate("yyyy-MM-dd", bigDate, smallDate);
                    comparedDate = (String) dateMap.get("smallDate");
                    comparedArr = reportMapper.selectHourlyDetailsByDate((String) dateMap.get("bigDate"));
                }

                for (int i = 0; i < comparedArr.size(); i++) {
                    JSONObject comparedJson = comparedArr.get(i);
                    if (!Check.isNull(comparedJson)) {
                        JSONObject beComparedJson = new JSONObject();
                        String statDate = comparedJson.getString("statDate");
                        String beComparedDate = "";
                        String statHour = "";
                        if ("month".equals(sign)) {
                            String day = DateUtils.getDay("yyyy-MM-dd", statDate);
                            beComparedDate = comparedDate + "-" + day;
                            beComparedJson = reportMapper.selectDayDailyByDate(beComparedDate);

                        } else if ("day".equals(sign)) {
                            statHour = comparedJson.getString("statHour");
                            beComparedJson = reportMapper.selectDayHourlyByHourAndDate(comparedDate, statHour);
                            beComparedDate = comparedDate;
                        }

                        if (!Check.isNull(beComparedJson)) {
                            JSONObject json = new JSONObject();
                            BigDecimal cost = comparedJson.getBigDecimal("cost");
                            Long photoShow = comparedJson.getLong("photoShow");
                            Long photoClick = comparedJson.getLong("photoClick");
                            Long aClick = comparedJson.getLong("aclick");
                            json.put("cost", cost);
                            json.put("photoShow", photoShow);
                            json.put("photoClick", photoClick);
                            json.put("aClick", aClick);
                            json.put("statDate", statDate);
                            if ("day".equals(sign)) {
                                json.put("statHour", statHour);
                            }

                            BigDecimal comparedCost = beComparedJson.getBigDecimal("cost");
                            Long comparedPhotoShow = beComparedJson.getLong("photoShow");
                            Long comparedPhotoClick = beComparedJson.getLong("photoClick");
                            Long comparedAClick = beComparedJson.getLong("aclick");
                            json.put("beComparedCost", comparedCost);
                            json.put("beComparedPhotoShow", comparedPhotoShow);
                            json.put("beComparedPhotoClick", comparedPhotoClick);
                            json.put("beComparedAClick", comparedAClick);
                            json.put("beComparedDate", beComparedDate);

                            if (comparedCost.compareTo(new BigDecimal(0)) != 0) {
                                BigDecimal costProportion = (cost.subtract(comparedCost)).divide(comparedCost, 2, RoundingMode.HALF_UP);
                                json.put("costProportion", costProportion);
                            } else {
                                json.put("costProportion", 0);
                            }
                            if (comparedPhotoClick != 0L) {
                                double photoClickProportion = (photoClick.doubleValue() - comparedPhotoClick.doubleValue()) / comparedPhotoClick.doubleValue();
                                json.put("photoClickProportion", photoClickProportion);
                            } else {
                                json.put("photoClickProportion", 0);
                            }
                            if (comparedPhotoShow != 0L) {
                                double showProportion = (photoShow.doubleValue() - comparedPhotoShow.doubleValue()) / comparedPhotoShow.doubleValue();
                                json.put("showProportion", showProportion);
                            } else {
                                json.put("showProportion", 0);
                            }
                            if (comparedAClick != 0L) {
                                double aClickProportion = (aClick.doubleValue() - comparedAClick.doubleValue()) / comparedAClick.doubleValue();
                                json.put("comparedAclick", aClickProportion);
                            } else {
                                json.put("comparedAclick", 0);
                            }
                            detail.add(json);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }


    /**
     * 明细列表
     *
     * @param requestJson
     * @return
     */
    @Override
    public List<JSONObject> getReportList(JSONObject requestJson) {
        List<JSONObject> reportList = new ArrayList<>();
        try {
            Integer type = requestJson.getInteger("type");
            String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
            String anotherDay = DateUtils.getAnotherDay("yyyy-MM-dd", nowDate, -1);
            if (type == 1) {
                List<JSONObject> nowReportList = reportMapper.selectReportDetail(nowDate);
                List<JSONObject> yesterdayReportList = reportMapper.selectReportDetail(anotherDay);
                JSONObject json = new JSONObject();
                json.put("now", nowReportList);
                json.put("yesterday", yesterdayReportList);
                reportList.add(json);

            } else if (type == 2) {
                reportList = reportMapper.selectReportDetail(anotherDay);
            } else if (type == 3) {
                String endDate = DateUtils.getAnotherDay("yyyy-MM-dd", anotherDay, -6);
                reportList = reportMapper.selectDayDetailByDate(anotherDay, endDate);
            } else if (type == 4) {
                String endDate = DateUtils.getAnotherDay("yyyy-MM-dd", anotherDay, -14);
                reportList = reportMapper.selectDayDetailByDate(anotherDay, endDate);
            } else if (type == 5) {
                String endDate = DateUtils.getMonthBefore("yyyy-MM-dd", anotherDay, -1);
                reportList = reportMapper.selectDayDetailByDate(anotherDay, endDate);
            } else if (type == 6) {
                String endDate = DateUtils.getMonthBefore("yyyy-MM-dd", anotherDay, -3);
                reportList = reportMapper.selectDayDetailByDate(anotherDay, endDate);
            } else if (type == 7) {
                String endDate = DateUtils.getMonthBefore("yyyy-MM-dd", anotherDay, -6);
                reportList = reportMapper.selectDayDetailByMonth(anotherDay, endDate);
            } else if (type == 8) {
                reportList = reportMapper.selectAllDayDetailByMonth();
            } else if (type == 9) {
                String startDate = requestJson.getString("startDate");
                String endDate = requestJson.getString("endDate");
                reportList = reportMapper.selectDayDetailByDate(startDate, endDate);
            } else if (type == 10) {
                String sign = requestJson.getString("sign");
                String bigDate = requestJson.getString("bigDate");
                String smallDate = requestJson.getString("smallDate");
                Map<String, Object> dateMap = new HashMap<>();
                if ("month".equals(sign)) {
                    dateMap = DateUtils.compareDate("yyyy-MM", bigDate, smallDate);
                } else if ("day".equals(sign)) {
                    dateMap = DateUtils.compareDate("yyyy-MM-dd", bigDate, smallDate);
                }
                String comparedDate = (String) dateMap.get("bigDate");
                String beComparedDate = (String) dateMap.get("smallDate");
                JSONObject detailJson = new JSONObject();
                if ("month".equals(sign)) {
                    List<JSONObject> comparedArr = reportMapper.selectDayDetailsByMonth(beComparedDate);
                    detailJson.put("beStatDate", beComparedDate);
                    detailJson.put("beComparedDetail", comparedArr);
                    List<JSONObject> beComparedArr = reportMapper.selectDayDetailsByMonth(comparedDate);
                    detailJson.put("statDate", comparedDate);
                    detailJson.put("comparedDetail", beComparedArr);
                } else if ("day".equals(sign)) {
                    List<JSONObject> comparedArr = reportMapper.selectHourlyDetailsByDate(comparedDate);
                    detailJson.put("statDate", comparedDate);
                    detailJson.put("comparedDetail", comparedArr);
                    List<JSONObject> beComparedArr = reportMapper.selectHourlyDetailsByDate(beComparedDate);
                    detailJson.put("beStatDate", beComparedDate);
                    detailJson.put("beComparedDetail", beComparedArr);
                }
                reportList.add(detailJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reportList;
    }

    /////////////////////////////////////////////////////////\
    //素材报表
    @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);
        }
        log.info("头条素材报表结束 当前accountId为：{}  {}~{}" , accountId, startDate,endDate);
        return code;
    }

    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IBytedanceAccountReportTaskRecordService recordService;

    @Override
    public void bytedanceMaterialReportV2(BytedanceAccountReportTaskRecord record) {
        Long accountId = record.getAccountId();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        log.info("头条素材报表开始 当前accountId：{}  {}~{}" , accountId, record.getStartDate(),record.getEndDate());
        Integer page = 1;
        Integer pageSize = 500;
        int code = bytedanceMaterialReportByPage(page, pageSize, token, accountId, record.getStartDate(), record.getEndDate());
        if (code == 200 || code == 1) {
            record.setStatus(10086);
            record.setUpdateTime(new Date());
            recordService.updateById(record);
        }
        log.info("头条素材报表结束 当前accountId为：{}  {}~{}" , accountId, record.getStartDate(),record.getEndDate());
    }
    @Resource
    private BytedanceMatReportTaskCheckInfoMapper checkInfoMapper;

    @Override
    public void checkoutData(CtopOauthToken token, String startDate, String endDate) {
        //1:检查
        List<BytedanceMatReportTaskCheckInfo>checkInfoList = checkInfoMapper.getByParams(token.getAccountId(),startDate,endDate);
    }

    private int bytedanceMaterialReportByPage(Integer page, Integer pageSize, CtopOauthToken token, Long accountId, String startDate, String endDate) {
        // 请求地址
        String url = "https://ad.oceanengine.com/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(token.getAccessToken(), url, 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;
        }
    }

}
