package com.ytpm.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytpm.advertise.param.ComprehensiveReportParam;
import com.ytpm.advertise.view.ComprehensiveAppReport;
import com.ytpm.advertise.view.ComprehensiveReportView;
import com.ytpm.handle.CustomerException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Slf4j(topic = "Taku请求工具类")
public class TakuRequestUtil {

    private final static String DOMAIN = "https://openapi.toponad.com";
    public final static String CONTENT_TYPE = "application/json";
    public final static String PUBLISHER_KEY = "d4b80bef5f946f618c9e781070aedbf2b1a073d4";

    public static void main(String[] args){
//        ComprehensiveReportParam param = new ComprehensiveReportParam();
//        param.setStartdate(20250623);
//        param.setEnddate(20250624);
//        param.setTime_zone("UTC-8");
//        param.setAdsource_id_list(Collections.singletonList(9308489));
//        param.setGroup_by(Collections.singletonList("adsource"));
        JSONObject object = new JSONObject();
        object.put("start_date",20250623);
        object.put("end_date",20250624);
        object.put("currency","CNY");
        object.put("time_zone","UTC-8");

        object.put("adsource_id_list",Collections.singletonList(9308489));
//        param.setApp_id_list(Arrays.asList("a685138d49cd2d","a684009039113d"));
//        param.setGroup_by(Collections.singletonList("app"));
        String result = TakuRequestUtil.doRequest(HttpPost.METHOD_NAME, "/v3/report/tk_hour", JSON.toJSONString(object),PUBLISHER_KEY);
        ComprehensiveAppReport report = JSONObject.parseObject(result, ComprehensiveAppReport.class);
        System.err.println(result);
    }

    public static String doRequest(String httpMethod, String reqUrl, String reqBody,String takuPublicKey) {
        String result = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpRequestBase httpRequest = null;
            if (httpMethod.equals(HttpPost.METHOD_NAME)) {
                HttpPost httpPost = new HttpPost(DOMAIN+reqUrl);
                httpPost.setEntity(new StringEntity(reqBody,"utf-8")); // 兼容中文
//                httpPost.setEntity(new StringEntity(reqBody));
                httpRequest = httpPost;
            } else if (httpMethod.equals(HttpGet.METHOD_NAME)) {
                httpRequest = new HttpGet(DOMAIN+reqUrl);
            } else if(httpMethod.equals(HttpPut.METHOD_NAME)){
                HttpPut httpPut = new HttpPut(DOMAIN + reqUrl);
                httpPut.setEntity(new StringEntity(reqBody,"utf-8"));
                httpRequest = httpPut;
            }
            // create the final signature
            String contentMD5 = Objects.nonNull(reqBody)?DigestUtils.md5Hex(reqBody).toUpperCase():"";
            String nowMillis = System.currentTimeMillis() + "";
            String headerStr = "X-Up-Key:" + takuPublicKey + "\n" + "X-Up-Timestamp:" + nowMillis;
            String relativePath = new URL(DOMAIN+reqUrl).getPath();
            String finalSign = genSignature(httpMethod, contentMD5, CONTENT_TYPE, headerStr, relativePath);
            // set the headers
            httpRequest.setHeader("Content-Type", CONTENT_TYPE);
            httpRequest.setHeader("X-Up-Timestamp", nowMillis);
            httpRequest.setHeader("X-Up-Key", takuPublicKey);
            httpRequest.setHeader("X-Up-Signature", finalSign);
            log.error("尝试向{}发送请求：请求类型{}， 请求内容：{}", httpMethod, reqUrl, reqBody);
            HttpResponse response = httpClient.execute(httpRequest);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity resEntity = response.getEntity();
            result = resEntity != null ? EntityUtils.toString(resEntity, "utf-8") : "";
            log.error("result:{}", result);
            if(200!=statusCode){
                JSONObject obj = JSON.parseObject(result);
                throw new RuntimeException("错误码：" + statusCode + "\n message："+obj.getString("errors"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new CustomerException(e.getMessage());
        }
        return result;
    }

    /**
     * 获取签名
     */
    public static String genSignature(String httpMethod, String contentMD5,
                                      String contentType, String headerStr, String relativePath) {
        StringBuffer buf = new StringBuffer();
        buf.append(httpMethod).append('\n').
                append(contentMD5).append('\n').
                append(contentType).append('\n').
                append(headerStr).append('\n').
                append(relativePath);
        return DigestUtils.md5Hex(buf.toString()).toUpperCase();

    }

    public static String sendWxRequest(String httpMethod, String reqUrl, String reqBody){
        String result = null;
        try{
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpRequestBase httpRequest = null;
            if (httpMethod.equals(HttpPost.METHOD_NAME)) {
                HttpPost httpPost = new HttpPost(reqUrl);
                httpPost.setEntity(new StringEntity(reqBody,"utf-8")); // 兼容中文
//                httpPost.setEntity(new StringEntity(reqBody));
                httpRequest = httpPost;
            } else if (httpMethod.equals(HttpGet.METHOD_NAME)) {
                httpRequest = new HttpGet(reqUrl);
            }
            httpRequest.setHeader("Content-Type", CONTENT_TYPE);
            log.debug("尝试向{}发送请求：请求类型{}， 请求内容：{}", httpMethod, reqUrl, reqBody);
            HttpResponse response = httpClient.execute(httpRequest);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity resEntity = response.getEntity();
            result = resEntity != null ? EntityUtils.toString(resEntity, "utf-8") : "";
            if(200!=statusCode){
                JSONObject obj = JSON.parseObject(result);
                throw new RuntimeException("错误码：" + statusCode + "\n message："+obj.getString("errors"));
            }
            log.debug("result:{}", result);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return result;
    }
}
