package com.yuchen.saas.park.service.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.UUID;

@Slf4j
public class McRobotApiRequestUtil {

    // 设置请求参数
    static String appKey = "open";
    static String appSecret = "test";
    static String serviceAreaId = "159";

    static long timestamp = System.currentTimeMillis();
    static String nonce = UUID.randomUUID().toString();

    static MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    static String CREATE_ORDER_URL = "http://api.dev.bj.robot.tslsmart.com/openapi/v2/delivery/orders/accept";
    static String CANCEL_ORDER_URL = "http://api.dev.bj.robot.tslsmart.com/openapi/v2/delivery/orders/cancel";

    /*public static void main(String[] args) throws IOException {

        //Response response = getOnlineInfo("C118C2E764CEDA1B");

        //Response response = getVideoStreams("C118C2E764CEDA1B");

        //String jsonBody = "{\"loadingPointId\":\"59\",\"targetPointId\":\"60\",\"serviceAreaId\":\"159\"}";
        //Response response = createOrder(jsonBody);

//        String jsonBody = "{\"orderSn\":\"NDT2024102940130304495\"}";
//        Response response = cancelOrder(jsonBody);


        //Response response = getOrderInfo("NDT2024102940130304495");

        Response response = getPointList(serviceAreaId);

        if (response.isSuccessful()) {
            // 在这里读取响应体内容，并确保及时关闭响应体
            String responseBody = response.body().string();
            System.out.println(responseBody);
        } else {
            System.out.println("Request failed with code: " + response.code());
        }

    }*/

    /**
     * 获取机器人设备状态
     * @param robotSnCode
     * @return
     */
    public static Response getOnlineInfo(String robotSnCode) {
        try {
            // 生成签名
            String signature = generateSHA256(generateSHA256(appKey + appSecret)+ nonce + timestamp);

            // 创建 OkHttpClient 对象
            OkHttpClient client = new OkHttpClient();
            // 设置请求的 URL，这里可以根据实际情况修改
            HttpUrl url = new HttpUrl.Builder()
                    .scheme("https")
                    .host("api.dev.bj.robot.tslsmart.com")
                    .addPathSegment("openapi")
                    .addPathSegment("v2")
                    .addPathSegment("device")
                    .addPathSegment("robot")
                    .addPathSegment(robotSnCode)
                    .addPathSegment("onlineInfo")
                    // 添加参数，这里可以根据实际需求修改参数名和值
                    .addQueryParameter("robotSnCode", robotSnCode)
                    .build();

            // 创建请求对象，并添加 Header 参数
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("tsl-au-appkey", appKey)
                    .addHeader("tsl-au-timestamp", String.valueOf(timestamp))
                    .addHeader("tsl-nonce", nonce)
                    .addHeader("tsl-au-signature", signature)
                    .addHeader("Host", "api.dev.bj.robot.tslsmart.com")
                    .addHeader("Connection", "keep-alive")
                    .get()
                    .build();

            // 发送请求并获取响应
            return client.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取巡逻机器人视频流
     * @param robotSnCode
     * @return
     */
    public static Response getVideoStreams(String robotSnCode) {
        try {
            // 生成签名
            String signature = generateSHA256(generateSHA256(appKey + appSecret)+ nonce + timestamp);
            // 创建 OkHttpClient 对象
            OkHttpClient client = new OkHttpClient();
            HttpUrl url = new HttpUrl.Builder()
                    .scheme("https")
                    .host("api.dev.bj.robot.tslsmart.com")
                    .addPathSegment("openapi")
                    .addPathSegment("v2")
                    .addPathSegment("device")
                    .addPathSegment("robot")
                    .addPathSegment(robotSnCode)
                    .addPathSegment("videoStreams")
                    .addQueryParameter("robotSnCode", robotSnCode)
                    .build();

            // 创建请求对象，并添加 Header 参数
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("tsl-au-appkey", appKey)
                    .addHeader("tsl-au-timestamp", String.valueOf(timestamp))
                    .addHeader("tsl-nonce", nonce)
                    .addHeader("tsl-au-signature", signature)
                    .addHeader("Host", "api.dev.bj.robot.tslsmart.com")
                    .addHeader("Connection", "keep-alive")
                    .get()
                    .build();
            // 发送请求并获取响应
            return client.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建配送订单
     * @param jsonBody
     * @return
     */
    public static Response createOrder(String jsonBody) {
        try {
            // 生成签名
            String signature = generateSHA256(generateSHA256(appKey + appSecret)+ nonce + timestamp);

            RequestBody body = RequestBody.create(JSON, jsonBody);

            // 创建 OkHttpClient 对象
            OkHttpClient client = new OkHttpClient();

            // 创建请求对象，并添加 Header 参数
            Request request = new Request.Builder()
                    .url(CREATE_ORDER_URL)
                    .addHeader("tsl-au-appkey", appKey)
                    .addHeader("tsl-au-timestamp", String.valueOf(timestamp))
                    .addHeader("tsl-nonce", nonce)
                    .addHeader("tsl-au-signature", signature)
                    .addHeader("Host", "api.dev.bj.robot.tslsmart.com")
                    .addHeader("Connection", "keep-alive")
                    .post(body)
                    .build();

            // 发送请求并获取响应
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                log.info("====== McRobot API Request successful with code: " + response.code());
            } else {
                log.error("====== McRobot API Request failed with code: ", response.code());
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 取消配送订单
     * @param jsonBody
     * @return
     */
    public static Response cancelOrder(String jsonBody) {
        try {
            // 生成签名
            String signature = generateSHA256(generateSHA256(appKey + appSecret)+ nonce + timestamp);

            RequestBody body = RequestBody.create(JSON, jsonBody);

            // 创建 OkHttpClient 对象
            OkHttpClient client = new OkHttpClient();

            // 创建请求对象，并添加 Header 参数
            Request request = new Request.Builder()
                    .url(CANCEL_ORDER_URL)
                    .addHeader("tsl-au-appkey", appKey)
                    .addHeader("tsl-au-timestamp", String.valueOf(timestamp))
                    .addHeader("tsl-nonce", nonce)
                    .addHeader("tsl-au-signature", signature)
                    .addHeader("Host", "api.dev.bj.robot.tslsmart.com")
                    .addHeader("Connection", "keep-alive")
                    .post(body)
                    .build();
            // 发送请求并获取响应
            return client.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询配送订单详情
     * @param orderSn
     * @return
     */
    public static Response getOrderInfo(String orderSn) {
        try {
            // 生成签名
            String signature = generateSHA256(generateSHA256(appKey + appSecret)+ nonce + timestamp);
            // 创建 OkHttpClient 对象
            OkHttpClient client = new OkHttpClient();
            HttpUrl url = new HttpUrl.Builder()
                    .scheme("https")
                    .host("api.dev.bj.robot.tslsmart.com")
                    .addPathSegment("openapi")
                    .addPathSegment("v2")
                    .addPathSegment("delivery")
                    .addPathSegment("orders")
                    .addPathSegment(orderSn)
                    .build();

            // 创建请求对象，并添加 Header 参数
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("tsl-au-appkey", appKey)
                    .addHeader("tsl-au-timestamp", String.valueOf(timestamp))
                    .addHeader("tsl-nonce", nonce)
                    .addHeader("tsl-au-signature", signature)
                    .addHeader("Host", "api.dev.bj.robot.tslsmart.com")
                    .addHeader("Connection", "keep-alive")
                    .get()
                    .build();
            // 发送请求并获取响应
            return client.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询配送业务所有点位信息
     * @param serviceAreaId
     * @return
     */
    public static Response getPointList(String serviceAreaId) {
        try {
            // 生成签名
            String signature = generateSHA256(generateSHA256(appKey + appSecret)+ nonce + timestamp);
            // 创建 OkHttpClient 对象
            OkHttpClient client = new OkHttpClient();
            HttpUrl url = new HttpUrl.Builder()
                    .scheme("https")
                    .host("api.dev.bj.robot.tslsmart.com")
                    .addPathSegment("openapi")
                    .addPathSegment("v2")
                    .addPathSegment("delivery")
                    .addPathSegment("point")
                    .addPathSegment("list")
                    .setQueryParameter("serviceAreaId", serviceAreaId)
                    .build();

            // 创建请求对象，并添加 Header 参数
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("tsl-au-appkey", appKey)
                    .addHeader("tsl-au-timestamp", String.valueOf(timestamp))
                    .addHeader("tsl-nonce", nonce)
                    .addHeader("tsl-au-signature", signature)
                    .addHeader("Host", "api.dev.bj.robot.tslsmart.com")
                    .addHeader("Connection", "keep-alive")
                    .get()
                    .build();
            // 发送请求并获取响应
            return client.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密
     * @param input
     * @return
     */
    private static String generateSHA256(String input) {
        try {
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            byte[] hash = sha256.digest(input.getBytes("UTF-8"));

            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}