package com.ruixuan.launch.unitls;

import com.alibaba.fastjson.JSONObject;
import com.ruixuan.common.utils.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class APIUtil {

    public static final String IP_PATH = "https://ad.e.kuaishou.com";

    public static JSONObject getApiResult(String apiPath, String token, Map<String, Object> param) {
        try {
            String url = IP_PATH + apiPath;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token);
            System.out.println(JSONObject.toJSON(param));//TODO
            String result = HttpUtil.httpPostRequest(url, param, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (resultJson.toString().length() < 500) {
                System.out.println(JSONObject.toJSON(resultJson)); //TODO
            }
            return resultJson;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用媒体接口异常，账户：{}，接口：{}", param.get("advertiser_id"), apiPath);
            JSONObject result = new JSONObject();
            result.put("code", -1);
            result.put("message", "调用媒体接口异常");
            return result;
        }
    }


    public static JSONObject getApiResultByGet(String apiPath, String token, JSONObject param) {
        try {
            String url = IP_PATH + apiPath;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token);
            System.out.println(JSONObject.toJSON(param)); //TODO
            String result = HttpUtil.httpGetRequest(url, headers, param);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (resultJson.toString().length() < 500) {
                System.out.println(JSONObject.toJSON(resultJson)); //TODO
            }            return resultJson;

        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用媒体接口异常，账户：{}，接口：{}", param.get("advertiser_id"), apiPath);
            JSONObject result = new JSONObject();
            result.put("code", -1);
            result.put("message", "调用媒体接口异常");
            return result;
        }
    }

}
