package com.ruoyi.front.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.logistics.config.KD100ExpressConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
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.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.List;
import java.util.Map;


@Service
public class Kuaidi100Service {
    @Autowired
     KD100ExpressConfig kd100ExpressConfig;

    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * 查询快递信息
     * @return API原始返回的JSON字符串
     */
    public String  queryExpress(Map map) throws Exception {
        // 1. 构建查询参数
        String param = "{\"com\":\"" + map.get("company") + "\",\"num\":\"" + map.get("number") + "\"}";
        // 2. 生成签名
        String sign = md5(param + kd100ExpressConfig.getAppKey() + kd100ExpressConfig.getCustomer()).toUpperCase();
        // 3. 构建请求体
        String postData = "customer=" + URLEncoder.encode(kd100ExpressConfig.getCustomer(), "UTF-8")
                + "&sign=" + URLEncoder.encode(sign, "UTF-8")
                + "&param=" + URLEncoder.encode(param, "UTF-8");

        // 4. 发送HTTP POST请求
        URL url = new URL(kd100ExpressConfig.getQueryUrl());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(10000);

        // 5. 写入请求数据
        try (OutputStream os = conn.getOutputStream()) {
            os.write(postData.getBytes(StandardCharsets.UTF_8));
            os.flush();
        }

        // 6. 读取响应结果
        int responseCode = conn.getResponseCode();
        StringBuilder response = new StringBuilder();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } else {
            throw new RuntimeException("HTTP请求失败，状态码: " + responseCode);
        }
        conn.disconnect();
        return response.toString();
    }

    /**
     * MD5加密工具方法
     */
    private static String md5(String str) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    /**
     * 查询快递100返回公司编码对应的物流公司名称
     */

    public List<Map<String, Object>> getComList(String com) {
     return    jdbcTemplate.queryForList("select  company_name from   biz_kd100_company where company_code=?",com);
    }


    /**
     * 查快递查询地图轨迹
     */
    public String queryExpresPlus(Map map)  throws Exception{
        // 1. 构建查询参数
        String param = "{\"com\":\"" + map.get("company") + "\",\"num\":\"" + map.get("number") + "\",\"from\":\"" + map.get("from") +"\",\"to\":\"" + map.get("to") + "\"}";
        // 2. 生成签名
        String sign = md5(param + kd100ExpressConfig.getAppKey() + kd100ExpressConfig.getCustomer()).toUpperCase();
        // 3. 构建请求体
        String postData = "customer=" + URLEncoder.encode(kd100ExpressConfig.getCustomer(), "UTF-8")
                + "&sign=" + URLEncoder.encode(sign, "UTF-8")
                + "&param=" + URLEncoder.encode(param, "UTF-8");

        // 4. 发送HTTP POST请求
        URL url = new URL(kd100ExpressConfig.getQueryPUrl());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(10000);

        // 5. 写入请求数据
        try (OutputStream os = conn.getOutputStream()) {
            os.write(postData.getBytes(StandardCharsets.UTF_8));
            os.flush();
        }

        // 6. 读取响应结果
        int responseCode = conn.getResponseCode();
        StringBuilder response = new StringBuilder();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } else {
            throw new RuntimeException("HTTP请求失败，状态码: " + responseCode);
        }
        conn.disconnect();
        return response.toString();
    }


    /**
     * 该接口提供智能识别姓名、电话、地址的功能，并解析地址返回对应信息
     */

    public Map queryIcrExpres(Map params) throws Exception {
        String param = "{\"content\":\"" + params.get("param")+ "\" }";
        String time= String.valueOf(Instant.now().toEpochMilli());
        // 2. 生成签名
        String sign = md5(param +time+ kd100ExpressConfig.getAppKey() + kd100ExpressConfig.getAppSecret()).toUpperCase();
        // 3. 构建请求体
        String postData = "key=" + URLEncoder.encode(kd100ExpressConfig.getAppKey(), "UTF-8")
                + "&sign=" + URLEncoder.encode(sign, "UTF-8")
                + "&t=" + time
                + "&param=" + URLEncoder.encode(param, "UTF-8");
        // 4. 发送HTTP POST请求
        URL url = new URL(kd100ExpressConfig.getQueryIcrUrl());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(10000);
        // 5. 写入请求数据
        try (OutputStream os = conn.getOutputStream()) {
            os.write(postData.getBytes(StandardCharsets.UTF_8));
            os.flush();
        }
        // 6. 读取响应结果
        int responseCode = conn.getResponseCode();
        StringBuilder response = new StringBuilder();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } else {
            throw new RuntimeException("HTTP请求失败，状态码: " + responseCode);
        }
        conn.disconnect();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = objectMapper.readValue(response.toString(), Map.class);
        return map;
    }
}
