package com.ruoyi.web.controller.flood;

import java.net.URI;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.neo4j.GraphNode;
import com.ruoyi.system.service.IFloodKnowledgeGraphService;

/**
 * 洪水知识图谱Controller
 *
 * @author jackeyhuang
 * @version 1.0.0
 * @date 2025-01-27
 */
@RestController
@RequestMapping("/flood/graph")
public class FloodKnowledgeGraphController extends BaseController
{
    @Autowired
    private IFloodKnowledgeGraphService floodKnowledgeGraphService;

    /** Neo4j连接URI */
    @Value("${spring.data.neo4j.uri:bolt://localhost:7687}")
    private String neo4jUri;

    /**
     * 获取知识图谱数据
     */
    @PreAuthorize("@ss.hasPermi('flood:graph:list')")
    @GetMapping("/data")
    public AjaxResult getGraphData()
    {
        Map<String, Object> graphData = floodKnowledgeGraphService.getGraphData();
        return success(graphData);
    }

    /**
     * 查询节点详情
     *
     * @param nodeId 节点ID
     * @return 节点信息
     */
    @PreAuthorize("@ss.hasPermi('flood:graph:query')")
    @GetMapping("/node/{nodeId}")
    public AjaxResult getNodeInfo(@PathVariable("nodeId") Long nodeId)
    {
        GraphNode node = floodKnowledgeGraphService.getNodeById(nodeId);
        if (node == null)
        {
            return error("节点不存在");
        }
        return success(node);
    }

    /**
     * 根据标签查询节点
     *
     * @param label 节点标签
     * @return 节点列表
     */
    @PreAuthorize("@ss.hasPermi('flood:graph:query')")
    @GetMapping("/nodes/label")
    public AjaxResult getNodesByLabel(@RequestParam("label") String label)
    {
        return success(floodKnowledgeGraphService.getNodesByLabel(label));
    }

    /**
     * 根据类型查询节点
     *
     * @param type 节点类型
     * @return 节点列表
     */
    @PreAuthorize("@ss.hasPermi('flood:graph:query')")
    @GetMapping("/nodes/type")
    public AjaxResult getNodesByType(@RequestParam("type") String type)
    {
        return success(floodKnowledgeGraphService.getNodesByType(type));
    }

    /**
     * 查询两个节点之间的最短路径
     *
     * @param startNodeId 起始节点ID
     * @param endNodeId 结束节点ID
     * @param maxDepth 最大深度（默认10）
     * @return 路径信息
     */
    @PreAuthorize("@ss.hasPermi('flood:graph:query')")
    @GetMapping("/path")
    public AjaxResult findShortestPath(
        @RequestParam("startNodeId") Long startNodeId,
        @RequestParam("endNodeId") Long endNodeId,
        @RequestParam(value = "maxDepth", defaultValue = "10") int maxDepth)
    {
        Map<String, Object> path = floodKnowledgeGraphService.findShortestPath(startNodeId, endNodeId, maxDepth);
        return success(path);
    }

    /**
     * 获取所有知识图谱列表
     *
     * @return 图谱列表
     */
    @PreAuthorize("@ss.hasPermi('flood:graph:list')")
    @GetMapping("/list")
    public AjaxResult getAllGraphs()
    {
        List<Map<String, Object>> graphList = floodKnowledgeGraphService.getAllGraphs();
        return success(graphList);
    }

    /**
     * 根据图谱标识获取特定图谱数据
     *
     * @param graphKey 图谱标识（如类型：concept、location、event，或"all"表示全部）
     * @return 图谱数据
     */
    @PreAuthorize("@ss.hasPermi('flood:graph:list')")
    @GetMapping("/data/byKey")
    public AjaxResult getGraphDataByKey(@RequestParam(value = "graphKey", defaultValue = "all") String graphKey)
    {
        Map<String, Object> graphData = floodKnowledgeGraphService.getGraphDataByKey(graphKey);
        return success(graphData);
    }

    /**
     * 获取Neo4j Browser URL
     *
     * @return Neo4j Browser地址
     */
    @PreAuthorize("@ss.hasPermi('flood:graph:list')")
    @GetMapping("/browserUrl")
    public AjaxResult getNeo4jBrowserUrl()
    {
        try
        {
            // 从Neo4j URI中解析主机和端口
            URI uri = new URI(neo4jUri);
            String host = uri.getHost();
            int port = uri.getPort();
            
            // Neo4j Browser默认使用HTTP协议，端口通常是7474
            // 如果Bolt端口是7687，HTTP端口通常是7474
            int httpPort = 7474;
            if (port == 7687)
            {
                httpPort = 7474;
            }
            else if (port > 0)
            {
                // 如果配置了其他端口，尝试使用相邻的HTTP端口
                httpPort = port - 100; // 通常HTTP端口比Bolt端口小100
            }
            
            // 构建Neo4j Browser URL
            String browserUrl = "http://" + host + ":" + httpPort + "/browser";
            
            return success().put("browserUrl", browserUrl).put("host", host).put("port", httpPort);
        }
        catch (Exception e)
        {
            // 如果解析失败，返回默认地址
            return success().put("browserUrl", "http://localhost:7474/browser").put("host", "localhost").put("port", 7474);
        }
    }
}
