package com.ruoyi.web.controller.monitor;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.domain.Server;
import com.ruoyi.jarvis.service.ILogisticsService;
import com.ruoyi.jarvis.service.IWxSendService;
import com.ruoyi.jarvis.wecom.WxSendGoofishNotifyClient;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务器监控
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/monitor/server")
public class ServerController
{
    @Resource
    private ILogisticsService logisticsService;
    
    @Resource
    private IWxSendService wxSendService;

    @Resource
    private WxSendGoofishNotifyClient wxSendGoofishNotifyClient;

    /** Ollama 服务地址，用于健康检查 */
    @Value("${jarvis.ollama.base-url:http://192.168.8.34:11434}")
    private String ollamaBaseUrl;
    
    @PreAuthorize("@ss.hasPermi('monitor:server:list')")
    @GetMapping()
    public AjaxResult getInfo() throws Exception
    {
        Server server = new Server();
        server.copyTo();
        return AjaxResult.success(server);
    }
    
    /**
     * 获取服务健康度检测
     */
    @PreAuthorize("@ss.hasPermi('monitor:server:list')")
    @GetMapping("/health")
    public AjaxResult getHealth() throws Exception
    {
        Map<String, Object> healthMap = new HashMap<>();
        
        // 物流服务健康检测
        try {
            ILogisticsService.HealthCheckResult logisticsHealth = logisticsService.checkHealth();
            Map<String, Object> logisticsMap = new HashMap<>();
            logisticsMap.put("healthy", logisticsHealth.isHealthy());
            logisticsMap.put("status", logisticsHealth.getStatus());
            logisticsMap.put("message", logisticsHealth.getMessage());
            logisticsMap.put("serviceUrl", logisticsHealth.getServiceUrl());
            healthMap.put("logistics", logisticsMap);
        } catch (Exception e) {
            Map<String, Object> logisticsMap = new HashMap<>();
            logisticsMap.put("healthy", false);
            logisticsMap.put("status", "异常");
            logisticsMap.put("message", "健康检测异常: " + e.getMessage());
            logisticsMap.put("serviceUrl", "");
            healthMap.put("logistics", logisticsMap);
        }
        
        // 微信推送：不在此自动下发消息，仅展示配置地址；真实检测见 POST /monitor/server/health/wx-send-test
        Map<String, Object> wxSendMap = new HashMap<>();
        wxSendMap.put("manualOnly", true);
        wxSendMap.put("healthy", null);
        wxSendMap.put("status", "未检测");
        wxSendMap.put("message", "点击「测试」将发送一条健康检查消息（会真实推送到微信）");
        wxSendMap.put("serviceUrl", wxSendService.getHealthCheckServiceUrl());
        healthMap.put("wxSend", wxSendMap);

        // 企微闲鱼通知：仅展示接口地址；真实检测见 POST /monitor/server/health/goofish-notify-test
        Map<String, Object> goofishMap = new HashMap<>();
        goofishMap.put("manualOnly", true);
        goofishMap.put("healthy", null);
        goofishMap.put("status", "未检测");
        goofishMap.put("message", "点击「测试」将经 wxSend 向企微闲鱼应用发送一条测试文本");
        goofishMap.put("serviceUrl", wxSendGoofishNotifyClient.getGoofishPushEndpointDisplay());
        healthMap.put("goofishNotify", goofishMap);
        
        // Ollama 服务健康检测（调试用）
        try {
            String url = ollamaBaseUrl.replaceAll("/$", "") + "/api/tags";
            String result = HttpUtils.sendGet(url);
            if (result != null && !result.trim().isEmpty()) {
                JSONObject json = JSON.parseObject(result);
                if (json != null && json.containsKey("models") && !json.containsKey("error")) {
                    Map<String, Object> ollamaMap = new HashMap<>();
                    ollamaMap.put("healthy", true);
                    ollamaMap.put("status", "正常");
                    ollamaMap.put("message", "Ollama 服务可用");
                    ollamaMap.put("serviceUrl", ollamaBaseUrl);
                    healthMap.put("ollama", ollamaMap);
                } else {
                    putOllamaUnhealthy(healthMap, url, json != null && json.getString("error") != null ? json.getString("error") : "返回格式异常");
                }
            } else {
                putOllamaUnhealthy(healthMap, url, "返回为空");
            }
        } catch (Exception e) {
            putOllamaUnhealthy(healthMap, ollamaBaseUrl, "健康检测异常: " + e.getMessage());
        }
        
        return AjaxResult.success(healthMap);
    }

    /**
     * 手动测试微信推送（会真实下发一条消息）
     */
    @PreAuthorize("@ss.hasPermi('monitor:server:list')")
    @PostMapping("/health/wx-send-test")
    public AjaxResult testWxSendHealth() {
        try {
            IWxSendService.HealthCheckResult r = wxSendService.checkHealth();
            Map<String, Object> m = new HashMap<>();
            m.put("manualOnly", true);
            m.put("healthy", r.isHealthy());
            m.put("status", r.getStatus());
            m.put("message", r.getMessage());
            m.put("serviceUrl", r.getServiceUrl());
            return AjaxResult.success(m);
        } catch (Exception e) {
            Map<String, Object> m = new HashMap<>();
            m.put("manualOnly", true);
            m.put("healthy", false);
            m.put("status", "异常");
            m.put("message", "检测异常: " + e.getMessage());
            m.put("serviceUrl", wxSendService.getHealthCheckServiceUrl());
            return AjaxResult.success(m);
        }
    }

    /**
     * 手动测试企微闲鱼通知（经 wxSend POST /wx/send/goofish，与 /send/pdd 相同 vanToken + title/text/touser）
     */
    @PreAuthorize("@ss.hasPermi('monitor:server:list')")
    @PostMapping("/health/goofish-notify-test")
    public AjaxResult testGoofishNotify() {
        String err = wxSendGoofishNotifyClient.testGoofishNotify();
        Map<String, Object> m = new HashMap<>();
        m.put("manualOnly", true);
        m.put("serviceUrl", wxSendGoofishNotifyClient.getGoofishPushEndpointDisplay());
        if (err == null) {
            m.put("healthy", true);
            m.put("status", "正常");
            m.put("message", "闲鱼通知测试消息已发送");
        } else {
            m.put("healthy", false);
            m.put("status", "异常");
            m.put("message", err);
        }
        return AjaxResult.success(m);
    }
    
    private void putOllamaUnhealthy(Map<String, Object> healthMap, String url, String message) {
        Map<String, Object> ollamaMap = new HashMap<>();
        ollamaMap.put("healthy", false);
        ollamaMap.put("status", "异常");
        ollamaMap.put("message", message);
        ollamaMap.put("serviceUrl", url);
        healthMap.put("ollama", ollamaMap);
    }
}
