package cn.com.ctop.kuaishou.modules.batch.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.batch.entity.KuaishouPopulation;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouPopulationMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouPopulationService;
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.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 人群包列表
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-05-06
 */
@Slf4j
@Service
public class KuaishouPopulationServiceImpl extends ServiceImpl<KuaishouPopulationMapper, KuaishouPopulation> implements IKuaishouPopulationService {

    @Autowired
    private KuaishouPopulationMapper populationMapper;
    private String urlPath = PropertiesUtils.getConfig("kuaishou_api_url");

    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;


    @Override
    public JSONObject getPopulationList(Long accountId, String accessToken, Integer status) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.POPULATION_LIST;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", "application/json");
        JSONObject requestJson = new JSONObject();
        requestJson.put("advertiser_id", accountId);
        requestJson.put("status", status);
        requestJson.put("page", 1);
        requestJson.put("page_size", 500);
        String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            return resultJson;
        }
        return null;
    }

    /**
     * 获取人群包接口
     *
     * @param accountId
     * @param populationId 人群包ID
     * @param accessToken  token
     * @param accountId    广告主ID
     * @return
     */
    @Override
    public JSONObject deletePopulation(Long accountId, Long populationId, String accessToken) {
        log.info("删除人群包，accountId:{}", accountId);
        String url = urlPath + KuaishouInterfaceConstant.POPULATION_DELETE;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", "application/json");
        JSONObject requestJson = new JSONObject();
        requestJson.put("advertiser_id", accountId);
        requestJson.put("orientation_id", populationId);
        String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            return resultJson;
        }
        return null;
    }


    /**
     * 获取人群包接口
     *
     * @param accountId
     * @param populationName 人群包名称
     * @param type           1：IMEI 2：IDFA 3：IMEI_MD5 4：IDFA_MD5 5：手机号-MD5 7：OAID
     * @param accountId      广告主ID
     * @param file           请求的页码
     * @param accessToken    token
     * @return
     */
    @Override
    public JSONObject updatePopulation(CtopOauthToken token, int type, String populationName, String filePath) {
        String url = urlPath + KuaishouInterfaceConstant.POPULATION_UPLOAD;
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Access-Token", token.getAccessToken());
        headerMap.put("Content-Type", "multipart/form-data");
        JSONObject requestJson = new JSONObject();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("advertiser_id", token.getAccountId());
        paramMap.put("type", type);
        paramMap.put("orientation_name", populationName);
        String result = kuaishouInterfaceService.exceptInfoForRestTemplate(url, paramMap, headerMap, filePath);
        if (!Check.isNull(result)) {
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                return resultJson;
            }
        }
        return null;
    }

    /**
     * 推送人群包接口（单日最多可调用50次推送接口）
     *
     * @param accountId
     * @param populationId 人群包ID （只有status为1或6的人群包可推送，最多支持4个人群包状态同时为“推送中”）
     * @param accessToken  token
     * @param accountId    广告主ID
     * @return
     */
    @Override
    public boolean pushPopulation(Long accountId, String populationId, String accessToken) {
        log.info("推送人群包，accountId:{}", accountId);
        String url = urlPath + KuaishouInterfaceConstant.POPULATION_PUSH;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", "application/json");
        JSONObject requestJson = new JSONObject();
        requestJson.put("advertiser_id", accountId);
        requestJson.put("orientation_id", populationId);
        String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            Integer code = resultJson.getInteger("code");
            return code == 0;
        }
        return false;
    }

    /**
     * 跨账户人群包推送接口
     *
     * @param populationId 人群包ID
     * @param accessToken  token
     * @param accountId    广告主ID
     * @param ids          要推送的账户ids
     * @return
     */
    @Override
    public JSONObject pushAccountsPopulation(CtopOauthToken token, Long orientationId, JSONArray accountIds) {
        log.info("推送人群包，accountId:{}", token.getAccountId());
        String url = urlPath + KuaishouInterfaceConstant.POPULATION_PUSH_ACCOUNTS;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", token.getAccessToken());
        headers.put("Content-Type", "application/json");
        JSONObject requestJson = new JSONObject();
        requestJson.put("advertiser_id", token.getAccountId());
        requestJson.put("orientation_id", orientationId);
        requestJson.put("dest_account_ids", accountIds);
        String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            return resultJson;
        }
        return null;
    }

    /**
     * 游戏精选标签人群包
     * 获取游戏精选标签所有接口类型
     *
     * @param accessToken token
     * @return
     */
    @Override
    public JSONObject selectGameTags(String accessToken) {
        String url = urlPath + KuaishouInterfaceConstant.POPULATION_GAME_TAG_LIST;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", "application/json");
        String result = HttpUtils.kuaiShouhttpPostRequest(url, null, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                return resultJson.getJSONObject("data");
            }
        }
        return null;
    }

    /**
     * 游戏精选标签人群包
     * 游戏精选标签创建
     *
     * @param accessToken token
     * @param accountId   广告主ID
     * @return
     */
    @Override
    public Long createGameTags(Long accountId, JSONObject obj, String accessToken) {
        String url = urlPath + KuaishouInterfaceConstant.POPULATION_GAME_TAG_CREATE;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", "application/json");
        JSONObject requestJson = new JSONObject();
        requestJson.put("advertiser_id", accountId);
        requestJson.put("orientation_name", obj.getString("populationName"));
        if (!Check.isNull(obj.getString("gameCategory"))) {
            requestJson.put("game_category", obj.getString("gameCategory"));
        }
        if (!Check.isNull(obj.getString("gameTheme"))) {
            requestJson.put("game_theme", obj.getString("gameTheme"));
        }
        if (!Check.isNull(obj.getString("artStyle"))) {
            requestJson.put("art_style", obj.getString("artStyle"));
        }
        if (!Check.isNull(obj.getString("payWilling"))) {
            requestJson.put("pay_willing", obj.getString("payWilling"));
        }
        if (!Check.isNull(obj.getString("activeLevel"))) {
            requestJson.put("active_level", obj.getString("activeLevel"));
        }
        String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                return resultJson.getJSONObject("data").getLong("orientation_id");
            }
        }
        return null;
    }

    /**
     * DMP更新人群包接口
     *
     * @param populationId   人群包ID
     * @param populationType 1：APPEND（增量更新）
     * @param type           人群数据类型 1：IMEI 2：IDFA 3：IMEI_MD5 4：IDFA_MD5 7：OAID 8：OAID_MD5
     * @param accessToken    token
     * @param accountId      广告主ID
     * @param file           请求的文件，最大支持500MB
     * @return
     */
    @Override
    public JSONObject updatePopulations(Long accountId, Integer type, Long populationId, Integer populationType, File file, String accessToken) {
        String url = urlPath + KuaishouInterfaceConstant.POPULATION_UPDATE;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", "application/json");
        JSONObject requestJson = new JSONObject();
        requestJson.put("advertiser_id", accountId);
        requestJson.put("type", type);
        requestJson.put("orientation_id", populationId);
        requestJson.put("operation_type", populationType);
        requestJson.put("file", file);
        String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                return resultJson.getJSONObject("data");
            }
        }
        return null;
    }

    /**
     * 获取人群预估数量
     *
     * @param accessToken token
     * @param accountId   广告主ID
     * @return
     */
    @Override
    public Long predictionPopulation(Long accountId, JSONObject obj, String accessToken) {
        String url = urlPath + KuaishouInterfaceConstant.POPULATION_PREDICTION;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", "application/json");
        JSONObject requestJson = new JSONObject();
        requestJson.put("advertiser_id", accountId);
        if (!Check.isNull(obj.getJSONArray("region"))) {
            requestJson.put("region", obj.getJSONArray("region"));
        }
        if (!Check.isNull(obj.getJSONArray("ages_range"))) {
            requestJson.put("ages_range", obj.getJSONArray("ages_range"));
        }
        if (!Check.isNull(obj.getInteger("gender"))) {
            requestJson.put("gender", obj.getInteger("gender"));
        }
        if (!Check.isNull(obj.getInteger("platform_os"))) {
            requestJson.put("platform_os", obj.getInteger("platform_os"));
        }
        if (!Check.isNull(obj.getInteger("android_osv"))) {
            requestJson.put("android_osv", obj.getInteger("android_osv"));
        }
        if (!Check.isNull(obj.getInteger("ios_osv"))) {
            requestJson.put("ios_osv", obj.getInteger("ios_osv"));
        }
        if (!Check.isNull(obj.getInteger("network"))) {
            requestJson.put("network", obj.getInteger("network"));
        }
        if (!Check.isNull(obj.getJSONArray("device_brand"))) {
            requestJson.put("device_brand", obj.getJSONArray("device_brand"));
        }
        if (!Check.isNull(obj.getJSONArray("device_price"))) {
            requestJson.put("device_price", obj.getJSONArray("device_price"));
        }
        if (!Check.isNull(obj.getInteger("business_interest_type"))) {
            requestJson.put("business_interest_type", obj.getInteger("business_interest_type"));
        }
        if (!Check.isNull(obj.getJSONArray("business_interest"))) {
            requestJson.put("business_interest", obj.getJSONArray("business_interest"));
        }
        if (!Check.isNull(obj.getJSONArray("fans_star"))) {
            requestJson.put("fans_star", obj.getJSONArray("fans_star"));
        }
        if (!Check.isNull(obj.getJSONArray("interest_video"))) {
            requestJson.put("interest_video", obj.getJSONArray("interest_video"));
        }
        if (!Check.isNull(obj.getJSONArray("app_interest"))) {
            requestJson.put("app_interest", obj.getJSONArray("app_interest"));
        }
        if (!Check.isNull(obj.getJSONArray("app_ids"))) {
            requestJson.put("app_ids", obj.getJSONArray("app_ids"));
        }
        if (!Check.isNull(obj.getJSONArray("population"))) {
            requestJson.put("population", obj.getJSONArray("population"));
        }
        if (!Check.isNull(obj.getJSONArray("exclude_population"))) {
            requestJson.put("exclude_population", obj.getJSONArray("exclude_population"));
        }
        String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                return resultJson.getJSONObject("data").getLong("audience_prediction_num");
            }
        }
        return null;
    }

    @Override
    public void replaceBatch(List<KuaishouPopulation> addList) {
        populationMapper.deleteByAccountId(addList.get(0).getAccountId());
        populationMapper.replaceBatch(addList);
    }
}
