package com.ruoyi.jarvis.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.jarvis.service.IWxSendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * 微信推送服务实现类
 */
@Service
public class WxSendServiceImpl implements IWxSendService {
    private static final Logger logger = LoggerFactory.getLogger(WxSendServiceImpl.class);
    
    private static final String PUSH_TOKEN = "super_token_b62190c26";
    
    @Value("${jarvis.server.wxsend.base-url:https://wxts.van333.cn}")
    private String wxSendBaseUrl;
    
    @Value("${jarvis.server.wxsend.health-path:/wx/send/jd}")
    private String wxSendHealthPath;
    
    private String healthCheckUrl;
    
    @PostConstruct
    public void init() {
        healthCheckUrl = wxSendBaseUrl + wxSendHealthPath;
        logger.info("微信推送服务健康检查地址已初始化: {}", healthCheckUrl);
    }

    @Override
    public String getHealthCheckServiceUrl() {
        return healthCheckUrl;
    }
    
    @Override
    public IWxSendService.HealthCheckResult checkHealth() {
        try {
            logger.debug("开始检查微信推送服务健康状态 - URL: {}", healthCheckUrl);
            
            // 构建健康检查请求，发送一条真实的消息
            // /send/jd 接口只需要 text 字段，vanToken 在 header 中传递
            JSONObject testRequest = new JSONObject();
            testRequest.put("text", "【系统健康检查】微信推送服务运行正常 - " + new java.util.Date());
            
            String jsonBody = testRequest.toJSONString();
            
            // 发送POST请求进行健康检查
            String healthResult = sendPostWithHeaders(healthCheckUrl, jsonBody, PUSH_TOKEN);
            
            if (healthResult == null || healthResult.trim().isEmpty()) {
                logger.warn("微信推送服务健康检查返回空结果");
                return new IWxSendService.HealthCheckResult(false, "异常", "健康检查返回空结果", healthCheckUrl);
            }
            
            // 尝试解析JSON响应
            try {
                JSONObject response = JSON.parseObject(healthResult);
                if (response != null) {
                    Integer code = response.getInteger("code");
                    Boolean success = response.getBoolean("success");
                    String msg = response.getString("msg");
                    
                    // 检查是否成功（code为200或0，或者success为true）
                    if ((code != null && (code == 200 || code == 0)) || Boolean.TRUE.equals(success)) {
                        logger.debug("微信推送服务健康检查通过，消息已发送");
                        return new IWxSendService.HealthCheckResult(true, "正常", "服务运行正常，健康检查消息已发送", healthCheckUrl);
                    } else {
                        // 检查是否是token验证失败（说明服务可用，只是token问题）
                        if (msg != null && (msg.contains("vanToken") || msg.contains("token"))) {
                            logger.debug("微信推送服务健康检查通过（服务可用，token验证失败）");
                            return new IWxSendService.HealthCheckResult(true, "正常", "服务运行正常（token验证失败）", healthCheckUrl);
                        }
                        logger.warn("微信推送服务健康检查失败 - 响应: {}", healthResult);
                        return new IWxSendService.HealthCheckResult(false, "异常", "健康检查返回异常状态: " + (msg != null ? msg : healthResult), healthCheckUrl);
                    }
                }
            } catch (Exception e) {
                // 如果不是JSON格式，检查是否包含成功标识
                String lowerResult = healthResult.toLowerCase();
                if (lowerResult.contains("ok") || lowerResult.contains("success") || lowerResult.contains("正常")) {
                    logger.debug("微信推送服务健康检查通过（非JSON格式）");
                    return new IWxSendService.HealthCheckResult(true, "正常", "服务运行正常", healthCheckUrl);
                }
            }
            
            logger.warn("微信推送服务健康检查失败 - 响应: {}", healthResult);
            return new IWxSendService.HealthCheckResult(false, "异常", "健康检查返回异常状态: " + healthResult, healthCheckUrl);
            
        } catch (Exception e) {
            logger.error("微信推送服务健康检查异常 - URL: {}, 错误: {}", healthCheckUrl, e.getMessage(), e);
            return new IWxSendService.HealthCheckResult(false, "异常", "健康检查异常: " + e.getMessage(), healthCheckUrl);
        }
    }
    
    /**
     * 发送POST请求，支持自定义header（用于健康检查）
     * @param url 请求URL
     * @param jsonBody JSON请求体
     * @param token 认证token
     * @return 响应结果
     */
    private String sendPostWithHeaders(String url, String jsonBody, String token) {
        java.io.BufferedReader in = null;
        java.io.PrintWriter out = null;
        StringBuilder result = new StringBuilder();
        try {
            java.net.URL realUrl = new java.net.URL(url);
            java.net.URLConnection conn = realUrl.openConnection();
            
            // 设置请求头
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("vanToken", token);
            conn.setRequestProperty("source", "XZJ_UBUNTU");
            
            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            // 设置超时时间（健康检查需要快速响应）
            conn.setConnectTimeout(5000); // 5秒连接超时
            conn.setReadTimeout(5000); // 5秒读取超时
            
            // 发送请求体
            out = new java.io.PrintWriter(conn.getOutputStream());
            out.print(jsonBody);
            out.flush();
            
            // 读取响应
            in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(), java.nio.charset.StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            
            logger.debug("微信推送服务健康检查请求成功 - URL: {}, 响应: {}", url, result.toString());
        } catch (java.net.ConnectException e) {
            logger.error("微信推送服务健康检查连接失败 - URL: {}", url, e);
            throw new RuntimeException("健康检查连接失败: " + e.getMessage(), e);
        } catch (java.net.SocketTimeoutException e) {
            logger.error("微信推送服务健康检查超时 - URL: {}", url, e);
            throw new RuntimeException("健康检查请求超时: " + e.getMessage(), e);
        } catch (java.io.IOException e) {
            logger.error("微信推送服务健康检查IO异常 - URL: {}", url, e);
            throw new RuntimeException("健康检查IO异常: " + e.getMessage(), e);
        } catch (Exception e) {
            logger.error("微信推送服务健康检查异常 - URL: {}", url, e);
            throw new RuntimeException("健康检查异常: " + e.getMessage(), e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (java.io.IOException ex) {
                logger.error("关闭流异常", ex);
            }
        }
        return result.toString();
    }
}

