package cn.com.ctop.toutiao.modules.adlab.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.toutiao.modules.adlab.constants.CreateProjectUrlConstant;
import cn.com.ctop.toutiao.modules.adlab.service.ICreateProjectService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * Created by JQ.bi on 2020.09.02
 */
@Slf4j
@Service
public class CreateProjectServiceImpl implements ICreateProjectService {

    @Override
    public JSONObject createGroup(CtopOauthToken oauthToken, JSONObject requestBody) {

        //请求头**
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", oauthToken.getAccessToken());
        //请求参数
        JSONObject params = new JSONObject();
        params.put("advertiser_id", requestBody.getLong("accountId"));
        params.put("name", requestBody.getString("name"));
        //暂时写死，只有项目网服定制
        params.put("scenario", "INTERNET_SERVICE");
        params.put("ad_target", requestBody.getString("adTarget"));
        params.put("delivery_range", requestBody.getString("deliveryRange") == null ? "DEFAULT" : requestBody.getString("deliveryRange"));
        params.put("landing_type", requestBody.getString("landingType"));

        return JSONObject.parseObject(HttpUtils.httpPostRequest(CreateProjectUrlConstant.ADLAB_GROUP_CREATE, params, headers));
    }

    @Override
    public JSONObject updateGroupConvert(CtopOauthToken oauthToken, Map<String, Object> requestBody) {

        //请求头**
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", oauthToken.getAccessToken());
        //请求参数
        JSONObject params = new JSONObject();
        params.put("advertiser_id", requestBody.get("accountId"));
        params.put("group_id", requestBody.get("groupId"));
        params.put("platform", requestBody.get("platform"));
        params.put("url", requestBody.get("url"));
        params.put("download_mode", requestBody.get("download_mode") == null ? "DEFAULT" : requestBody.get("download_mode"));
        params.put("package", requestBody.get("adlabPackage"));
        params.put("web_url", requestBody.get("webUrl"));
        params.put("convert_id", requestBody.get("convertId"));
        params.put("open_url", requestBody.get("openUrl"));
        params.put("download_type", requestBody.get("downloadType"));
        params.put("app_type", requestBody.get("appType"));

        return JSONObject.parseObject(HttpUtils.httpPostRequest(CreateProjectUrlConstant.ADLAB_GROUP_CONVERT_UPDATE, params, headers));

    }

    @Override
    public JSONObject updateGroupAudience(CtopOauthToken oauthToken, Map<String, Object> requestBody) {

        //请求头**
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", oauthToken.getAccessToken());
        //请求参数
        JSONObject params = new JSONObject();
        params.put("advertiser_id", requestBody.get("accountId"));
        params.put("group_id", requestBody.get("groupId"));
        params.put("inventory_type", requestBody.get("inventoryType"));
        //投放范围为穿山甲时可选 ORIGINAL_VIDEO 表示原生，REWARDED_VIDEO 表示激励视频
        if ("UNION".equals(requestBody.get("deliveryRange"))) {
            params.put("union_video_type", requestBody.get("unionVideoType"));
        }
        //定向信息
        params.put("audience", requestBody.get("audience"));
        params.put("inventory_types", requestBody.get("inventoryTypes"));

        return JSONObject.parseObject(HttpUtils.httpPostRequest(CreateProjectUrlConstant.ADLAB_GROUP_AUDIENCE_UPDATE, params, headers));
    }

    @Override
    public JSONObject updateGroupCreative(CtopOauthToken oauthToken, Map<String, Object> requestBody) {

        //请求头**
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", oauthToken.getAccessToken());
        log.info(oauthToken.getAccessToken());
        //请求参数
        JSONObject params = new JSONObject();
        params.put("advertiser_id", requestBody.get("accountId"));
        params.put("group_id", requestBody.get("groupId"));
        params.put("image_info", requestBody.get("imageInfo"));
        params.put("video_info", requestBody.get("videoInfo"));
        params.put("title", requestBody.get("title"));
        params.put("app_name", requestBody.get("appName"));
        params.put("source", requestBody.get("source"));
        params.put("is_follow_material", requestBody.get("isFollowMaterial"));
        params.put("third_industry_id", requestBody.get("thirdIndustryId"));
        params.put("ad_keywords", requestBody.get("adKeywords"));
        params.put("playable_url", requestBody.get("playableUrl"));
        params.put("action_track_url", requestBody.get("actionTrackUrl"));
        params.put("track_url", requestBody.get("trackUrl"));
        if (!"UNION".equals(requestBody.get("deliveryRange"))) {
            params.put("video_play_track_url", requestBody.get("videoPlayTrackUrl"));
            params.put("video_play_done_track_url", requestBody.get("videoPlayDoneTrackUrl"));
            params.put("video_play_effective_track_url", requestBody.get("videoPlayEffectiveTrackUrl"));
        }
        params.put("creative_auto_generate_switch", requestBody.get("creativeAutoGenerateSwitch"));
        log.info(params.toJSONString());
        return JSONObject.parseObject(HttpUtils.httpPostRequest(CreateProjectUrlConstant.ADLAB_GROUP_CREATIVE_UPDATE, params, headers));
    }

    @Override
    public JSONObject updateGroupBudget(CtopOauthToken oauthToken, Map<String, Object> requestBody) {

        //请求头**
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", oauthToken.getAccessToken());
        //请求参数
        JSONObject params = new JSONObject();
        params.put("advertiser_id", requestBody.get("accountId"));
        params.put("group_id", requestBody.get("groupId"));
        params.put("bid", requestBody.get("bid"));
        params.put("budget_mode", requestBody.get("budgetMode") == null ? "DAILY" : requestBody.get("budgetMode"));
        params.put("budget", requestBody.get("budget"));
        params.put("auto_stop", requestBody.get("autoStop") == null ? 0 : requestBody.get("autoStop"));
        params.put("deep_bid", requestBody.get("deepBid"));
        params.put("start_time", requestBody.get("startTime"));
        params.put("end_time", requestBody.get("endTime"));
        //weekTime字段需要处理为number[number[]]
        params.put("week_time", weekTimeHandle((String) requestBody.get("weekTime")));

        return JSONObject.parseObject(HttpUtils.httpPostRequest(CreateProjectUrlConstant.ADLAB_GROUP_BUDGET_UPDATE, params, headers));
    }

    private List<List<Integer>> weekTimeHandle(String weekTime) {
        List<List<Integer>> weekTime2List = null;
        if (!weekTime.isEmpty() || (weekTime.contains("0") && weekTime.contains("1"))) {
            weekTime2List = weekTime2List = new ArrayList();
            char[] chars = weekTime.toCharArray();
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < chars.length; i++) {
                if ((i + 1) % 48 == 0) {
                    if (chars[i] == '1') {
                        temp.add(i % 48);
                    }
                    weekTime2List.add(temp);
                    temp = new ArrayList<>();
                } else {
                    if (chars[i] == '1') {
                        temp.add(i % 48);
                    }
                }
            }
        }
        return weekTime2List;
    }
}
