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

import cn.com.ctop.common.module.entity.OauthAgentToken;
import cn.com.ctop.common.module.service.IOauthAgentTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.kuaishou.modules.report.entity.KuaiShouDailyAgent;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyAgent;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyAgentSum;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaiShouDailyAgentMapper;
import cn.com.ctop.kuaishou.modules.report.service.IKuaiShouDailyAgentService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 代理商报表
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-08-18
 */
@Slf4j
@Service
public class KuaiShouDailyAgentServiceImpl extends ServiceImpl<KuaiShouDailyAgentMapper, KuaiShouDailyAgent> implements IKuaiShouDailyAgentService {
    @Autowired
    private IOauthAgentTokenService agentTokenService;
    @Autowired
    private KuaiShouDailyAgentMapper agentMapper;

    @Override
    public void getAgentReportByPage(String startDate, String endDate) {
        List<Long> appList = new ArrayList<>();
        appList.add(27L);
        appList.add(165893351L);
        appList.add(165923740L);
        for (int i = 0; i < appList.size(); i++) {
            Long appId = appList.get(i);
            log.info("获取代理商数据AppId：{}",appId);
            OauthAgentToken agentToken = agentTokenService.getTokenByAppId(appId);
            getAgentReport(agentToken.getAccessToken(), agentToken.getAgentId(), startDate, endDate, 1);
        }
    }


    private void getAgentReport(String token, Long agentId, String startDate, String endDate, int page) {
        try {
            String url = "https://ad.e.kuaishou.com/rest/openapi/v1/agent/report";
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", " application/json");
            headers.put("Access-Token", token);
            JSONObject param = new JSONObject();
            param.put("start_date", startDate);
            param.put("end_date", endDate);
            param.put("agent_id", agentId);
            param.put("page_size", 1000);
            param.put("page", page);

            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (Check.isNull(resultJson)) {
                log.info("代理商数据返回为空");
                return;
            }
            Integer code = resultJson.getInteger("code");
            if (code != 0) {
                log.error("代理商报表返回code错误，返回：{}", resultJson);
                return;
            }
            JSONObject data = resultJson.getJSONObject("data");
            if (Check.isNull(data)) {
                log.error("代理商报表返回data节点为空");
                return;
            }
            JSONArray details = data.getJSONArray("details");
            if (Check.isNull(details)) {
                log.error("代理商报表返回details节点为空");
                return;
            }
            List<KuaiShouDailyAgent> agentList = new ArrayList<>();
            for (int i = 0; i < details.size(); i++) {
                JSONObject detailJson = details.getJSONObject(i);
                if (!Check.isNull(detailJson)) {
                    KuaiShouDailyAgent agent = new KuaiShouDailyAgent();
                    agent.setAgentId(agentId);
                    agent.setAccountId(detailJson.getLong("account_id"));
                    agent.setDateTime(detailJson.getString("date_time"));
                    agent.setUserId(detailJson.getLong("user_id"));
                    agent.setAccountName(detailJson.getString("account_name"));
                    agent.setTotalChargedInYuan(detailJson.getBigDecimal("total_charged_in_yuan"));
                    agent.setTotalBalanceInYuan(detailJson.getBigDecimal("total_balance"));
                    agent.setRealChargedInYuan(detailJson.getBigDecimal("real_charged_in_yuan"));
                    agent.setTotalRebateRealChargedInYuan(detailJson.getBigDecimal("total_rebate_real_charged_in_yuan"));
                    agent.setContractRebateRealChargedInYuan(detailJson.getBigDecimal("contract_rebate_real_charged_in_yuan"));
                    agent.setDirectRebateRealChargedInYuan(detailJson.getBigDecimal("direct_rebate_real_charged_in_yuan"));
                    agent.setCreditRealChargedInYuan(detailJson.getBigDecimal("credit_real_charged_in_yuan"));
                    agent.setChargeDayOnDayPercent(detailJson.getString("charge_day_on_day_percent"));
                    agent.setAdPhotoImpression(detailJson.getLong("ad_photo_impression"));
                    agent.setAdPhotoClick(detailJson.getLong("ad_photo_click"));
                    agent.setAdItemImpression(detailJson.getLong("ad_item_impression"));
                    agent.setAdItemClick(detailJson.getLong("ad_item_click"));
                    agent.setPhotoClickRatio(detailJson.getString("photo_click_ratio"));
                    agent.setItemClickRatio(detailJson.getString("item_click_ratio"));
                    agent.setChargedCampaignCount(detailJson.getLong("charged_campaign_count"));
                    agent.setProductName(detailJson.getString("product_name"));
                    agent.setCorporationName(detailJson.getString("corporation_name"));
                    agent.setFirstCostDay(detailJson.getString("first_cost_day"));
                    agent.setIndustry(detailJson.getString("industry"));
                    agent.setSecondIndustry(detailJson.getString("second_industry"));
                    agentList.add(agent);
                }
            }

            if (!Check.isNull(agentList)) {
                agentMapper.replaceBatch(agentList);
            }

            getAgentReport(token, agentId, startDate, endDate, page + 1);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 汇总
     *
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public List<KuaishouReportDailyAgentSum> companyReport(String startDate, String endDate) {
        return agentMapper.companyReport(startDate, endDate);
    }

    @Override
    public KuaishouReportDailyAgentSum companyReportSum(String startDate, String endDate) {
        return agentMapper.companyReportSum(startDate, endDate);
    }

    @Override
    public List<KuaishouReportDailyAgent> companyReportAccountDetailList(String date, String advertiserName, Integer o) {
        return agentMapper.companyReportAccountDetailList(date, advertiserName, o);
    }
}
