package com.ruoyi.database.util;

import cn.hutool.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.database.domain.ParkingBillInfo;
import com.ruoyi.database.domain.ParkingBillPaymentInfo;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
@RequiredArgsConstructor
public class HaiKangApiUtils {

    private static final String HIK_URL = "https://artemis.hikparking.com";
    private static final String client_id = "25799436";
    private static final String client_secret = "eTe6Xy6iXFUiL9v2Qa2gTjZkqVHFK5bN";
    private static final String park_code = "101CX2ALLFGY329";
    private final RedisCache redisCache;
    private static final int CONNECT_TIMEOUT = 5000; // 连接超时 5秒
    private static final int SOCKET_TIMEOUT = 10000;
    private static final String HIK_TOKEN_KEY = "HIK_TOKEN_KEY";

    private static Gson gson = new GsonBuilder().create();

    private static CloseableHttpClient createHttpClient() {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .build();

        return HttpClients.custom()
                .setDefaultRequestConfig(config)
                .build();
    }


    /**
     * 获取海康云平台accessToken
     * @return accessToken
     */
    public String getAccessToken(){
        String accessToken = redisCache.getCacheObject(HIK_TOKEN_KEY);
        if (accessToken != null) {
            return accessToken;
        }
        String hikAccessToken = getHikAccessToken();
        if (hikAccessToken == null) {
            return null;
        }
        JSONObject jsonObject = new JSONObject(hikAccessToken);
        accessToken = jsonObject.getStr("access_token");
        if (accessToken == null) {
            return null;
        }
        redisCache.setCacheObject(HIK_TOKEN_KEY, accessToken,43199, TimeUnit.SECONDS);
        return accessToken;
    }

    /**
     * 调用海康云平台
     * 获取accessToken接口
     */
    public String getHikAccessToken() {
        try (CloseableHttpClient client = createHttpClient()) {
            HttpPost httpPost = new HttpPost(HIK_URL + "/artemis/oauth/token");

            // 1. 使用List<NameValuePair>构建表单参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("client_id", client_id));
            params.add(new BasicNameValuePair("client_secret", client_secret));

            // 2. 创建UrlEncodedFormEntity
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            httpPost.setEntity(entity);

            // 3. 设置正确的Content-Type
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");

            // 4. 如果API需要Basic认证
            String auth = client_id + ":" + client_secret;
            String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
            httpPost.setHeader("Authorization", "Basic " + encodedAuth);

            try (CloseableHttpResponse response = client.execute(httpPost)) {
                HttpEntity entityResponse = response.getEntity();
                if (entityResponse != null) {
                    return EntityUtils.toString(entityResponse, "UTF-8");
                } else {
                    System.err.println("Received empty response from server");
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根据停车场编码
     * 获取停车场详情
     */
    public String getHikParkInfo(){
        try (CloseableHttpClient client = createHttpClient()) {
            HttpPost httpPost = new HttpPost(HIK_URL + "/artemis/api/v1/dealer/parkinfo/" + park_code);
            httpPost.setHeader("access_token", getAccessToken());
            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity entityResponse = response.getEntity();
            if (entityResponse != null) {
                String res = EntityUtils.toString(entityResponse, "UTF-8");
                System.out.println(res);
                return res;
            } else {
                // 处理空响应的情况
                System.err.println("Received empty response from server");
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根据车牌获取车辆停车账单
     */
    public String getParkingPaymentInfo(String plateNo){
        try (CloseableHttpClient client = createHttpClient()) {
            HttpPost httpPost = new HttpPost(HIK_URL + "/artemis/api/v1/charge/getParkingPaymentInfo");
            HashMap<String, String> map = new HashMap<>();
            map.put("plateNo", plateNo);
            String json = gson.toJson(map);
            StringEntity entity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("access_token", getAccessToken());
            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity entityResponse = response.getEntity();
            if (entityResponse != null) {
                String res = EntityUtils.toString(entityResponse, "UTF-8");
                System.out.println(res);
                return res;
            } else {
                // 处理空响应的情况
                System.err.println("Received empty response from server");
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    public String notice(ParkingBillPaymentInfo billPaymentInfo,ParkingBillInfo parkingBillInfo,int payType){
        try (CloseableHttpClient client = createHttpClient()) {
            HttpPost httpPost = new HttpPost(HIK_URL + "/artemis/api/v1/charge/payment/notice");
            HashMap<String, Object> map = new HashMap<>();
            map.put("billNo", billPaymentInfo.getBillCode());
            map.put("thirdBillNo", billPaymentInfo.getTransactionId());
            map.put("payTime", billPaymentInfo.getPayTime());
            map.put("payType", payType);
            map.put("payMoney", parkingBillInfo.getPayMoney());
            map.put("thirdUserId", billPaymentInfo.getOpenId());
            String json = gson.toJson(map);
            StringEntity entity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("access_token", getAccessToken());
            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity entityResponse = response.getEntity();
            if (entityResponse != null) {
                String res = EntityUtils.toString(entityResponse, "UTF-8");
                System.out.println(res);
                return res;
            } else {
                // 处理空响应的情况
                System.err.println("Received empty response from server");
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
