package cn.com.ctop.bytedance.service.impl;

import cn.com.ctop.bytedance.entity.*;
import cn.com.ctop.bytedance.mapper.CustomerPlanStatisticInfoMapper;
import cn.com.ctop.bytedance.mapper.PlatformCampaignStatisticInfoMapper;
import cn.com.ctop.bytedance.service.*;
import cn.com.ctop.bytedance.vo.ByteDanceAdvertiserReportDTO;
import cn.com.ctop.bytedance.vo.StatisticCampaignVo;
import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.*;
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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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 java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 宋英豪
 */
@Slf4j
@Service
public class ReportServiceImpl implements IReportService {
    @Value("${jeecg.path.csv-upload}")
    private String csvUploadPath;
    @Autowired
    private IPlatformCampaignStatisticInfoService platformCampaignStatisticInfoService;
    @Autowired
    private ICustomerPlanStatisticInfoService customerPlanStatisticInfoService;
    @Autowired
    private PlatformCampaignStatisticInfoMapper statisticInfoMapper;
    @Autowired
    private CustomerPlanStatisticInfoMapper customerPlanStatisticInfoMapper;
    @Autowired
    private PlatformCampaignStatisticInfoMapper platformCampaignStatisticInfoMapper;
    @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;

    @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);
        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) {
            log.info("广告主报表信息为空=》accountId:{}", token.getAccountId());
            return;
        }

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

    @Override
    public Map<String, Object> getAdvertiserReport(ByteDanceAdvertiserReportDTO conditions) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(conditions, config));
        Long accountId = conditions.getAdvertiserId();
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId + "");
        JSONObject getObject = getAdvertiserStat(token, jsonObject);
        Integer code = getObject.getInteger("code");
        String message = getObject.getString("message");
        if (null == code || code != 0) {
            log.error("广告主数据获取异常：{}", message);
        } else {
            JSONArray dataArray = getObject.getJSONObject("data").getJSONArray("list");
            if (null != dataArray && dataArray.size() > 0) {
                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);
                    }
                }

            }
        }
        return getObject;
    }

    @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.size() <= 0) {
            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 Map<String, Object> getCampaignReport(ByteDanceAdvertiserReportDTO conditions) {
        conditions.setAdvertiserId(111463131228L);
        conditions.setStartDate("2019-06-01");
        conditions.setEndDate("2019-06-10");
        conditions.setPageSize(1000);
        conditions.setPage(1);
        conditions.setTimeGranularity(CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(conditions, config));
        Long accountId = conditions.getAdvertiserId();
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId + "");
        JSONObject getObject = getAdStat(token, jsonObject);
        Integer code = getObject.getInteger("code");
        String message = getObject.getString("message");
        if (null == code || code != 0) {
            log.error("广告组报表数据获取异常：{}", message);
        } else {
            JSONArray dataArray = getObject.getJSONObject("data").getJSONArray("list");
            if (null != dataArray && dataArray.size() > 0) {
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject data = dataArray.getJSONObject(i);
                    if (null != conditions.getTimeGranularity() && CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY.equals(conditions.getTimeGranularity())) {
                        BytedanceCampaignHourlyReport hourlyReport = new BytedanceCampaignHourlyReport(data, token.getAccountId());
                        campaignHourlyReportService.saveOrUpdate(hourlyReport);
                    } else {
                        BytedanceCampaignDailyReport dailyReport = new BytedanceCampaignDailyReport(data, token.getAccountId());
                        campaignDailyReportService.saveOrUpdate(dailyReport);
                    }
                }
            }
        }
        return getObject;
    }

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

    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));
        var getObject = getAdStat(token, jsonObject);
        var code = getObject.getInteger("code");
        var message = getObject.getString("message");
        if (null == code || code != 0) {
            log.error("广告计划报表数据获取异常：{}", message);
            return;
        }
        var dataArray = getObject.getJSONObject("data").getJSONArray("list");
        if (null == dataArray || dataArray.size() <= 0) {
            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 BytedancePlanHourlyReport(data, token.getAccountId());
                planHourlyReportService.saveOrUpdate(hourlyReport);
            } else {
                var dailyReport = new BytedancePlanDailyReport(data, token.getAccountId());
                planDailyReportService.saveOrUpdate(dailyReport);
            }
        }

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

    @Override
    public Map<String, Object> getAdReport(ByteDanceAdvertiserReportDTO conditions) {
        conditions.setAdvertiserId(111463131228L);
        conditions.setStartDate("2019-06-01");
        conditions.setEndDate("2019-06-10");
        conditions.setPageSize(1000);
        conditions.setPage(1);
        conditions.setTimeGranularity(CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(conditions, config));
        Long accountId = conditions.getAdvertiserId();
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId + "");
        JSONObject getObject = getAdStat(token, jsonObject);
        Integer code = getObject.getInteger("code");
        String message = getObject.getString("message");
        if (null == code || code != 0) {
            log.error("广告计划报表数据获取异常：{}", message);
        } else {
            JSONArray dataArray = getObject.getJSONObject("data").getJSONArray("list");
            if (null != dataArray && dataArray.size() > 0) {
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject data = dataArray.getJSONObject(i);
                    if (null != conditions.getTimeGranularity() && CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY.equals(conditions.getTimeGranularity())) {
                        BytedancePlanHourlyReport hourlyReport = new BytedancePlanHourlyReport(data, token.getAccountId());
                        planHourlyReportService.saveOrUpdate(hourlyReport);
                    } else {
                        BytedancePlanDailyReport dailyReport = new BytedancePlanDailyReport(data, token.getAccountId());
                        planDailyReportService.saveOrUpdate(dailyReport);
                    }
                }
            }
        }
        return getObject;
    }

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

    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 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) {
            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 BytedanceCreativeHourlyReport(data, token.getAccountId());
                creativeHourlyReportService.saveOrUpdate(hourlyReport);
            } else {
                var dailyReport = new BytedanceCreativeDailyReport(data, token.getAccountId());
                creativeDailyReportService.saveOrUpdate(dailyReport);
            }
        }
        getCreativeReportByPage(token, conditions, page + 1);
    }

    @Override
    public Map<String, Object> getCreativeReport(ByteDanceAdvertiserReportDTO conditions) {
        conditions.setAdvertiserId(111463131228L);
        conditions.setStartDate("2019-06-01");
        conditions.setEndDate("2019-06-10");
        conditions.setPageSize(1000);
        conditions.setPage(1);
        conditions.setTimeGranularity(CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(conditions, config));
        Long accountId = conditions.getAdvertiserId();
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId + "");
        JSONObject getObject = getCreativeStat(token, jsonObject);
        Integer code = getObject.getInteger("code");
        String message = getObject.getString("message");
        if (null == code || code != 0) {
            log.error("广告创意报表数据获取异常：{}", message);
        } else {
            JSONArray dataArray = getObject.getJSONObject("data").getJSONArray("list");
            if (null != dataArray && dataArray.size() > 0) {
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject data = dataArray.getJSONObject(i);
                    if (null != conditions.getTimeGranularity() && CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY.equals(conditions.getTimeGranularity())) {
                        BytedanceCreativeHourlyReport hourlyReport = new BytedanceCreativeHourlyReport(data, token.getAccountId());
                        creativeHourlyReportService.saveOrUpdate(hourlyReport);
                    } else {
                        BytedanceCreativeDailyReport dailyReport = new BytedanceCreativeDailyReport(data, token.getAccountId());
                        creativeDailyReportService.saveOrUpdate(dailyReport);
                    }
                }
            }
        }
        return getObject;
    }

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

    private JSONObject getAdStat(CtopOauthToken token, JSONObject conditions) {
        // 请求地址
        String url = "https://ad.toutiao.com/open_api/2/report/ad/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);
    }

    @Override
    public void insertCustomerInfo(String csvPath, String charset) {
        try {
            List<String[]> data = CsvUtils.readCsv(csvPath, charset);
            if (null != data && data.size() > 1) {
                for (int i = 1; i < data.size(); i++) {
                    String[] record = data.get(i);
                    CustomerPlanStatisticInfo statisticInfo = new CustomerPlanStatisticInfo(record);
                    customerPlanStatisticInfoMapper.insert(statisticInfo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertPlatformInfo(String csvPath, String charset, Long accountId) {
        try {
            List<String[]> data = CsvUtils.readCsv(csvPath, charset);
            if (null != data && data.size() > 1) {
                for (int i = 1; i < data.size(); i++) {
                    String[] record = data.get(i);
                    PlatformCampaignStatisticInfo statisticInfo = new PlatformCampaignStatisticInfo(record, accountId);
                    platformCampaignStatisticInfoMapper.insert(statisticInfo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> debitAuto(JSONObject data) {
        Map<String, Object> resultMap = new HashMap<>();
        String accountOneKsDataUrl = data.getString("accountOneKsDataUrl");
        String accountFourKsDataUrl = data.getString("accountFourKsDataUrl");
        String debitDataUrl = data.getString("debitDataUrl");
        //1:文件下载入库
        String accountOneKsDataPath = downLoadByUrl(accountOneKsDataUrl);
        String accountFourKsDataPath = downLoadByUrl(accountFourKsDataUrl);
        String debitDataPath = downLoadByUrl(debitDataUrl);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/M/dd");
        //2:文件入库
        //2.1 清除数据库原始数据
        QueryWrapper<CustomerPlanStatisticInfo> planWrapper = new QueryWrapper<>();
        planWrapper.isNotNull("id");
        customerPlanStatisticInfoService.remove(planWrapper);

        QueryWrapper<PlatformCampaignStatisticInfo> campaignWrapper = new QueryWrapper<>();
        campaignWrapper.isNotNull("id");
        platformCampaignStatisticInfoService.remove(campaignWrapper);

        this.insertPlatformInfo(accountOneKsDataPath, "gb2312", 1L);
        QueryWrapper<PlatformCampaignStatisticInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("campaign_code", "biaodan").orderByDesc("id").last("limit 1");
        PlatformCampaignStatisticInfo statisticInfo = platformCampaignStatisticInfoMapper.selectOne(queryWrapper);
        if (null != statisticInfo) {
            PlatformCampaignStatisticInfo updateInfo = new PlatformCampaignStatisticInfo();
            updateInfo.setCampaignCode("biaodan2");
            QueryWrapper<PlatformCampaignStatisticInfo> updateWrapper = new QueryWrapper<>();
            updateWrapper.ne("campaign_info", statisticInfo.getCampaignInfo()).eq("campaign_code", statisticInfo.getCampaignCode());
            platformCampaignStatisticInfoMapper.update(updateInfo, updateWrapper);
        }
        this.insertPlatformInfo(accountFourKsDataPath, "gb2312", 4L);
        this.insertCustomerInfo(debitDataPath, "utf8");
        //3：根据模板生成相应的excel模板文件
        try {
            String platformReportPath = getExcelDataPath(simpleDateFormat.format(new Date()), 1L, 4L);
//            //4：同步上传到oss文件服务器
//            String ossPath = OSSUtils.uploadFile2Oss(new File(platformReportPath));
//            //5: 返回文件服务器访问链接
            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
            resultMap.put("path", platformReportPath);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SERVER_ERROR.getCode());
            return resultMap;
        }
    }

    public String getExcelDataPath(String date, Long accountId1, Long accountId4) throws Exception {
        List<StatisticCampaignVo> statisticCampaign1Vos = statisticInfoMapper.getVoByParams(accountId1);
        List<StatisticCampaignVo> statisticCampaign4Vos = statisticInfoMapper.getVoByParams(accountId4);
        File f = new File(csvUploadPath + "template.xlsx");
        InputStream inputStream = new FileInputStream(f);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
//        //获取第一个sheet
        XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
        CellStyle numbericCellStyle = xssfWorkbook.createCellStyle();
        numbericCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
        int index;
        for (index = 1; index < statisticCampaign1Vos.size() + 1; index++) {
            StatisticCampaignVo vo = statisticCampaign1Vos.get(index - 1);
            String content = vo.getContent();
            String[] contents = content.split("-");
            Row row = xssfSheet.getRow(index);
            setExcelRow(numbericCellStyle, vo, contents, row, "single");
        }
        List<StatisticCampaignVo> zero1Vos = statisticInfoMapper.sumZeroVoByParams(accountId1);
        List<StatisticCampaignVo> zaodianVos = statisticInfoMapper.sumZaodianVoByParams(accountId1);
        if (null != zero1Vos && zero1Vos.size() > 0) {
            for (int z = 0; z < zero1Vos.size(); z++) {
                StatisticCampaignVo vo = zero1Vos.get(z);
                Row row = xssfSheet.getRow(index);
                String content = vo.getContent();
                String[] contents = content.split("-");
                setExcelRow(numbericCellStyle, vo, contents, row, "single");
                index++;
            }
        }
        if (null != zaodianVos && zaodianVos.size() > 0) {
            for (int z = 0; z < zaodianVos.size(); z++) {
                StatisticCampaignVo vo = zaodianVos.get(z);
                Row row = xssfSheet.getRow(index);
                String content = vo.getContent();
                String[] contents = content.split("-");
                setExcelRow(numbericCellStyle, vo, contents, row, "single");
                index++;
            }
        }
        Row totalRow1 = xssfSheet.getRow(index);
        StatisticCampaignVo total = statisticInfoMapper.getTotalStatisticVoByparams(accountId1);
        if (null != total) {
            setExcelRow(numbericCellStyle, total, new String[]{}, totalRow1, "total1");
        }
        index++;
        for (int j = 0; j < statisticCampaign4Vos.size(); j++) {
            index++;
            StatisticCampaignVo vo = statisticCampaign4Vos.get(j);
            String content = vo.getContent();
            String[] contents = content.split("-");
            Row row = xssfSheet.getRow(index);
            setExcelRow(numbericCellStyle, vo, contents, row, "single");
        }
        List<StatisticCampaignVo> zero4Vos = statisticInfoMapper.sumZeroVoByParams(accountId4);
        if (null != zero4Vos && zero4Vos.size() > 0) {
            for (int z = 0; z < zero4Vos.size(); z++) {
                index++;
                StatisticCampaignVo vo = zero4Vos.get(z);
                Row row = xssfSheet.getRow(index);
                String content = vo.getContent();
                String[] contents = content.split("-");
                setExcelRow(numbericCellStyle, vo, contents, row, "single");
            }
        }
        index++;
        Row totalRow4 = xssfSheet.getRow(index);
        StatisticCampaignVo total1 = statisticInfoMapper.getTotalStatisticVoByparams(accountId4);
        if (null != total1) {
            setExcelRow(numbericCellStyle, total1, new String[]{}, totalRow4, "total4");
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-m-dd");
        String path = csvUploadPath + "report_" + dateFormat.format(new Date()) + ".xlsx";
        FileOutputStream fileOutputStream = new FileOutputStream(path);
        xssfWorkbook.write(fileOutputStream);
        fileOutputStream.close();
        return path;

    }

    private void setExcelRow(CellStyle numbericCellStyle, StatisticCampaignVo vo, String[] contents, Row row, String type) {
        for (int j = 0; j < 38; j++) {
            Cell cell = row.createCell(j);
            if (j == 0) {
                //日期
                if (null != type && "single".equals(type)) {
                    cell.setCellValue(vo.getStatisticDate());
                } else if (null != type && "total1".equals(type)) {
                    cell.setCellValue("户一总计");
                } else {
                    cell.setCellValue("户四总计");
                }
            } else if (j == 1) {
                //代理
                cell.setCellValue(vo.getProxy());
            } else if (j == 2) {
                //投放系统
                if (null != contents && contents.length > 3) {
                    cell.setCellValue(contents[2]);
                } else {
                    cell.setCellValue("");
                }
            } else if (j == 3) {
                //渠道号
                if (null != contents && contents.length > 2) {
                    cell.setCellValue(contents[1]);
                } else {
                    cell.setCellValue("");
                }
            } else if (j == 4) {
                //content
                if (null != contents && contents.length > 0) {
                    cell.setCellValue(contents[0]);
                } else {
                    cell.setCellValue("");
                }
//                cell.setCellValue(vo.getContent());
            } else if (j == 5) {
                if (null != contents && contents.length > 5) {
                    cell.setCellValue(contents[4]);
                } else {
                    cell.setCellValue("");
                }
            } else if (j == 6) {
                //出价方式
                if (null != contents && contents.length > 6) {
                    cell.setCellValue(contents[5]);
                } else {
                    cell.setCellValue("");
                }
            } else if (j == 7) {
                //定向条件
                if (null != contents && contents.length > 4) {
                    cell.setCellValue(contents[3]);
                } else {
                    cell.setCellValue("");
                }
            } else if (j == 8) {
                //定向条件
                if (null != contents && contents.length > 7) {
                    cell.setCellValue(contents[6]);
                } else {
                    cell.setCellValue("");
                }
            } else if (j == 9) {
                //花费
                if (null != vo.getCost() && !"".equals(vo.getCost())) {
                    cell.setCellValue(Float.parseFloat(vo.getCost()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 10) {
                //封面曝光数
                if (null != vo.getCoverViews() && !"".equals(vo.getCoverViews())) {
                    cell.setCellValue(Integer.parseInt(vo.getCoverViews()));
                }
            } else if (j == 11) {
                //封面点击数
                if (null != vo.getCoverClick() && !"".equals(vo.getCoverClick())) {
                    cell.setCellValue(Integer.parseInt(vo.getCoverClick()));
                }
            } else if (j == 12) {
                //素材曝光数
                if (null != vo.getMaterialViews() && !"".equals(vo.getMaterialViews())) {
                    cell.setCellValue(Integer.parseInt(vo.getMaterialViews()));
                }
            } else if (j == 13) {
                //行为数
                if (null != vo.getActions() && !"".equals(vo.getActions())) {
                    cell.setCellValue(Integer.parseInt(vo.getActions()));
                }
            } else if (j == 14) {
                //点击率
                if (null != vo.getClickRate() && !"".equals(vo.getClickRate())) {
                    cell.setCellValue(Float.parseFloat(vo.getClickRate()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 15) {
                //行为点击率
                if (null != vo.getActionClickRate() && !"".equals(vo.getActionClickRate())) {
                    cell.setCellValue(Float.parseFloat(vo.getActionClickRate()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 16) {
                //ACTR*BCTR
                if (null != vo.getAbctr() && !"".equals(vo.getAbctr())) {
                    cell.setCellValue(Float.parseFloat(vo.getAbctr()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 17) {
                //点击成本
                if (null != vo.getClickPrice() && !"".equals(vo.getClickPrice())) {
                    cell.setCellValue(Float.parseFloat(vo.getClickPrice()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 18) {
                //行为成本
                if (null != vo.getActionPrice() && !"".equals(vo.getActionPrice())) {
                    cell.setCellValue(Float.parseFloat(vo.getActionPrice()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 19) {
                //注册用户
                if (null != vo.getRegistUserNum() && !"".equals(vo.getRegistUserNum())) {
                    BigDecimal decimal = new BigDecimal(vo.getRegistUserNum());
                    cell.setCellValue(decimal.intValue());
                }
            } else if (j == 20) {
                //完件用户
                if (null != vo.getComplateUserNum() && !"".equals(vo.getComplateUserNum())) {
                    BigDecimal decimal = new BigDecimal(vo.getComplateUserNum());
                    cell.setCellValue(decimal.intValue());
                }
            } else if (j == 21) {
                //授信用户
                if (null != vo.getCreditUserNum() && !"".equals(vo.getCreditUserNum())) {
                    BigDecimal decimal = new BigDecimal(vo.getCreditUserNum());
                    cell.setCellValue(decimal.intValue());
                }
            } else if (j == 22) {
                //当日注册且完件数
                if (null != vo.getRegistCompleteNum() && !"".equals(vo.getRegistCompleteNum())) {
                    BigDecimal decimal = new BigDecimal(vo.getRegistCompleteNum());
                    cell.setCellValue(decimal.intValue());
                }
            } else if (j == 23) {
                //当日注册且授信数
                if (null != vo.getRegistCreditNum() && !"".equals(vo.getRegistCreditNum())) {
                    BigDecimal decimal = new BigDecimal(vo.getRegistCreditNum());
                    cell.setCellValue(decimal.intValue());
                }
            } else if (j == 24) {
                //注册成本
                if (null != vo.getRegistPrice() && !"".equals(vo.getRegistPrice())) {
                    cell.setCellValue(Float.parseFloat(vo.getRegistPrice()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 25) {
                //完件成本
                if (null != vo.getCompletePrice() && !"".equals(vo.getCompletePrice())) {
                    cell.setCellValue(Float.parseFloat(vo.getCompletePrice()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 26) {
                //授信成本
                if (null != vo.getCreditPrice() && !"".equals(vo.getCreditPrice())) {
                    cell.setCellValue(Float.parseFloat(vo.getCreditPrice()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 27) {
                //当日注册且完件成本
                if (null != vo.getRegistCompletePrice() && !"".equals(vo.getRegistCompletePrice())) {
                    cell.setCellValue(Float.parseFloat(vo.getRegistCompletePrice()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 28) {
                //当日注册且授信成本
                if (null != vo.getRegistCreditPrice() && !"".equals(vo.getRegistCreditPrice())) {
                    cell.setCellValue(Float.parseFloat(vo.getRegistCreditPrice()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 29) {
                //点击注册率
                if (null != vo.getClickRegistRate() && !"".equals(vo.getClickRegistRate())) {
                    cell.setCellValue(Float.parseFloat(vo.getClickRegistRate()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 30) {
                //行为注册率
                if (null != vo.getActionRegistRate() && !"".equals(vo.getActionRegistRate())) {
                    cell.setCellValue(Float.parseFloat(vo.getActionRegistRate()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 31) {
                //完件率
                if (null != vo.getCompleteRate() && !"".equals(vo.getCompleteRate())) {
                    cell.setCellValue(Float.parseFloat(vo.getCompleteRate()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 32) {
                //授信率
                if (null != vo.getCreditRate() && !"".equals(vo.getCreditRate())) {
                    cell.setCellValue(Float.parseFloat(vo.getCreditRate()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 33) {
                //当日完件率
                if (null != vo.getRegistCompleteRate() && !"".equals(vo.getRegistCompleteRate())) {
                    cell.setCellValue(Float.parseFloat(vo.getRegistCompleteRate()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 34) {
                //当日授信率
                if (null != vo.getRegistCreditRate() && !"".equals(vo.getRegistCreditRate())) {
                    cell.setCellValue(Float.parseFloat(vo.getRegistCreditRate()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 35) {
                //当日完件/完件
                if (null != vo.getCompleteRateDay() && !"".equals(vo.getCompleteRateDay())) {
                    cell.setCellValue(Float.parseFloat(vo.getCompleteRateDay()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 36) {
                //当日授信/授信
                if (null != vo.getCreditRateDay() && !"".equals(vo.getCreditRateDay())) {
                    cell.setCellValue(Float.parseFloat(vo.getCreditRateDay()));
                    cell.setCellStyle(numbericCellStyle);
                }
            } else if (j == 37) {
                //当日授信/注册
                if (null != vo.getCreditRegistRateDay() && !"".equals(vo.getCreditRegistRateDay())) {
                    cell.setCellValue(Float.parseFloat(vo.getCreditRegistRateDay()));
                    cell.setCellStyle(numbericCellStyle);
                }
            }
        }
    }

    public String downLoadByUrl(String fileUrl) {
        //获取文件名，文件名实际上在URL中可以找到
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        //这里服务器上要将此图保存的路径
        String savePath = this.csvUploadPath + fileName;
        try {
            //将网络资源地址传给,即赋值给url
            URL url = new URL("https:" + fileUrl);
            //此为联系获得网络资源的固定格式用法，以便后面的in变量获得url截取网络资源的输入流
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            DataInputStream in = new DataInputStream(connection.getInputStream());
            //此处也可用BufferedInputStream与BufferedOutputStream
            DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
            //将参数savePath，即将截取的图片的存储在本地地址赋值给out输出流所指定的地址
            byte[] buffer = new byte[4096];
            int count = 0;
            //将输入流以字节的形式读取并写入buffer中
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            out.close();
            in.close();
            connection.disconnect();
            //返回内容是保存后的完整的URL
            return savePath;

        } catch (Exception e) {
            return null;
        }
    }

    public JSONObject getAgentStat(CtopOauthToken token, JSONObject conditions) {
        // 请求地址
        String url = "https://ad.toutiao.com/open_api/2/report/agent/get/";
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, conditions);
    }

    public JSONObject getCreativeStat(CtopOauthToken token, JSONObject conditions) {
        // 请求地址
        String url = "https://ad.toutiao.com/open_api/2/report/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);
    }

    public JSONObject getCampaignStat(CtopOauthToken token, JSONObject conditions) {
        // 请求地址
        String url = "https://ad.toutiao.com/open_api/2/report/campaign/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 = "https://ad.toutiao.com/open_api/2/report/advertiser/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);
    }
}
