package com.ruoyi.database.service;

import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;

@Service
public class ParkingPointsService {

    // 常量定义
    private static final String TOKEN = "VAR21UEUjhHmeMqiAvA7VYvQLPn5rO2z";
    private static final String QUERY_SCORE_URL = "https://yxphp.ckldzsw.com/index/score/search";
    private static final String PAY_SCORE_URL = "https://yxphp.ckldzsw.com/index/score/reduce";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 生成签名
     * 签名规则：md5(phone + timestamp + TOKEN)
     */
    public static String generateSign(String phone, String timestamp) throws NoSuchAlgorithmException {
        String data = phone + timestamp + TOKEN;
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(data.getBytes());
        byte[] digest = md.digest();
        StringBuilder hexString = new StringBuilder();
        for (byte b : digest) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    /**
     * 查询积分
     */
    public static String queryScore(String phone) throws Exception {
        // 生成时间戳（Unix时间戳，秒级）
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        // 生成签名
        String sign = generateSign(phone, timestamp);

        // 构建请求参数
        String params = "phone=" + phone + "&timestamp=" + timestamp + "&sign=" + sign;

        // 发送POST请求
        HttpURLConnection conn = (HttpURLConnection) new URL(QUERY_SCORE_URL).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        try (OutputStream os = conn.getOutputStream()) {
            os.write(params.getBytes());
            os.flush();
        }

        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
        }

        return response.toString();
    }

    /**
     * 停车积分支付
     */
    public static String payScore(String phone, int money) throws Exception {
        // 生成时间戳（Unix时间戳，秒级）
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        // 生成签名
        String sign = generateSign(phone, timestamp);

        // 构建请求参数
        String params = "phone=" + phone + "&timestamp=" + timestamp + "&sign=" + sign + "&money=" + money;

        // 发送POST请求
        HttpURLConnection conn = (HttpURLConnection) new URL(PAY_SCORE_URL).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        try (OutputStream os = conn.getOutputStream()) {
            os.write(params.getBytes());
            os.flush();
        }

        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
        }

        return response.toString();
    }

    public static void main(String[] args) {
        try {
            // 示例：查询积分
//            String phone = "15599026928";
            String phone = "13151593507";
            String queryResult = queryScore(phone);
            System.out.println("查询积分结果：" + queryResult);
            Map<String, Object> stringObjectMap = parseResponseToMap(queryResult);
            System.out.println(stringObjectMap);

            // 示例：停车积分支付（支付1积分）
            String payResult = payScore(phone, 0);
            System.out.println("停车积分支付结果：" + payResult);
            Map<String, Object> stringObjectMap1 = parseResponseToMap(payResult);
            System.out.println(stringObjectMap1);

            String queryResult1 = queryScore(phone);
            System.out.println("查询积分结果1：" + queryResult1);
            Map<String, Object> stringObjectMap2 = parseResponseToMap(queryResult1);
            System.out.println(stringObjectMap2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static Map<String, Object> parseResponseToMap(Object response) {
        try {
            // 如果response本身就是Map类型
            if (response instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> map = (Map<String, Object>) response;
                return map;
            }

            // 如果response有toMap或asMap方法（假设）
            try {
                java.lang.reflect.Method method = response.getClass()
                        .getMethod("toMap");
                if (Map.class.isAssignableFrom(method.getReturnType())) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> map = (Map<String, Object>) method.invoke(response);
                    return map;
                }
            } catch (NoSuchMethodException e) {
                // 方法不存在，继续尝试其他方式
            }

            // 尝试JSON解析
            String jsonString = response.toString();
            return objectMapper.readValue(jsonString,
                    new TypeReference<Map<String, Object>>() {});

        } catch (Exception e) {
            throw new RuntimeException("Failed to parse response to Map", e);
        }
    }
}