package cn.iocoder.byzs.module.system.controller.admin.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.util.HashMap;
import java.util.Map;

/**
 * 塞邮 SUBMAIL 短信发送 DEMO
 * 官方文档：https://www.mysubmail.com/documents/8YGXz1
 * 
 * 功能示例：
 * 1. 单条短信发送（模板变量方式）
 * 2. 短信发送状态查询
 */
public class SubmailSmsDemo {

    // ====================== 配置信息 ======================
    private static final String APP_ID = "114776";
    private static final String APP_KEY = "f52ddc825fe814f7725784ab506ee02b";
    private static final String SMS_SIGNATURE = "【北京未来山川科技】";
    private static final String PROJECT = "PNMef3";
    private static final String API_URL_XSEND = "https://api.mysubmail.com/message/xsend";
    private static final String API_URL_QUERY = "https://api.mysubmail.com/message/query";
    // =====================================================

    /**
     * 发送短信（模板方式 - XSend）
     * 使用模板ID发送短信，支持自定义模板变量
     * 
     * @param phone 接收手机号
     * @param vars 模板变量键值对
     * @return 接口返回结果
     */
    public static String sendSmsByXSend(String phone, Map<String, String> vars) {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        
        try {
            URL url = new URL(API_URL_XSEND);
            conn = (HttpURLConnection) url.openConnection();
            
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestProperty("Accept", "application/json");

            StringBuilder postData = new StringBuilder();
            postData.append("appid=").append(URLEncoder.encode(APP_ID, StandardCharsets.UTF_8));
            postData.append("&signature=").append(URLEncoder.encode(APP_KEY, StandardCharsets.UTF_8));
            postData.append("&project=").append(URLEncoder.encode(PROJECT, StandardCharsets.UTF_8));
            postData.append("&to=").append(URLEncoder.encode(phone, StandardCharsets.UTF_8));
            postData.append("&sms_signature=").append(URLEncoder.encode(SMS_SIGNATURE, StandardCharsets.UTF_8));
            
            if (vars != null && !vars.isEmpty()) {
                String varsJson = JSON.toJSONString(vars);
                postData.append("&vars=").append(URLEncoder.encode(varsJson, StandardCharsets.UTF_8));
            }

            try (OutputStream os = conn.getOutputStream()) {
                os.write(postData.toString().getBytes(StandardCharsets.UTF_8));
                os.flush();
            }

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            } else {
                reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8));
            }

            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            return result.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        } finally {
            if (reader != null) {
                try { reader.close(); } catch (Exception ignored) {}
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    /**
     * 查询短信发送状态
     * 
     * @param sendId 消息ID
     * @return 接口返回结果
     */
    public static String querySmsStatus(String sendId) {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        
        try {
            URL url = new URL(API_URL_QUERY);
            conn = (HttpURLConnection) url.openConnection();
            
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestProperty("Accept", "application/json");

            StringBuilder postData = new StringBuilder();
            postData.append("appid=").append(URLEncoder.encode(APP_ID, "UTF-8"));
            postData.append("&signature=").append(URLEncoder.encode(APP_KEY, "UTF-8"));
            postData.append("&send_id=").append(URLEncoder.encode(sendId, "UTF-8"));

            try (OutputStream os = conn.getOutputStream()) {
                os.write(postData.toString().getBytes(StandardCharsets.UTF_8));
                os.flush();
            }

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            } else {
                reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8));
            }

            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            return result.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        } finally {
            if (reader != null) {
                try { reader.close(); } catch (Exception ignored) {}
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    /**
     * 解析并打印短信发送结果
     * 
     * @param response 接口响应
     * @param action 操作描述
     */
    public static void parseAndPrintResult(String response, String action) {
        System.out.println("=== " + action + " ===");
        System.out.println("响应内容: " + response);
        System.out.println();
        
        try {
            if (response != null && response.trim().startsWith("{")) {
                JSONObject json = JSON.parseObject(response);
                String status = json.getString("status");
                
                if ("success".equals(status)) {
                    System.out.println("状态: 发送成功");
                    if (json.containsKey("send_id")) {
                        System.out.println("消息ID: " + json.getString("send_id"));
                    }
                    if (json.containsKey("fee")) {
                        System.out.println("费用: " + json.getString("fee"));
                    }
                } else {
                    System.out.println("状态: 发送失败");
                    if (json.containsKey("code")) {
                        System.out.println("错误码: " + json.getString("code"));
                    }
                    if (json.containsKey("msg")) {
                        System.out.println("错误信息: " + json.getString("msg"));
                    }
                }
            } else {
                System.out.println("格式: 非JSON响应");
            }
        } catch (Exception e) {
            System.out.println("解析失败: " + e.getMessage());
        }
        System.out.println("==========================");
        System.out.println();
    }

    public static void main(String[] args) {
        System.out.println("========== SUBMAIL 短信发送 DEMO ==========");
        System.out.println();

        // 使用模板发送短信（XSend方式）
        System.out.println("=======使用模板发送短信（XSend方式）");
        String phone = "15048629248";
        Map<String, String> vars = new HashMap<>();
        vars.put("user", "9248");
        vars.put("code", "123456");
        String response1 = sendSmsByXSend(phone, vars);
        parseAndPrintResult(response1, "XSend发送结果");

        // 查询短信状态（使用第一个发送的消息ID）
        System.out.println("=======查询短信状态");
        try {
            if (response1.trim().startsWith("{")) {
                JSONObject json = JSON.parseObject(response1);
                if ("success".equals(json.getString("status"))) {
                    String sendId = json.getString("send_id");
                    String response4 = querySmsStatus(sendId);
                    parseAndPrintResult(response4, "状态查询结果");
                }
            }
        } catch (Exception e) {
            System.out.println("查询失败: " + e.getMessage());
        }

        System.out.println("========== DEMO 执行完毕 ==========");
    }
}