package cn.com.ctop.kuaishou.modules.batch.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.*;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouDailyReportTask;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouHistoryReportTask;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouHistoryReportTaskMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouReportDailyMaterialMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouDailyReportTaskService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouHistoryReportTaskService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouReportDailyMaterialService;
import cn.com.ctop.kuaishou.modules.report.entity.KuaiShouReportDailyMaterial;
import cn.com.ctop.kuaishou.modules.report.entity.KuaiShouReportDailyMaterialVo;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyAccount;
import cn.com.ctop.kuaishou.modules.report.entity.VideoGetvo;
import cn.com.ctop.kuaishou.modules.report.mapper.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csvreader.CsvReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 快手历史数据任务记录
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-03-09
 */
@Slf4j
@Service
public class KuaiShouHistoryReportTaskServiceImpl extends ServiceImpl<KuaiShouHistoryReportTaskMapper, KuaiShouHistoryReportTask> implements IKuaiShouHistoryReportTaskService {
    @Value("${jeecg.path.report-history}")
    private String downloadPath;
    static List<Integer> historyTypeList;
    static List<Integer> dailyTypeList;
    @Autowired
    private ICtopOauthTokenService ctopOauthTokenService;
    @Autowired
    private KuaishouReportDailyAccountMapper reportDailyAccountMapper;

    @Autowired
    private KuaishouReportDailyCampaignMapper reportDailyCampaignMapper;


    @Autowired
    private KuaishouReportDailyGroupMapper reportDailyGroupMapper;

    @Autowired
    private KuaishouReportDailyCreativeMapper reportDailyCreativeMapper;
    @Autowired
    private IKuaiShouDailyReportTaskService dailyReportTaskService;

    @Autowired
    private KuaiShouReportDailyMaterialMapper kuaishouReportDailyMaterialMapper;
    @Autowired
    private IKuaiShouReportDailyMaterialService reportDailyMaterialService;
    @Autowired
    private KuaiShouReportDailyMaterialMapper dailyMaterialMapper;

    @Override
    public void createTask(Long accountId, String token, String startDate, String endDate, String taskType) {
        if (Check.isNull(accountId) || Check.isNull(token)) {
            log.error("token或accountId为空");
            return;
        }
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.ASYNC_TASK_CREAT;
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token);
            JSONObject param = new JSONObject();
            param.put("advertiser_id", accountId);
            JSONObject taskParams = new JSONObject();
            taskParams.put("start_date", startDate);
            taskParams.put("end_date", endDate);

            if (null != taskType && taskType.equals(CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_DAILY)) {
                if (Check.isNull(dailyTypeList)) {
                    getDailyTypeList();
                }
                for (int i = 0; i < dailyTypeList.size(); i++) {
                    Integer type = dailyTypeList.get(i);
                    String taskName = accountId + "_" + type + "_" + System.currentTimeMillis();
                    param.put("task_name", taskName);
                    taskParams.put("view_type", type);
                    param.put("task_params", taskParams);

                    String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
                    Thread.sleep(500);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    if (!Check.isNull(resultJson)) {
                        Integer code = resultJson.getInteger("code");
                        if (code == 0) {
                            JSONObject dataJson = resultJson.getJSONObject("data");
                            KuaiShouDailyReportTask dailyReportTask = new KuaiShouDailyReportTask();
                            dailyReportTask.setAccountId(accountId);
                            dailyReportTask.setStatDate(endDate);
                            dailyReportTask.setTaskId(dataJson.getString("task_id"));
                            dailyReportTask.setViewType(type);
                            dailyReportTask.setTaskStatus(0);
                            dailyReportTask.setTaskName(taskName);
                            dailyReportTaskService.save(dailyReportTask);
                        } else {
                            log.error("快手分天报表请求失败，accountId:{},返回数据:{}", accountId, resultJson);
                        }
                    }
                }
            } else {
                if (Check.isNull(historyTypeList)) {
                    getHistoryTypeList();
                }
                for (int i = 0; i < historyTypeList.size(); i++) {
                    Integer type = historyTypeList.get(i);
                    String taskName = accountId + "_" + type + "_" + System.currentTimeMillis();
                    param.put("task_name", taskName);
                    taskParams.put("view_type", type);
                    param.put("task_params", taskParams);
                    String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    log.info("请求状态返回数据:{}", resultJson);
                    if (!Check.isNull(resultJson)) {
                        Integer code = resultJson.getInteger("code");
                        if (code == 0) {
                            JSONObject dataJson = resultJson.getJSONObject("data");
                            KuaiShouHistoryReportTask reportTask = new KuaiShouHistoryReportTask();
                            reportTask.setAccountId(accountId);
                            reportTask.setStartDate(startDate);
                            reportTask.setEndDate(endDate);
                            reportTask.setTaskId(dataJson.getString("task_id"));
                            reportTask.setViewType(type);
                            reportTask.setTaskStatus(0);
                            reportTask.setTaskName(taskName);
                            this.save(reportTask);
                        } else {
                            log.error("快手历史报表请求失败，accountId:{},返回数据:{}", accountId, resultJson);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取任务列表
     */
    @Override
    public void getTaskList() {
        log.info("开始历史数据文件检查下载");
        QueryWrapper<KuaiShouHistoryReportTask> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.eq("task_status", 0);
        taskQueryWrapper.orderByDesc("create_time");
        List<KuaiShouHistoryReportTask> taskList = this.list(taskQueryWrapper);
        if (!Check.isNull(taskList)) {
            for (KuaiShouHistoryReportTask task : taskList) {
                CtopOauthToken token = ctopOauthTokenService.getTokenByAccountId(task.getAccountId());
                if (!Check.isNull(token)) {
                    String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.ASYNC_TASK_LIST;
                    Map<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/json");
                    headers.put("Access-Token", token.getAccessToken());
                    JSONObject param = new JSONObject();
                    param.put("advertiser_id", task.getAccountId());
                    JSONArray taskIds = new JSONArray();
                    taskIds.add(task.getTaskId());
                    param.put("task_ids", taskIds);
                    String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    log.info("请求状态返回数据:{}", resultJson);
                    if (!Check.isNull(resultJson)) {
                        Integer code = resultJson.getInteger("code");
                        if (code == 0) {
                            JSONObject dataJson = resultJson.getJSONObject("data");
                            if (!Check.isNull(dataJson)) {
                                JSONArray details = dataJson.getJSONArray("details");
                                if (!Check.isNull(details)) {
                                    for (int i = 0; i < details.size(); i++) {
                                        JSONObject detailJson = details.getJSONObject(i);
                                        if (!Check.isNull(detailJson)) {
                                            Integer taskStatus = detailJson.getInteger("task_status");
                                            if (taskStatus == 2) {
                                                loadFile(token.getAccessToken(), task);
                                            } else if (taskStatus == 3) {
                                                task.setTaskStatus(3);
                                                this.updateById(task);
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            log.error("快手获取任务列表返回错误，accountId：{}，返回结果：{}", task.getAccountId(), resultJson);
                        }
                    }
                }
            }
        }
    }


    private void loadFile(String token, KuaiShouHistoryReportTask task) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.ASYNC_TASK_DOWNLOAD;
            String fileName = task.getAccountId() + "_" + task.getViewType() + ".csv";
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("advertiser_id", task.getAccountId());
            requestMap.put("task_id", task.getTaskId());
            String localPath = LoadFileUtil.downloadByUrl(requestMap, downloadPath, url, token, fileName);
            ArrayList<String[]> reportList = getReportList(localPath);
            if (task.getViewType() == 1) {
                if (!Check.isNull(reportList)) {
                    List<KuaishouReportDailyAccount> reportDailyAccounts = new ArrayList<>();
                    for (int row = 0; row < reportList.size(); row++) {
                        if (Check.isNull(row)) {
                            continue;
                        }
                        KuaishouReportDailyAccount reportDailyAccount = new KuaishouReportDailyAccount();
                        reportDailyAccount.setAccountId(task.getAccountId());
                        reportDailyAccount.setCharge(ConverterUtils.getAsBigDecimal(reportList.get(row)[1]));
                        reportDailyAccount.setAdScene(reportList.get(row)[0]);
                        reportDailyAccount.setPhotoShow(ConverterUtils.getAsLong(reportList.get(row)[2]));
                        reportDailyAccount.setAclick(ConverterUtils.getAsLong(reportList.get(row)[3]));
                        reportDailyAccount.setBclick(ConverterUtils.getAsLong(reportList.get(row)[4]));
                        reportDailyAccount.setPhotoShare(ConverterUtils.getAsLong(reportList.get(row)[5]));
                        reportDailyAccount.setPhotoComment(ConverterUtils.getAsLong(reportList.get(row)[6]));
                        reportDailyAccount.setPhotoLike(ConverterUtils.getAsLong(reportList.get(row)[7]));
                        reportDailyAccount.setFollow(ConverterUtils.getAsLong(reportList.get(row)[8]));
                        reportDailyAccount.setCancelFollow(ConverterUtils.getAsLong(reportList.get(row)[9]));
                        reportDailyAccount.setReport(ConverterUtils.getAsLong(reportList.get(row)[10]));
                        reportDailyAccount.setBlock(ConverterUtils.getAsLong(reportList.get(row)[11]));
                        reportDailyAccount.setNegative(ConverterUtils.getAsLong(reportList.get(row)[12]));
                        reportDailyAccount.setDownloadStarted(ConverterUtils.getAsLong(reportList.get(row)[13]));
                        reportDailyAccount.setDownloadCompleted(ConverterUtils.getAsLong(reportList.get(row)[14]));
                        reportDailyAccount.setActivation(ConverterUtils.getAsLong(reportList.get(row)[15]));
                        reportDailyAccount.setSubmit(ConverterUtils.getAsLong(reportList.get(row)[16]));
                        reportDailyAccount.setStatDate(reportList.get(row)[17]);
                        reportDailyAccount.setPhotoClick(ConverterUtils.getAsLong(reportList.get(row)[19]));
                        reportDailyAccount.setPhotoClickRatio(ConverterUtils.getAsDouble(reportList.get(row)[20]));
                        reportDailyAccount.setActionRatio(ConverterUtils.getAsDouble(reportList.get(row)[21]));
                        reportDailyAccount.setImpression1kCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[22]));
                        reportDailyAccount.setPhotoClickCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[23]));
                        reportDailyAccount.setActionCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[25]));
                        reportDailyAccount.setEventPayFirstDay(ConverterUtils.getAsLong(reportList.get(row)[26]));
                        reportDailyAccount.setEventPayPurchaseAmountFirstDay(ConverterUtils.getAsBigDecimal(reportList.get(row)[27]));
                        reportDailyAccount.setEventPayFirstDayRoi(ConverterUtils.getAsDouble(reportList.get(row)[28]));
                        reportDailyAccount.setEventPay(ConverterUtils.getAsLong(reportList.get(row)[29]));
                        reportDailyAccount.setEventPayPurchaseAmount(ConverterUtils.getAsBigDecimal(reportList.get(row)[30]));
                        reportDailyAccount.setEventPayRoi(ConverterUtils.getAsDouble(reportList.get(row)[31]));
                        reportDailyAccount.setEventRegister(ConverterUtils.getAsLong(reportList.get(row)[32]));
                        reportDailyAccount.setEventRegisterCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[33]));
                        reportDailyAccount.setEventRegisterRatio(ConverterUtils.getAsDouble(reportList.get(row)[34]));
                        reportDailyAccount.setEventJinJianApp(ConverterUtils.getAsLong(reportList.get(row)[35]));
                        reportDailyAccount.setEventJinJianAppCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[36]));
                        reportDailyAccount.setEventCreditGrantApp(ConverterUtils.getAsLong(reportList.get(row)[37]));
                        reportDailyAccount.setEventCreditGrantAppCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[38]));
                        reportDailyAccount.setEventCreditGrantAppRatio(ConverterUtils.getAsDouble(reportList.get(row)[39]));
                        reportDailyAccount.setEventOrderPaid(ConverterUtils.getAsLong(reportList.get(row)[40]));
                        reportDailyAccount.setEventOrderPaidPurchaseAmount(ConverterUtils.getAsBigDecimal(reportList.get(row)[41]));
                        reportDailyAccount.setEventOrderPaidCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[42]));
                        reportDailyAccount.setFormCount(ConverterUtils.getAsLong(reportList.get(row)[43]));
                        reportDailyAccount.setFormCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[44]));
                        reportDailyAccount.setFormActionRatio(ConverterUtils.getAsDouble(reportList.get(row)[45]));
                        reportDailyAccount.setEventJinJianLandingPage(ConverterUtils.getAsLong(reportList.get(row)[46]));
                        reportDailyAccount.setEventJinJianLandingPageCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[47]));
                        reportDailyAccount.setEventCreditGrantLandingPage(ConverterUtils.getAsLong(reportList.get(row)[48]));
                        reportDailyAccount.setEventCreditGrantLandingPageCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[49]));
                        reportDailyAccount.setEventCreditGrantLandingRatio(ConverterUtils.getAsDouble(reportList.get(row)[50]));
                        reportDailyAccount.setEventNextDayStayCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[51]));
                        reportDailyAccount.setEventNextDayStayRatio(ConverterUtils.getAsBigDecimal(reportList.get(row)[52]));
                        reportDailyAccount.setEventNextDayStay(ConverterUtils.getAsLong(reportList.get(row)[53]));
                        reportDailyAccount.setPlay3sRatio(ConverterUtils.getAsDouble(reportList.get(row)[54]));
                        reportDailyAccount.setEventNewUserPay(ConverterUtils.getAsLong(reportList.get(row)[63]));
                        reportDailyAccount.setEventNewUserPayCost(ConverterUtils.getAsBigDecimal(reportList.get(row)[64]));
                        reportDailyAccount.setEventNewUserPayRatio(ConverterUtils.getAsBigDecimal(reportList.get(row)[65]));
                        reportDailyAccounts.add(reportDailyAccount);
                    }
                    if (!Check.isNull(reportDailyAccounts)) {
                        reportDailyAccountMapper.replaceBatch(reportDailyAccounts);
                    }
                }
            } else if (task.getViewType() == 5) {
                if (!Check.isNull(reportList)) {
                    List<KuaiShouReportDailyMaterial> materialList = new ArrayList<>();
                    List<Long> photoIdList = new ArrayList<>();
                    for (int row = 0; row < reportList.size(); row++) {
                        String[] strings = reportList.get(row);
                        if (Check.isNull(strings)) {
                            continue;
                        }
                        KuaiShouReportDailyMaterial material = new KuaiShouReportDailyMaterial();
                        material.setAccountId(task.getAccountId());
                        material.setPhotoId(ConverterUtils.getAsLong(strings[0]));
                        photoIdList.add(ConverterUtils.getAsLong(strings[0]));
                        material.setImageToken(strings[1]);
                        material.setCoverUrl(strings[2]);
                        material.setPhotoUrl(strings[3]);
                        // 4
                        material.setCreativeMaterialTypeString(strings[5]);
                        material.setAdScene(strings[6]);
                        material.setCharge(ConverterUtils.getAsBigDecimal(strings[7]));
                        material.setPhotoShow(ConverterUtils.getAsLong(strings[8]));
                        material.setAclick(ConverterUtils.getAsLong(strings[9]));
                        material.setBclick(ConverterUtils.getAsLong(strings[10]));
                        material.setPhotoShare(ConverterUtils.getAsInteger(strings[11]));
                        material.setPhotoComment(ConverterUtils.getAsInteger(strings[12]));
                        material.setPhotoLike(ConverterUtils.getAsInteger(strings[13]));
                        material.setFollow(ConverterUtils.getAsInteger(strings[14]));
                        material.setCancelFollow(ConverterUtils.getAsInteger(strings[15]));
                        material.setReport(ConverterUtils.getAsInteger(strings[16]));
                        material.setBlock(ConverterUtils.getAsInteger(strings[17]));
                        material.setNegative(ConverterUtils.getAsInteger(strings[18]));
                        material.setDownloadStarted(ConverterUtils.getAsInteger(strings[19]));
                        material.setDownloadCompleted(ConverterUtils.getAsInteger(strings[20]));
                        material.setActivation(ConverterUtils.getAsInteger(strings[21]));
                        material.setSubmit(ConverterUtils.getAsInteger(strings[22]));
                        material.setStatDate(strings[23]);
                        // 24
                        material.setPhotoClick(ConverterUtils.getAsLong(strings[25]));
                        material.setPhotoClickRatio(ConverterUtils.getAsDouble(strings[26]));
                        material.setActionRatio(ConverterUtils.getAsDouble(strings[27]));
                        material.setImpression1kCost(ConverterUtils.getAsBigDecimal(strings[28]));
                        material.setPhotoClickCost(ConverterUtils.getAsBigDecimal(strings[29]));
                        // material.setClick1(ConverterUtils.getAsBigDecimal(strings[30]));
                        material.setActionCost(ConverterUtils.getAsBigDecimal(strings[31]));
                        material.setEventPayFirstDay(ConverterUtils.getAsInteger(strings[32]));
                        material.setEventPayPurchaseAmountFirstDay(ConverterUtils.getAsBigDecimal(strings[33]));
                        material.setEventPayFirstDayRoi(ConverterUtils.getAsDouble(strings[34]));
                        material.setEventPay(ConverterUtils.getAsInteger(strings[35]));
                        material.setEventPayPurchaseAmount(ConverterUtils.getAsBigDecimal(strings[36]));
                        material.setEventPayRoi(ConverterUtils.getAsDouble(strings[37]));
                        material.setEventRegister(ConverterUtils.getAsInteger(strings[38]));
                        material.setEventRegisterCost(ConverterUtils.getAsBigDecimal(strings[39]));
                        material.setEventRegisterRatio(ConverterUtils.getAsDouble(strings[40]));
                        material.setEventJinJianApp(ConverterUtils.getAsInteger(strings[41]));
                        material.setEventJinJianAppCost(ConverterUtils.getAsBigDecimal(strings[42]));
                        material.setEventCreditGrantApp(ConverterUtils.getAsInteger(strings[43]));
                        material.setEventCreditGrantAppCost(ConverterUtils.getAsBigDecimal(strings[44]));
                        material.setEventCreditGrantAppRatio(ConverterUtils.getAsDouble(strings[45]));
                        material.setEventOrderPaid(ConverterUtils.getAsInteger(strings[46]));
                        material.setEventOrderPaidPurchaseAmount(ConverterUtils.getAsBigDecimal(strings[47]));
                        material.setEventOrderPaidCost(ConverterUtils.getAsBigDecimal(strings[48]));
                        material.setFormCount(ConverterUtils.getAsInteger(strings[49]));
                        material.setFormCost(ConverterUtils.getAsBigDecimal(strings[50]));
                        material.setFormActionRatio(ConverterUtils.getAsDouble(strings[51]));
                        material.setEventJinJianLandingPage(ConverterUtils.getAsInteger(strings[52]));
                        material.setEventJinJianLandingPageCost(ConverterUtils.getAsBigDecimal(strings[53]));
                        material.setEventCreditGrantLandingPage(ConverterUtils.getAsInteger(strings[54]));
                        material.setEventCreditGrantLandingPageCost(ConverterUtils.getAsBigDecimal(strings[55]));
                        material.setEventCreditGrantLandingRatio(ConverterUtils.getAsDouble(strings[56]));
                        material.setEventNextDayStayCost(ConverterUtils.getAsBigDecimal(strings[57]));
                        material.setEventNextDayStayRatio(ConverterUtils.getAsInteger(strings[58]));
                        material.setEventNextDayStay(ConverterUtils.getAsInteger(strings[59]));
                        material.setPlay3sRatio(ConverterUtils.getAsDouble(strings[60]));
                        materialList.add(material);
                    }
                    if (!Check.isNull(materialList)) {
                        List<KuaiShouReportDailyMaterial> videoInfoByList = reportDailyMaterialService.getVideoInfoByList(materialList, photoIdList);
                        dailyMaterialMapper.batchReplace(videoInfoByList);

                    }

                }

            }


            //   System.err.println(reportList);
          /*  if (!Check.isNull(localPath)) {
                Map<String, Object> deleteMap = new HashMap<>();
                deleteMap.put("account_id", task.getAccountId());

                if (task.getViewType() == 1) {
                    reportDailyAccountMapper.deleteByMap(deleteMap);
                    reportDailyAccountMapper.loadAccountDailyReport(task.getAccountId(), localPath);
                } else if (task.getViewType() == 2) {
                    reportDailyCampaignMapper.deleteByMap(deleteMap);
                    reportDailyCampaignMapper.loadCampaignDailyReport(task.getAccountId(), localPath);

                } else if (task.getViewType() == 3) {
                    reportDailyGroupMapper.deleteByMap(deleteMap);
                    reportDailyGroupMapper.loadGroupDailyReport(task.getAccountId(), localPath);

                } else if (task.getViewType() == 4) {
                    reportDailyCreativeMapper.deleteByMap(deleteMap);
                    reportDailyCreativeMapper.loadCreativeDailyReport(task.getAccountId(), localPath);

                } else if (task.getViewType() == 10) {
                    reportDailyCreativeMapper.deleteByAccountId(task.getAccountId());
                    reportDailyCreativeMapper.loadProgramCreativeDailyReport(task.getAccountId(), localPath);

                } else if (task.getViewType() == 5) {
                    kuaishouReportDailyMaterialMapper.deleteByMap(deleteMap);
                    kuaishouReportDailyMaterialMapper.loadMaterialDailyReport(task.getAccountId(), localPath);
                    Thread thread = new Thread() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1 * 500L);
                                getMd5(null, task.getAccountId());
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                    };
                    thread.start();
                } else if (task.getViewType() == 7) {
                    kuaishouReportDailyImageMapper.deleteByMap(deleteMap);
                    //封面报表
                    kuaishouReportDailyImageMapper.loadImageDailyReport(task.getAccountId(), localPath);
                    //清洗数据
                    kuaishouReportDailyImageMapper.updateImageReportCode();
                    kuaishouReportDailyImageMapper.updateImageReportUserId();
                    kuaishouReportDailyImageMapper.updateImageReportRealname();
                }


            }*/
            task.setTaskStatus(4);

        } catch (Exception e) {
            e.printStackTrace();
            task.setTaskStatus(5);
        }
        this.updateById(task);

    }


    private ArrayList<String[]> getReportList(String localPath) throws IOException {
        ArrayList<String[]> csvFileList = new ArrayList<String[]>();
        // 定义一个CSV路径
        // 创建CSV读对象 例如:CsvReader(文件路径，分隔符，编码格式);
        CsvReader reader = new CsvReader(localPath, ',', Charset.forName("UTF-8"));
        // 跳过表头 如果需要表头的话，这句可以忽略
        reader.readHeaders();
        // 逐行读入除表头的数据
        while (reader.readRecord()) {
            //  System.out.println(reader.getRawRecord());
            csvFileList.add(reader.getValues());
        }
        reader.close();
        return csvFileList;

    }

    @Autowired
    private KuaishouReportDailyImageMapper kuaishouReportDailyImageMapper;


    private void getHistoryTypeList() {

        historyTypeList = new ArrayList<>();
        historyTypeList.add(1);
        historyTypeList.add(5);
      /*  historyTypeList.add(2);
        historyTypeList.add(3);*/
        // historyTypeList.add(4);
        //
        // historyTypeList.add(7);
        //  historyTypeList.add(10);


    }

    private void getDailyTypeList() {
        dailyTypeList = new ArrayList<>();
        dailyTypeList.add(2);
        dailyTypeList.add(3);
        dailyTypeList.add(4);
        dailyTypeList.add(5);
        dailyTypeList.add(7);
        dailyTypeList.add(10);
    }


    static ExecutorService executorService = Executors.newFixedThreadPool(30);

    @Override
    public void getMd5(String statDate, Long accountId) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                List<KuaiShouReportDailyMaterialVo> photoList = kuaishouReportDailyMaterialMapper.getPhotoList(accountId, statDate);
                if (!Check.isNull(photoList)) {
                    for (KuaiShouReportDailyMaterialVo materialVo : photoList) {
                        Long photoId = materialVo.getPhotoId();
                        VideoGetvo videoGetvo = kuaishouReportDailyMaterialMapper.getVideoGetByPhotoId(photoId);
                        if (!Check.isNull(videoGetvo)) {
                            QueryWrapper<KuaiShouReportDailyMaterial> updateQueryWrapper = new QueryWrapper<>();
                            updateQueryWrapper.eq("photo_id", photoId);
                            if (!Check.isNull(statDate)) {
                                updateQueryWrapper.eq("stat_date", statDate);
                            }

                            updateQueryWrapper.isNull("signature");
                            KuaiShouReportDailyMaterial material = new KuaiShouReportDailyMaterial();
                            material.setSignature(videoGetvo.getSignature());
                            material.setChannelType(videoGetvo.getChannelType());
                            kuaishouReportDailyMaterialMapper.update(material, updateQueryWrapper);
                            log.info("修改成功：photoId:{},accountId:{}", photoId, accountId);
                        }

                    }
                }
            }
        });

    }

    @Override
    public void getMd5V2(String statDate) {
        List<KuaiShouReportDailyMaterialVo> photoList = kuaishouReportDailyMaterialMapper.getPhotoListByDate(statDate);
        if (!Check.isNull(photoList)) {
            for (KuaiShouReportDailyMaterialVo materialVo : photoList) {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        Long photoId = materialVo.getPhotoId();
                        VideoGetvo videoGetvo = kuaishouReportDailyMaterialMapper.getVideoGetByPhotoId(photoId);
                        if (!Check.isNull(videoGetvo)) {
                            QueryWrapper<KuaiShouReportDailyMaterial> updateQueryWrapper = new QueryWrapper<>();
                            updateQueryWrapper.eq("photo_id", photoId);
                            if (!Check.isNull(statDate)) {
                                updateQueryWrapper.eq("stat_date", statDate);
                            }
                            KuaiShouReportDailyMaterial material = new KuaiShouReportDailyMaterial();
                            material.setSignature(videoGetvo.getSignature());
                            material.setChannelType(videoGetvo.getChannelType());
                            kuaishouReportDailyMaterialMapper.update(material, updateQueryWrapper);
                        }
                    }
                });
            }
        }


    }


}
