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

import cn.com.ctop.common.module.entity.RuleDataTargetKuaishou;
import cn.com.ctop.common.module.entity.RuleDatePlanKuaishou;
import cn.com.ctop.common.module.entity.RuleDateUnitKuaishou;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IRuleDataTargetKuaishouService;
import cn.com.ctop.common.module.service.IRuleDataUnitKuaishouService;
import cn.com.ctop.common.module.service.IRuleDatePlanKuaishouService;
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.service.IRuleKuaiShouPlanService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
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;

@Service
public class RuleKuaiShouPlanServiceImpl implements IRuleKuaiShouPlanService {

    @Autowired
    ICtopOauthTokenService oauthTokenService;

    @Autowired
    IRuleDataTargetKuaishouService targetKuaishouService;

    @Autowired
    IRuleDatePlanKuaishouService planKuaishouService;

    @Autowired
    IRuleDataUnitKuaishouService unitKuaishouService;

    @Override
    public void cleanRuleDataPlan(Long accountId, String startDate, String endDate, int page) {
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        param.put("page_size", 500);
        param.put("page", page);
        param.put("start_date", startDate);
        param.put("end_date", endDate);

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

        String result = HttpUtils.kuaiShouhttpPostRequest("https://ad.e.kuaishou.com/rest/openapi/v1/campaign/list", param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            XxlJobHelper.log("获取广告计划接口异常,advertiserId:{}", accountId);
            return;
        }
        Integer code = resultJson.getInteger("code");
        if (null == code || code != 0) {
            XxlJobHelper.log("获取广告计划返回结果异常,advertiserId:{},异常信息:{}", accountId, resultJson);
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }
        this.insertPlan(accountId, details);
        cleanRuleDataPlan(accountId, startDate, endDate, page + 1);
    }

    @Override
    public void cleanRuleDataUnit(Long accountId, String startDate, String endDate, int page) {
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        param.put("page_size", 500);
        param.put("page", page);
        param.put("start_date", startDate);
        param.put("end_date", endDate);

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

        String result = HttpUtils.kuaiShouhttpPostRequest("https://ad.e.kuaishou.com/rest/openapi/v1/report/unit_report", param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            XxlJobHelper.log("获取广告组报表接口异常,advertiserId:{}", accountId);
            return;
        }
        Integer code = resultJson.getInteger("code");
        if (null == code || code != 0) {
            XxlJobHelper.log("获取广告组报表返回结果异常,advertiserId:{},异常信息:{}", accountId, resultJson);
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }
        this.insertUnit(accountId, details);
        cleanRuleDataUnit(accountId, startDate, endDate, page + 1);
    }

    @Override
    public void cleanRuleDataTarget(Long accountId, String startDate, String endDate, int page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.GROUP_LIST;
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        param.put("page_size", 500);
        param.put("page", page);
        param.put("start_date", startDate);
        param.put("end_date", endDate);

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

        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            XxlJobHelper.log("获取广告组接口异常,advertiserId:{}", accountId);
            return;
        }
        Integer code = resultJson.getInteger("code");
        if (null == code || code != 0) {
            XxlJobHelper.log("获取广告组返回结果异常,advertiserId:{},异常信息:{}", accountId, resultJson);
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }
        this.insertTarget(accountId, details);
        cleanRuleDataTarget(accountId, startDate, endDate, page + 1);
    }

    private void insertPlan(Long accountId, JSONArray details) {
        List<RuleDatePlanKuaishou> batch = new ArrayList<>();
        details.forEach(detail -> {
            JSONObject planDetail = (JSONObject) detail;
            RuleDatePlanKuaishou plan = new RuleDatePlanKuaishou();
            if (planDetail.getInteger("status") == 4 && planDetail.getInteger("put_status") == 1) {
                plan.setId(planDetail.getLong("campaign_id"));
                plan.setAccountId(accountId);
                plan.setPlanId(planDetail.getLong("campaign_id"));
                plan.setPlanName(planDetail.getString("campaign_name"));
                batch.add(plan);
            }
        });
        planKuaishouService.saveOrUpdateBatch(batch);
    }

    private void insertUnit(Long accountId, JSONArray details) {
        List<RuleDateUnitKuaishou> batch = new ArrayList<>();
        details.forEach(detail -> {
            JSONObject unitDetail = (JSONObject) detail;
            RuleDateUnitKuaishou plan = new RuleDateUnitKuaishou();
            plan.setId(unitDetail.getLong("unit_id"));
            plan.setAccountId(accountId);
            plan.setUnitId(unitDetail.getLong("unit_id"));
            plan.setUnitName(unitDetail.getString("unit_name"));
            plan.setCharge(unitDetail.getBigDecimal("charge"));
/*            plan.setActivation(unitDetail.getBigDecimal("activation"));
            plan.setActivationCost(unitDetail.getBigDecimal("charge"));
            plan.setEventRegister(unitDetail.getBigDecimal("charge"));
            plan.setRegisterCost(unitDetail.getBigDecimal("charge"));
            plan.setFormCount(unitDetail.getBigDecimal("charge"));
            plan.setFormCost(unitDetail.getBigDecimal("charge"));
            plan.setEventPay(unitDetail.getBigDecimal("charge"));
            plan.setPayCost(unitDetail.getBigDecimal("charge"));*/
            batch.add(plan);
        });
        unitKuaishouService.saveOrUpdateBatch(batch);
    }

    private void insertTarget(Long accountId, JSONArray details) {
        List<RuleDataTargetKuaishou> batch = new ArrayList<>();
        details.forEach(detail -> {
            JSONObject unitDetail = (JSONObject) detail;
            RuleDataTargetKuaishou target = new RuleDataTargetKuaishou();
            if ((unitDetail.getInteger("status") == 20 || unitDetail.getInteger("status") == 19) &&
                    unitDetail.getInteger("put_status") == 1) {
                target.setId(unitDetail.getLong("unit_id"));
                target.setAccountId(accountId);
                target.setUnitId(unitDetail.getLong("unit_id"));
                target.setSceneId(unitDetail.getJSONArray("scene_id").toString());
                target.setRegion(unitDetail.getJSONArray("region").toString());
                target.setGender(unitDetail.getInteger("gender"));
                target.setPlatformOs(unitDetail.getInteger("platform_os"));
                target.setDeviceBrand(unitDetail.getJSONArray("device_brand").toString());
                target.setDevicePrice(unitDetail.getJSONArray("device_price").toString());
                target.setFilterConvertedLevel(unitDetail.getString("filter_converted_level"));
                target.setIsOpen(unitDetail.getInteger("is_open"));
                target.setScheduleTime(unitDetail.getJSONArray("schedule_time").toString());
                batch.add(target);
            }
        });
        targetKuaishouService.saveOrUpdateBatch(batch);
    }
}
