package cn.com.ctop.kuaishou.modules.batch.service.impl;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.kuaishou.modules.batch.entity.vo.KuaiShouVideoGetVo;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouReportDailyMaterialMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouReportDailyMaterialService;
import cn.com.ctop.kuaishou.modules.report.entity.EtlKuaishouAccountMaterialReportDaily;
import cn.com.ctop.kuaishou.modules.report.entity.KuaiShouReportDailyMaterial;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaiShouReportHourlyMaterialMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 素材
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-09-09
 */
@Slf4j
@Service
public class KuaiShouReportDailyMaterialServiceImpl extends ServiceImpl<KuaiShouReportDailyMaterialMapper, KuaiShouReportDailyMaterial> implements IKuaiShouReportDailyMaterialService {
    @Resource
    private KuaiShouReportDailyMaterialMapper dailyMaterialMapper;
    @Resource
    private KuaiShouReportHourlyMaterialMapper hourlyMaterialMapper;

    @Override
    public List<KuaiShouVideoGetVo> getVideoList(Map<String, Object> requestMap) {
        return dailyMaterialMapper.getVideoList(requestMap);
    }

    /**
     * 获取素材数据
     *
     * @param accountId
     * @param startDate
     * @param endDate
     */
    @Override
    public void getMaterialReportByAccountIdAndStatDate(Long accountId, String token, String startDate, String endDate, String temporalGranularity, Integer page) {
        String url = "https://ad.e.kuaishou.com/rest/openapi/v1/report/material_report";
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token);
        Map<String, Object> param = new HashMap<>();
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        param.put("advertiser_id", accountId);
        param.put("temporal_granularity", temporalGranularity);
        param.put("view_type", 5);
        param.put("page_size", 2000);
        param.put("page", page);
        String result = HttpUtils.httpPostRequest(url, param, headers);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            return;
        }
        Integer total_count = resultJson.getInteger("total_count");
        if (Check.isNull(total_count) || 0 == total_count) {
            return;
        }
        JSONArray details = resultJson.getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }
        List<KuaiShouReportDailyMaterial> addList = new ArrayList<>();
        List<Long> photoIdList = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = details.getJSONObject(i);
            detailJson.put("photo_like", detailJson.getInteger("like"));
            detailJson.put("photo_share", detailJson.getInteger("share"));
            detailJson.put("photo_comment", detailJson.getInteger("comment"));
            detailJson.put("photo_show", detailJson.getInteger("show"));
            KuaiShouReportDailyMaterial material = JSONObject.toJavaObject(detailJson, KuaiShouReportDailyMaterial.class);
           /* VideoGetvo videoGetvo = dailyMaterialMapper.getVideoGetByPhotoId(material.getPhotoId());
            if (!Check.isNull(videoGetvo)) {
                material.setChannelType(videoGetvo.getChannelType());
                material.setSignature(videoGetvo.getSignature());
            }*/
            material.setAccountId(accountId);
            photoIdList.add(material.getPhotoId());
            addList.add(material);
        }
        addList = this.getVideoInfoByList(addList, photoIdList);
        if ("DAILY".equals(temporalGranularity)) {
            dailyMaterialMapper.batchReplace(addList);
        } else if ("HOURLY".equals(temporalGranularity)) {
            hourlyMaterialMapper.batchReplace(addList);
        }

        getMaterialReportByAccountIdAndStatDate(accountId, token, startDate, endDate, temporalGranularity, page + 1);
    }

    @Override
    public List<KuaiShouReportDailyMaterial> getVideoInfoByList(List<KuaiShouReportDailyMaterial> addList, List<Long> photoIdList) {
        if (Check.isNull(photoIdList)) {
            return null;
        }
        List<JSONObject> videoInfoList = dailyMaterialMapper.getVideoInfoByList(photoIdList);
        Map<Long, JSONObject> videoMap = new HashMap<>();
        for (int i = 0; i < videoInfoList.size(); i++) {
            JSONObject jsonObject = videoInfoList.get(i);
            videoMap.put(jsonObject.getLong("photoId"), jsonObject);
        }
        for (KuaiShouReportDailyMaterial dailyMaterial : addList) {
            JSONObject jsonObject = videoMap.get(dailyMaterial.getPhotoId());
            if (Check.isNull(jsonObject)) {
                continue;
            }
            dailyMaterial.setSignature(jsonObject.getString("signature"));
            dailyMaterial.setChannelType(jsonObject.getInteger("channelType"));
        }
        return addList;
    }

    @Override
    public Result<Object> labelMaterialList(String companyId, String realname, String roleCode, String startTime, String endTime, Integer pageNo, Integer pageSize) {
        Long total = dailyMaterialMapper.labelMaterialListTotal(companyId, realname, roleCode, startTime, endTime);
        PageHelper.startPage(pageNo, pageSize, false);
        PageInfo pageInfo = new PageInfo(dailyMaterialMapper.labelMaterialList(companyId, realname, roleCode, startTime, endTime));
        pageInfo.setTotal(total);
        JSONObject data = new JSONObject();
        data.put("pageInfo", pageInfo);
        if (total > 0) {
            data.put("total", dailyMaterialMapper.labelMaterialAll(companyId, realname, roleCode, startTime, endTime));
        }
        return Result.ok(data);
    }

    @Override
    public List<EtlKuaishouAccountMaterialReportDaily> getReportList(Long accountId, String statDate, Long projectId, String projectName) {
        return dailyMaterialMapper.getReportList(accountId, statDate, projectId, projectName);
    }

    @Override
    public List<KuaiShouReportDailyMaterial> getSignatureByDate(String date) {
        return dailyMaterialMapper.getSignatureByDate(date);
    }

    @Override
    public KuaiShouReportDailyMaterial getEtlDataByParams(String signature, String date, Long projectId) {
        return dailyMaterialMapper.getEtlDataByParams(signature, date, projectId);
    }

    @Override
    public List<KuaiShouReportDailyMaterial> getSignatureByDateGroupByProjectId(String date) {
        return dailyMaterialMapper.getSignatureByDateGroupByProjectId(date);
    }
}
