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;

@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";

    /**
     * 生成签名
     * 签名规则：md5(phone + timestamp + TOKEN)
     */
    public 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 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 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 queryResult = queryScore(phone);
            System.out.println("查询积分结果：" + queryResult);

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


            String queryResult1 = queryScore(phone);
            System.out.println("查询积分结果1：" + queryResult1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}