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.mapper.RuleDatePlanKuaishouMapper;
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.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupService;
import cn.com.ctop.kuaishou.modules.report.service.IRuleKuaiShouPlanService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.core.context.XxlJobHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RuleKuaiShouPlanServiceImpl extends ServiceImpl<RuleDatePlanKuaishouMapper, RuleDatePlanKuaishou>  implements IRuleKuaiShouPlanService {

    @Autowired
    ICtopOauthTokenService oauthTokenService;

    @Autowired
    IRuleDataTargetKuaishouService targetKuaishouService;

    @Autowired
    IRuleDatePlanKuaishouService planKuaishouService;

    @Autowired
    IRuleDataUnitKuaishouService unitKuaishouService;

    @Autowired
    IKuaiShouGroupService kuaiShouGroupService;

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

        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, 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, int page) {
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        param.put("page_size", 500);
        param.put("page", page);

        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/ad_unit/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.insertTarget(accountId, details);
        cleanRuleDataTarget(accountId, 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);
            }
        });
        if(!batch.isEmpty()) {
            planKuaishouService.saveOrUpdateBatch(batch);
        }
    }

    private void insertUnit(Long accountId, JSONArray details) {
        List<RuleDateUnitKuaishou> batch = new ArrayList<>();
        details.forEach(detail -> {
            JSONObject unitDetail = (JSONObject) detail;
            RuleDateUnitKuaishou unit = new RuleDateUnitKuaishou();
            QueryWrapper<KuaiShouGroup> wrapper=new QueryWrapper<>();
            wrapper.eq("unit_id",unitDetail.getLong("unit_id"));
            KuaiShouGroup group = kuaiShouGroupService.getOne(wrapper);
            if(group!=null){
                Integer status = group.getStatus();
                Integer putStatus = group.getPutStatus();
                if((status == 20 || status == 19) && putStatus == 1){
                    unit.setId(unitDetail.getLong("unit_id"));
                    unit.setAccountId(accountId);
                    unit.setPlanId(unitDetail.getLong("campaign_id"));
                    unit.setUnitId(unitDetail.getLong("unit_id"));
                    unit.setUnitName(unitDetail.getString("unit_name"));
                    unit.setCharge(unitDetail.getBigDecimal("charge"));
                    //未知优化目标数据存空
                    if(group.getOcpxActionType()!=0){
                        unit.setConvertNum(handleConvertNum(group.getOcpxActionType(),unitDetail));
                        if(null!=unit.getConvertNum()&&unit.getConvertNum()!=0){
                            unit.setConvertCost(unitDetail.getBigDecimal("charge").divide(BigDecimal.valueOf(unit.getConvertNum()), 2, RoundingMode.HALF_UP));
                        }
                    }
                    batch.add(unit);
                }
            }

        });
        if(!batch.isEmpty()){
            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();
            Integer status = unitDetail.getInteger("status");
            Integer putStatus = unitDetail.getInteger("put_status");
            if ((status == 20 || status == 19) && putStatus == 1) {
                target.setId(unitDetail.getLong("unit_id"));
                target.setAccountId(accountId);
                target.setPlanId(unitDetail.getLong("campaign_id"));
                target.setUnitId(unitDetail.getLong("unit_id"));
                target.setSceneId(unitDetail.getJSONArray("scene_id")==null?"":unitDetail.getJSONArray("scene_id").toString());
                //获取组定向信息
                JSONObject unitTarget = unitDetail.getJSONObject("target");
                //地域
                JSONArray region = unitTarget.getJSONArray("region");
                target.setRegion(region==null?"":region.toJSONString());
                //性别
                Integer gender = unitDetail.getJSONObject("target").getInteger("gender");
                target.setGender(gender==null?0:gender);
                //年龄
                JSONArray agesRange = unitTarget.getJSONArray("ages_range");
                target.setAgesRange(agesRange==null?"":agesRange.toJSONString());
                //操作系统
                Integer platformOs = unitTarget.getInteger("platform_os");
                target.setPlatformOs(platformOs==null?0:platformOs);
                //设类类型
                JSONArray deviceBrand = unitTarget.getJSONArray("device_brand");
                target.setDeviceBrand(deviceBrand==null?"":deviceBrand.toJSONString());
                //设备价格
                JSONArray devicePrice = unitTarget.getJSONArray("device_price");
                target.setDevicePrice(devicePrice==null?"":devicePrice.toJSONString());
                //过滤已转化人群
                Integer filterConvertedLevel = unitTarget.getInteger("filter_converted_level");
                target.setFilterConvertedLevel(filterConvertedLevel);
                //人群包定向
                JSONArray population = unitTarget.getJSONArray("population");
                target.setPopulation(population==null?"":population.toJSONString());
                //人群包排除
                JSONArray excludePopulation = unitTarget.getJSONArray("exclude_population");
                target.setExcludePopulation(excludePopulation==null?"":excludePopulation.toJSONString());
                //应用商店
                JSONArray appStore = unitDetail.getJSONArray("app_store");
                target.setAppStore(appStore==null?"":appStore.toJSONString());
                //商业兴趣
                JSONArray businessInterest = unitTarget.getJSONArray("business_interest");
                target.setBusinessInterest(businessInterest==null?"":businessInterest.toJSONString());
                //网络环境
                Integer network = unitTarget.getInteger("network");
                target.setNetwork(network==null?0:network);

                Integer isOpen = unitDetail.getJSONObject("target").getJSONObject("intelli_extend").getInteger("is_open");
                target.setIsOpen(isOpen==null?0:isOpen);
                target.setScheduleTime(unitDetail.getString("schedule_time")==null?"":unitDetail.getString("schedule_time"));

                batch.add(target);
            }
        });
        if (!batch.isEmpty()) {
            targetKuaishouService.saveOrUpdateBatch(batch);
        }
    }

    /**
     * 53：提交线索，form_count
     * 180：激活，activation
     * 190: 付费，event_pay
     * 191：首日ROI，event_pay_roi
     * 348：有效线索，event_valid_clues
     * 383: 授信，event_credit_grant_app
     * 384: 完件 event_jin_jian_app
     * 715：微信复制 event_add_wechat
     * @param ocpxActionType
     * @param detail
     * @return
     */
    private Long handleConvertNum(int ocpxActionType,JSONObject detail){
        Long convertNum=null;
        switch (ocpxActionType){
            case 2:
                convertNum=detail.getLong("bclick");
                break;
            case 10:
                convertNum=detail.getLong("aclick");
                break;
            case 11:
                convertNum=detail.getLong("photo_click");
                break;
            case 31:
                convertNum=detail.getLong("download_completed");
                break;
            case 53:
                convertNum=detail.getLong("form_count");
                break;
            case 180:
                convertNum=detail.getLong("activation");
                break;
            case 190:
                convertNum=detail.getLong("event_pay");
                break;
            case 191:
                convertNum=detail.getDouble("event_pay_first_day_roi").longValue();
                break;
            case 348:
                convertNum=detail.getLong("event_valid_clues");
                break;
            case 383:
                convertNum=detail.getLong("event_credit_grant_app");
                break;
            case 384:
                convertNum=detail.getLong("event_jin_jian_app");
                break;
            case 715:
                convertNum=detail.getLong("event_add_wechat");
                break;
        }
        return convertNum;
    }
}
