package cn.com.ctop.kuaishou.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.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyGroup;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyGroupMapper;
import cn.com.ctop.kuaishou.modules.report.service.IEtlKuaiShouGroupDailyReportService;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportDailyGroupService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class KuaishouReportDailyGroupServiceImpl extends ServiceImpl<KuaishouReportDailyGroupMapper, KuaishouReportDailyGroup> implements IKuaishouReportDailyGroupService {
    @Autowired
    private KuaishouReportDailyGroupMapper groupMapper;
    @Autowired
    private IEtlKuaiShouGroupDailyReportService etlKuaiShouGroupDailyReportService;

    @Override
    public void formatChannelCode(String date) {
        groupMapper.formatChannelCode(date);
    }

    @Override
    public void getAdvertiserGroupReportDaily(CtopOauthToken token, Date startDate, Date endDate) {
        getAdvertiserGroupReportDailyByPage(token, startDate, endDate, 1);
    }

    private void getAdvertiserGroupReportDailyByPage(CtopOauthToken token, Date startDate, Date endDate, int page) {
        log.info("获取广告组日报，accountId:{},开始时间:{},结束时间：{}", token.getAccountId(), DateUtils.formatDate(startDate), DateUtils.formatDate(endDate));
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.GTOUP_REPORT;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());
        Map<String, Object> param = new HashMap<>();
        if (!Check.isNull(startDate)) {
            param.put("start_date", DateUtils.formatDate(startDate));
        }
        if (!Check.isNull(endDate)) {
            param.put("end_date", DateUtils.formatDate(endDate));
        }
        param.put("advertiser_id", token.getAccountId());
        param.put("temporal_granularity", "DAILY");
        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);
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手广告组报表异常:{},accountId:{}", message, token.getAccountId());
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            log.info("快手广告组报表信息为空=》accountId:{}", token.getAccountId());
            return;
        }
        List<KuaishouReportDailyGroup> addList = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = details.getJSONObject(i);
            detailJson.put("photo_share", detailJson.getString("share"));
            detailJson.put("photo_comment", detailJson.getString("comment"));
            detailJson.put("photo_like", detailJson.getString("like"));
            detailJson.put("photo_show", detailJson.getString("show"));
            KuaishouReportDailyGroup dailyGroup = JSONObject.toJavaObject(detailJson, KuaishouReportDailyGroup.class);
            dailyGroup.setAccountId(token.getAccountId());
            addList.add(dailyGroup);
        }
        if (!Check.isNull(addList)) {
            groupMapper.replaceBatch(addList);
            etlKuaiShouGroupDailyReportService.cleanGroupData(token.getAccountId(), details);
        }
        getAdvertiserGroupReportDailyByPage(token, startDate, endDate, page + 1);
    }
}
