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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.toutiao.modules.link.entity.BaseReportBytedanceVideoDaily;
import cn.com.ctop.toutiao.modules.link.service.IBaseReportBytedanceVideoDailyService;
import cn.com.ctop.toutiao.modules.report.mapper.BytedanceVideoReportMapper;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceVideoReportService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
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;

@Slf4j
@Service
public class BytedanceVideoReportServiceImpl implements IBytedanceVideoReportService {

    @Resource
    BytedanceVideoReportMapper bytedanceVideoReportMapper;

    @Autowired
    IBaseReportBytedanceVideoDailyService baseReportBytedanceVideoDailyService;

    @Override
    public PageInfo<JSONObject> getVideoReportBy(JSONArray accountIds, String startDate, String endDate, String filed, String target, String order, String clip, String shot, String plan,String leader, int pageSize, int pageNo) {
        PageHelper.startPage(pageNo,pageSize);
        List<JSONObject> jsonObjectList=bytedanceVideoReportMapper.queryVideoReportBy(accountIds,startDate,endDate,filed,target,order,clip,shot,plan,leader);
        return new PageInfo<>(jsonObjectList);
    }

    @Override
    public List<JSONObject> getVideoDetailBy(JSONArray accountIds, String startDate, String endDate, String filed, String signature) {
        return bytedanceVideoReportMapper.queryVideoDetailBy(accountIds,startDate,endDate,filed,signature);
    }

    @Override
    public List<JSONObject> exportExcelReportBy(JSONArray accountIds, String startDate, String endDate, String filed, String target, String order, String clip, String shot, String plan, String leader) {
        return bytedanceVideoReportMapper.queryVideoReportBy(accountIds,startDate,endDate,filed,target,order,clip,shot,plan,leader);
    }

    @Override
    public void pullVideoReport(CtopOauthToken oauthToken, String startDate, String endDate, int page) {

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", " application/json");
        headers.put("Access-Token", oauthToken.getAccessToken());

        JSONObject param = new JSONObject();
        param.put("advertiser_id", oauthToken.getAccountId());
        param.put("start_date",startDate);
        param.put("end_date",endDate);
        param.put("page_size", 200);
        param.put("page", page);

        JSONObject resultJson = JSONObject.parseObject(HttpUtils.httpGetRequest("https://ad.oceanengine.com/open_api/2/report/video/get/", headers, param));
        if (Check.isNull(resultJson)) {
            log.warn("拉取头条视频报表返回结果为空,advertiserId:{}", oauthToken.getAccountId());
            return;
        }
        if(resultJson.getInteger("code")!=0){
            log.error("拉取头条视频表异常,advertiserId:{}，message:{}", oauthToken.getAccountId(),resultJson.getString("message"));
            return;
        }
        JSONObject data = resultJson.getJSONObject("data");
        if (null == data || data.size() <= 0) {
            log.error("拉取头条视频表异常,data is null");
            return;
        }

        JSONArray list= data.getJSONArray("list");
        if(list.isEmpty()){
            log.warn("拉取头条视频表,数据为空advertiserId:{}", oauthToken.getAccountId());
            return;
        }
        List<BaseReportBytedanceVideoDaily> batch =new ArrayList<>();
        list.forEach(videoReport->{
            JSONObject videoReportJSONObject= (JSONObject)videoReport;
            Long materialId= videoReportJSONObject.getJSONObject("dimensions").getLong("material_id");
            JSONObject metrics= videoReportJSONObject.getJSONObject("metrics");
            BaseReportBytedanceVideoDaily temp= JSONObject.toJavaObject(metrics,BaseReportBytedanceVideoDaily.class);
            temp.setMaterialShow(metrics.getLong("show"));
            temp.setConvertMaterial(metrics.getLong("convert"));
            temp.setAccountId(oauthToken.getAccountId());
            temp.setMaterialId(materialId);
            temp.setStatDatetime(startDate);
            batch.add(temp);
        });
        baseReportBytedanceVideoDailyService.saveBatch(batch);

        if(resultJson.getJSONObject("data").getJSONObject("page_info").getInteger("total_page")>page){
            pullVideoReport(oauthToken, startDate, endDate, page + 1);
        }
    }
}
