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

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.KuaishouTemplate;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouTemplateTarget;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouTemplateMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouTemplateService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouTemplateTargetService;
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.HashMap;
import java.util.Map;

/**
 * 快手-定向模板
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-11-09
 */
@Slf4j
@Service
public class KuaishouTemplateServiceImpl extends ServiceImpl<KuaishouTemplateMapper, KuaishouTemplate> implements IKuaishouTemplateService {
    @Autowired
    private IKuaishouTemplateTargetService templateTargetService;

    @Override
    public void getTemplateByAccountId(Long accountId, String accessToken, Integer page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.TEMPLATE_LIST;
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        param.put("page", page);
        param.put("page_size", 500);
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            Integer code = resultJson.getInteger("code");
         /*   Map<String, Object> deleteMap = new HashMap<>();
            deleteMap.put("account_id", accountId);
            this.removeByMap(deleteMap);*/
            if (code == 0) {
                JSONObject dataJson = resultJson.getJSONObject("data");
                if (Check.isNull(dataJson)) {
                    return;
                }
                JSONArray details = dataJson.getJSONArray("details");
                if (Check.isNull(details)) {
                    return;
                }
                for (int i = 0; i < details.size(); i++) {
                    JSONObject jsonObject = details.getJSONObject(i);
                    Long templateId = jsonObject.getLong("template_id");
                    KuaishouTemplate template = new KuaishouTemplate();
                    template.setId(accountId + "_" + templateId);
                    template.setAccountId(accountId);
                    template.setTemplateId(templateId);
                    template.setTemplateName(jsonObject.getString("template_name"));
                    template.setUnitCount(jsonObject.getInteger("unit_count"));
                    template.setCreateTime(jsonObject.getDate("create_time"));
                    template.setUpdateTime(jsonObject.getDate("updateTime"));
                    this.saveOrUpdate(template);
                    JSONObject targetJson = jsonObject.getJSONObject("target");
                    if (!Check.isNull(targetJson)) {
                        KuaishouTemplateTarget templateTarget = new KuaishouTemplateTarget();
                        templateTarget.setId(accountId + "_" + templateId);
                        templateTarget.setTemplateId(templateId);
                        if (!Check.isNull(targetJson.getJSONArray("region"))) {
                            templateTarget.setRegion(targetJson.getJSONArray("region").toJSONString());
                        }
                        if (!Check.isNull(targetJson.getJSONArray("district_ids"))) {
                            templateTarget.setDistrictIds(targetJson.getJSONArray("district_ids").toString());
                        }
                        if (!Check.isNull(targetJson.getInteger("user_type"))) {
                            templateTarget.setUserType(targetJson.getInteger("user_type"));
                        }
                        if (!Check.isNull(targetJson.getJSONArray("ages_range"))) {
                            templateTarget.setAgesRange(targetJson.getJSONArray("ages_range").toJSONString());
                        }
                        JSONObject ageJson = targetJson.getJSONObject("age");
                        if (!Check.isNull(ageJson)) {
                            templateTarget.setMin(ageJson.getInteger("min"));
                            templateTarget.setMax(ageJson.getInteger("max"));
                        }
                        if (!Check.isNull(targetJson.getInteger("gender"))) {
                            templateTarget.setGender(targetJson.getInteger("gender"));
                        }
                        if (!Check.isNull(targetJson.getInteger("platform_os"))) {
                            templateTarget.setPlatformOs(targetJson.getInteger("platform_os"));
                        }
                        if (!Check.isNull(targetJson.getInteger("android_osv"))) {
                            templateTarget.setAndroidOsv(targetJson.getInteger("android_osv"));
                        }
                        if (!Check.isNull(targetJson.getInteger("ios_osv"))) {
                            templateTarget.setIosOsv(targetJson.getInteger("ios_osv"));
                        }
                        if (!Check.isNull(targetJson.getInteger("network"))) {
                            templateTarget.setNetwork(targetJson.getInteger("network"));
                        }
                        if (!Check.isNull(targetJson.getInteger("filter_converted_level"))) {
                            templateTarget.setFilterConvertedLevel(targetJson.getInteger("filter_converted_level"));
                        }
                        if (!Check.isNull(targetJson.getJSONArray("device_brand"))) {
                            templateTarget.setDeviceBrand(targetJson.getJSONArray("device_brand").toJSONString());
                        }
                        if (!Check.isNull(targetJson.getJSONArray("device_price"))) {
                            templateTarget.setDevicePrice(targetJson.getJSONArray("device_price").toJSONString());
                        }
                        if (!Check.isNull(targetJson.getInteger("business_interest_type"))) {
                            templateTarget.setBusinessInterestType(targetJson.getInteger("business_interest_type"));
                        }
                        if (!Check.isNull(targetJson.getJSONArray("business_interest"))) {
                            templateTarget.setBusinessInterest(targetJson.getJSONArray("business_interest").toJSONString());
                        }
                        if (!Check.isNull(targetJson.getJSONArray("fans_star"))) {
                            templateTarget.setFansStar(targetJson.getJSONArray("fans_star").toJSONString());
                        }
                        if (!Check.isNull(targetJson.getJSONArray("interest_video"))) {
                            templateTarget.setInterestVideo(targetJson.getJSONArray("interest_video").toJSONString());
                        }
                        if (!Check.isNull(targetJson.getJSONArray("app_interest"))) {
                            templateTarget.setAppInterest(targetJson.getJSONArray("app_interest").toJSONString());
                        }
                        if (!Check.isNull(targetJson.getJSONArray("app_ids"))) {
                            templateTarget.setAppIds(targetJson.getJSONArray("app_ids").toJSONString());
                        }
                        if (!Check.isNull(targetJson.getJSONArray("population"))) {
                            templateTarget.setPopulation(targetJson.getJSONArray("population").toJSONString());
                        }
                        if (!Check.isNull(targetJson.getJSONArray("paid_audience"))) {
                            templateTarget.setPaidAudience(targetJson.getJSONArray("paid_audience").toJSONString());
                        }
                        if (!Check.isNull(targetJson.getJSONArray("exclude_population"))) {
                            templateTarget.setExcludePopulation(targetJson.getJSONArray("exclude_population").toJSONString());
                        }
                        JSONObject intelliExtendJson = targetJson.getJSONObject("intelli_extend");
                        if (!Check.isNull(intelliExtendJson)) {
                            if (!Check.isNull(intelliExtendJson.getInteger("is_open"))) {
                                templateTarget.setIsOpen(intelliExtendJson.getInteger("is_open"));
                            }
                            if (!Check.isNull(intelliExtendJson.getInteger("no_age_break"))) {
                                templateTarget.setNoAgeBreak(intelliExtendJson.getInteger("no_age_break"));
                            }
                            if (!Check.isNull(intelliExtendJson.getInteger("no_gender_break"))) {
                                templateTarget.setNoGenderBreak(intelliExtendJson.getInteger("no_gender_break"));
                            }
                            if (!Check.isNull(intelliExtendJson.getInteger("no_area_break"))) {
                                templateTarget.setNoAreaBreak(intelliExtendJson.getInteger("no_area_break"));
                            }
                        }
                        templateTargetService.saveOrUpdate(templateTarget);
                    }

                }

                getTemplateByAccountId(accountId, accessToken, page + 1);
            } else {
                log.error("获取模板信息返回信息错误：accountId：{}，返回信息：{}", accountId, resultJson);


            }


        } else {
            log.error("获取模板信息返回信息为空：accountId：{}", accountId);
        }


    }


    /**
     * 创建定向模板
     *
     * @param accountId
     * @param accessToken
     * @param requestJson
     * @return
     */
    @Override
    public JSONObject createTemplate(Long accountId, String accessToken, JSONObject requestJson) {
        JSONObject returnJson = new JSONObject();

        try {
            if (Check.isNull(requestJson.getString("templateName"))) {
                throw new Exception("定向模板名称为必传项");
            }

            JSONObject param = new JSONObject();
            param.put("advertiser_id", accountId);
            param.put("template_name", requestJson.getString("templateName"));
            JSONObject targetJson = new JSONObject();
            if (!Check.isNull(requestJson.getJSONArray("region"))) {
                targetJson.put("region", requestJson.getJSONArray("region"));
            }
            if (!Check.isNull(requestJson.getJSONArray("districtIds"))) {
                targetJson.put("district_ids", requestJson.getJSONArray("districtIds"));
            }
            if (!Check.isNull(requestJson.getInteger("userType"))) {
                targetJson.put("user_type", requestJson.getInteger("userType"));
            }
            if (!Check.isNull(requestJson.getJSONArray("agesRange"))) {
                targetJson.put("ages_range", requestJson.getJSONArray("agesRange"));
            }

            JSONObject ageJson = new JSONObject();
            if (!Check.isNull(requestJson.getInteger("min"))) {
                ageJson.put("min", requestJson.getInteger("min"));
            }
            if (!Check.isNull(requestJson.getInteger("max"))) {
                ageJson.put("max", requestJson.getInteger("max"));
            }
            if (!Check.isNull(ageJson)) {
                targetJson.put("age", ageJson);
            }

            if (!Check.isNull(requestJson.getInteger("gender"))) {
                targetJson.put("gender", requestJson.getInteger("gender"));
            }
            if (!Check.isNull(requestJson.getInteger("platformOs"))) {
                targetJson.put("platform_os", requestJson.getInteger("platformOs"));
            }
            if (!Check.isNull(requestJson.getInteger("androidOsv"))) {
                targetJson.put("android_osv", requestJson.getInteger("androidOsv"));
            }
            if (!Check.isNull(requestJson.getInteger("iosOsv"))) {
                targetJson.put("ios_osv", requestJson.getInteger("iosOsv"));
            }
            if (!Check.isNull(requestJson.getInteger("network"))) {
                targetJson.put("network", requestJson.getInteger("network"));
            }
            if (!Check.isNull(requestJson.getInteger("filterConvertedLevel"))) {
                targetJson.put("filter_converted_level", requestJson.getInteger("filterConvertedLevel"));
            }
            if (!Check.isNull(requestJson.getJSONArray("deviceBrand"))) {
                targetJson.put("device_brand", requestJson.getJSONArray("deviceBrand"));
            }
            if (!Check.isNull(requestJson.getJSONArray("devicePrice"))) {
                targetJson.put("device_price", requestJson.getJSONArray("devicePrice"));
            }
            if (!Check.isNull(requestJson.getInteger("businessInterestType"))) {
                targetJson.put("business_interest_type", requestJson.getInteger("businessInterestType"));
            }
            if (!Check.isNull(requestJson.getJSONArray("businessInterest"))) {
                targetJson.put("business_interest", requestJson.getJSONArray("businessInterest"));
            }
            if (!Check.isNull(requestJson.getJSONArray("fansStar"))) {
                targetJson.put("fans_star", requestJson.getJSONArray("fansStar"));
            }
            if (!Check.isNull(requestJson.getJSONArray("interestVideo"))) {
                targetJson.put("interest_video", requestJson.getJSONArray("interestVideo"));
            }
            if (!Check.isNull(requestJson.getJSONArray("appInterest"))) {
                targetJson.put("app_interest", requestJson.getJSONArray("appInterest"));
            }
            if (!Check.isNull(requestJson.getJSONArray("appIds"))) {
                targetJson.put("app_ids", requestJson.getJSONArray("appIds"));
            }
            if (!Check.isNull(requestJson.getJSONArray("population"))) {
                targetJson.put("population", requestJson.getJSONArray("population"));
            }
            if (!Check.isNull(requestJson.getJSONArray("paidAudience"))) {
                targetJson.put("paid_audience", requestJson.getJSONArray("paidAudience"));
            }
            if (!Check.isNull(requestJson.getJSONArray("excludePopulation"))) {
                targetJson.put("exclude_population", requestJson.getJSONArray("excludePopulation"));
            }
            JSONObject intelliExtendJson = new JSONObject();

            if (!Check.isNull(requestJson.getInteger("isOpen"))) {
                intelliExtendJson.put("is_open", requestJson.getInteger("isOpen"));
            }
            if (!Check.isNull(requestJson.getInteger("noAgeBreak"))) {
                intelliExtendJson.put("no_age_break", requestJson.getInteger("noAgeBreak"));
            }
            if (!Check.isNull(requestJson.getInteger("noGenderBreak"))) {
                intelliExtendJson.put("no_gender_break", requestJson.getInteger("noGenderBreak"));
            }
            if (!Check.isNull(requestJson.getInteger("noAreaBreak"))) {
                intelliExtendJson.put("no_area_break", requestJson.getInteger("noAreaBreak"));
            }
            if (!Check.isNull(intelliExtendJson)) {
                targetJson.put("intelli_extend", intelliExtendJson);
            }
            if (!Check.isNull(targetJson)) {
                param.put("target", targetJson);
            }

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

            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.TEMPLATE_CREATE;

            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);

            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    getTemplateByAccountId(accountId, accessToken, 1);
                    returnJson.put("code", 0);
                    JSONObject data = resultJson.getJSONObject("data");
                    returnJson.put("templateId", data.getLong("template_id"));

                } else {
                    returnJson.put("code", -1);
                    returnJson.put("message", returnJson.getString("message"));
                }
            } else {
                returnJson.put("code", -1);
                returnJson.put("message", "返回结果为空");
            }


        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    /**
     * 修改定向模板
     *
     * @param accountId
     * @param accessToken
     * @param requestJson
     * @return
     */
    @Override
    public JSONObject updateTemplate(Long accountId, String accessToken, JSONObject requestJson) {
        System.err.println(requestJson);
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(requestJson.getString("templateName"))) {
                throw new Exception("定向模板名称为必传项");
            }
            if (Check.isNull(requestJson.getLong("templateId"))) {
                throw new Exception("定向模板id为必传项");
            }

            JSONObject param = new JSONObject();
            param.put("template_id", requestJson.getLong("templateId"));
            param.put("advertiser_id", accountId);
            if (!Check.isNull(requestJson.getString("templateName"))) {
                param.put("template_name", requestJson.getString("templateName"));
            }
            JSONObject targetJson = new JSONObject();
            if (!Check.isNull(requestJson.getJSONArray("region"))) {
                targetJson.put("region", requestJson.getJSONArray("region"));
            }
            if (!Check.isNull(requestJson.getJSONArray("districtIds"))) {
                targetJson.put("district_ids", requestJson.getJSONArray("districtIds"));
            }
            if (!Check.isNull(requestJson.getInteger("userType"))) {
                targetJson.put("user_type", requestJson.getInteger("userType"));
            }
            if (!Check.isNull(requestJson.getJSONArray("agesRange"))) {
                targetJson.put("ages_range", requestJson.getJSONArray("agesRange"));
            }


            if (!Check.isNull(requestJson.getInteger("min")) && !Check.isNull(requestJson.getInteger("max"))) {
                JSONObject ageJson = new JSONObject();
                ageJson.put("min", requestJson.getInteger("min"));
                ageJson.put("max", requestJson.getInteger("max"));
                targetJson.put("age", ageJson);
            }

            if (!Check.isNull(requestJson.getInteger("gender"))) {
                targetJson.put("gender", requestJson.getInteger("gender"));
            }
            if (!Check.isNull(requestJson.getInteger("platformOs"))) {
                targetJson.put("platform_os", requestJson.getInteger("platformOs"));
            }
            if (!Check.isNull(requestJson.getInteger("androidOsv"))) {
                targetJson.put("android_osv", requestJson.getInteger("androidOsv"));
            }
            if (!Check.isNull(requestJson.getInteger("iosOsv"))) {
                targetJson.put("ios_osv", requestJson.getInteger("iosOsv"));
            }
            if (!Check.isNull(requestJson.getInteger("network"))) {
                targetJson.put("network", requestJson.getInteger("network"));
            }
            if (!Check.isNull(requestJson.getInteger("filterConvertedLevel"))) {
                targetJson.put("filter_converted_level", requestJson.getInteger("filterConvertedLevel"));
            }
            if (!Check.isNull(requestJson.getJSONArray("deviceBrand"))) {
                targetJson.put("device_brand", requestJson.getJSONArray("deviceBrand"));
            }
            if (!Check.isNull(requestJson.getJSONArray("devicePrice"))) {
                targetJson.put("device_price", requestJson.getJSONArray("devicePrice"));
            }
            if (!Check.isNull(requestJson.getInteger("businessInterestType"))) {
                targetJson.put("business_interest_type", requestJson.getInteger("businessInterestType"));
            }
            if (!Check.isNull(requestJson.getJSONArray("businessInterest"))) {
                targetJson.put("business_interest", requestJson.getJSONArray("businessInterest"));
            }
            if (!Check.isNull(requestJson.getJSONArray("fansStar"))) {
                targetJson.put("fans_star", requestJson.getJSONArray("fansStar"));
            }
            if (!Check.isNull(requestJson.getJSONArray("interestVideo"))) {
                targetJson.put("interest_video", requestJson.getJSONArray("interestVideo"));
            }
            if (!Check.isNull(requestJson.getJSONArray("appInterest"))) {
                targetJson.put("app_interest", requestJson.getJSONArray("appInterest"));
            }
            if (!Check.isNull(requestJson.getJSONArray("appIds"))) {
                targetJson.put("app_ids", requestJson.getJSONArray("appIds"));
            }
            if (!Check.isNull(requestJson.getJSONArray("population"))) {
                targetJson.put("population", requestJson.getJSONArray("population"));
            }
            if (!Check.isNull(requestJson.getJSONArray("paidAudience"))) {
                targetJson.put("paid_audience", requestJson.getJSONArray("paidAudience"));
            }
            if (!Check.isNull(requestJson.getJSONArray("excludePopulation"))) {
                targetJson.put("exclude_population", requestJson.getJSONArray("excludePopulation"));
            }


            if (!Check.isNull(requestJson.getInteger("isOpen"))) {
                JSONObject intelliExtendJson = new JSONObject();
                intelliExtendJson.put("is_open", requestJson.getInteger("isOpen"));

                if (!Check.isNull(requestJson.getInteger("noAgeBreak"))) {
                    intelliExtendJson.put("no_age_break", requestJson.getInteger("noAgeBreak"));
                }
                if (!Check.isNull(requestJson.getInteger("noGenderBreak"))) {
                    intelliExtendJson.put("no_gender_break", requestJson.getInteger("noGenderBreak"));
                }
                if (!Check.isNull(requestJson.getInteger("noAreaBreak"))) {
                    intelliExtendJson.put("no_area_break", requestJson.getInteger("noAreaBreak"));
                }
                if (!Check.isNull(intelliExtendJson)) {
                    targetJson.put("intelli_extend", intelliExtendJson);
                }

            }

            if (!Check.isNull(targetJson)) {
                param.put("target", targetJson);
            }
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.TEMPLATE_UPDATE;
            System.err.println("入参：" + param);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    getTemplateByAccountId(accountId, accessToken, 1);
                    returnJson.put("code", 0);
                    JSONObject data = resultJson.getJSONObject("data");
                    if (!Check.isNull(data)) {
                        returnJson.put("templateId", data.getLong("template_id"));
                    }
                } else {
                    log.error("修改失败：{}", resultJson);
                    returnJson.put("code", -1);
                    returnJson.put("message", resultJson.getString("message"));
                }
            } else {
                returnJson.put("code", -1);
                returnJson.put("message", "返回结果为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }
}
