<?php

namespace App\Livewire\Integrations;

use Livewire\Component;
use App\Services\KnowledgeServiceApi;
use Illuminate\Support\Facades\Log;

class KnowledgeGraphComponent extends Component
{
    public $selectedKpCode = null;
    public $graphData = [];
    public $nodes = [];
    public $edges = [];
    public $isLoading = false;
    public $showStats = false;
    public $statsData = [];

    protected $listeners = [
        'kpSelected' => 'handleKpSelected',
        'refreshGraph' => 'refreshGraph',
    ];

    public function mount($selectedKpCode = null)
    {
        $this->selectedKpCode = $selectedKpCode;
        $this->loadGraphData();
    }

    public function loadGraphData()
    {
        $this->isLoading = true;
        try {
            $service = app(KnowledgeServiceApi::class);

            // 获取完整图谱数据
            if ($this->selectedKpCode) {
                // 如果指定了知识点，获取该点的详细信息
                $nodeData = $service->getKnowledgePointDetail($this->selectedKpCode);
                $upstream = $service->getUpstreamNodes($this->selectedKpCode, 2);
                $downstream = $service->getDownstreamNodes($this->selectedKpCode, 2);

                $this->buildSelectedGraph($nodeData, $upstream, $downstream);
            } else {
                // 获取完整图谱
                $this->buildFullGraph();
            }

            // 获取统计信息
            $this->loadStatsData();

        } catch (\Exception $e) {
            Log::error('加载知识图谱失败', [
                'kp_code' => $this->selectedKpCode,
                'error' => $e->getMessage()
            ]);
            $this->dispatch('error', message: '加载知识图谱失败：' . $e->getMessage());
        }
        $this->isLoading = false;
    }

    private function buildFullGraph()
    {
        try {
            $knowledgeApiBase = config('services.knowledge_api.base_url', 'http://localhost:5011');
            $response = Http::timeout(10)
                ->get($knowledgeApiBase . '/graph/export');

            if ($response->successful()) {
                $data = $response->json();
                $this->nodes = $data['nodes'] ?? [];
                $this->edges = $data['edges'] ?? [];

                // 转换为可视化格式
                $this->graphData = $this->formatForVisualization($this->nodes, $this->edges);
            }
        } catch (\Exception $e) {
            Log::error('获取完整图谱失败', ['error' => $e->getMessage()]);
        }
    }

    private function buildSelectedGraph($nodeData, $upstream, $downstream)
    {
        // 构建以选中节点为中心的图谱
        $this->nodes = [$nodeData];
        $this->edges = [];

        // 添加上游节点
        if (isset($upstream['nodes'])) {
            $this->nodes = array_merge($this->nodes, $upstream['nodes']);
        }

        // 添加下游节点
        if (isset($downstream['nodes'])) {
            $this->nodes = array_merge($this->nodes, $downstream['nodes']);
        }

        // 转换为可视化格式
        $this->graphData = $this->formatForVisualization($this->nodes, $this->edges);
    }

    private function formatForVisualization($nodes, $edges)
    {
        $formattedNodes = [];
        $formattedEdges = [];

        foreach ($nodes as $node) {
            $formattedNodes[] = [
                'id' => $node['kp_code'],
                'label' => $node['cn_name'] ?? $node['kp_code'],
                'kp_code' => $node['kp_code'],
                'cn_name' => $node['cn_name'] ?? '',
                'en_name' => $node['en_name'] ?? '',
                'category' => $node['category'] ?? '',
                'phase' => $node['phase'] ?? '',
                'importance' => $node['importance'] ?? 0,
                'description' => $node['description'] ?? '',
                'skills_count' => count($node['skills'] ?? []),
            ];
        }

        foreach ($edges as $edge) {
            $formattedEdges[] = [
                'from' => $edge['source'],
                'to' => $edge['target'],
                'type' => $edge['relation_type'] ?? '',
                'direction' => $edge['relation_direction'] ?? '',
                'label' => $edge['description'] ?? '',
            ];
        }

        return [
            'nodes' => $formattedNodes,
            'edges' => $formattedEdges,
        ];
    }

    private function loadStatsData()
    {
        try {
            $stats = app(\App\Services\QuestionServiceApi::class)->getStatistics();
            $this->statsData = $stats['by_kp'] ?? [];

            foreach ($this->graphData['nodes'] as &$node) {
                $kpCode = $node['kp_code'];
                $node['question_count'] = $this->statsData[$kpCode] ?? 0;
                $node['skills_list'] = [];
            }
        } catch (\Exception $e) {
            Log::error('获取统计数据失败', ['error' => $e->getMessage()]);
        }
    }

    public function handleKpSelected($kpCode)
    {
        $this->selectedKpCode = $kpCode;
        $this->loadGraphData();
    }

    public function refreshGraph()
    {
        $this->loadGraphData();
    }

    public function toggleStats()
    {
        $this->showStats = !$this->showStats;
    }

    public function render()
    {
        return view('livewire.integrations.knowledge-graph-component', [
            'graphData' => $this->graphData,
        ]);
    }
}
