package com.corewing.app.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 短信宝工具类
 * 官方文档: @<a href="https://www.smsbao.com/">...</a>
 */
@Slf4j
@Component
public class SmsBaoUtil {

    @Value("${smsbao.username:}")
    private String username;

    @Value("${smsbao.password:}")
    private String password;

    /**
     * 短信宝API地址
     */
    private static final String SMS_API_URL = "http://api.smsbao.com/sms";

    /**
     * 发送短信
     *
     * @param phone   手机号
     * @param content 短信内容
     * @return 是否发送成功
     */
    public boolean sendSms(String phone, String content) {
        try {
            // URL编码
            String encodedContent = URLEncoder.encode(content, StandardCharsets.UTF_8.name());

            // 构建请求URL
            String requestUrl = String.format("%s?u=%s&p=%s&m=%s&c=%s",
                    SMS_API_URL, username, password, phone, encodedContent);

            // 发送HTTP请求
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 读取响应
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String response = reader.readLine();
            reader.close();

            // 解析响应码
            int code = Integer.parseInt(response);
            if (code == 0) {
                log.info("短信发送成功, 手机号: {}", phone);
                return true;
            } else {
                log.error("短信发送失败, 手机号: {}, 错误码: {}, 错误信息: {}",
                        phone, code, getErrorMessage(code));
                return false;
            }
        } catch (Exception e) {
            log.error("短信发送异常, 手机号: {}, 异常信息: {}", phone, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送验证码短信
     *
     * @param phone 手机号
     * @param code  验证码
     * @return 是否发送成功
     */
    public boolean sendVerifyCode(String phone, String code) {
        String content = String.format(I18nUtil.getMessage("sms.verify.code.template"), code);
        return sendSms(phone, content);
    }

    /**
     * 获取错误信息
     *
     * @param code 错误码
     * @return 错误信息
     */
    private String getErrorMessage(int code) {
        switch (code) {
            case 0:
                return I18nUtil.getMessage("sms.result.success");
            case 30:
                return I18nUtil.getMessage("sms.result.password.error");
            case 40:
                return I18nUtil.getMessage("sms.result.account.not.exist");
            case 41:
                return I18nUtil.getMessage("sms.result.balance.insufficient");
            case 42:
                return I18nUtil.getMessage("sms.result.account.expired");
            case 43:
                return I18nUtil.getMessage("sms.result.ip.restricted");
            case 50:
                return I18nUtil.getMessage("sms.result.sensitive.word");
            case 51:
                return I18nUtil.getMessage("sms.result.phone.incorrect");
            default:
                return I18nUtil.getMessage("sms.result.unknown.error");
        }
    }
}
