<?php

namespace App\Livewire\Integrations;

use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class KnowledgePointDetails extends Component
{
    public $selectedNode = null;
    public $nodeDetails = null;
    public $isLoading = false;
    public $activeTab = 'overview'; // 'overview', 'children', 'skills'

    protected $listeners = [
        'nodeDetailsLoaded' => 'handleNodeDetailsLoaded',
        'nodeDetailsCleared' => 'handleNodeDetailsCleared',
        'kpSelected' => 'handleKpSelected',
    ];

    public function handleNodeDetailsLoaded($details)
    {
        $this->nodeDetails = $details;
        $this->selectedNode = $details;
        $this->activeTab = 'overview';
    }

    public function handleNodeDetailsCleared()
    {
        $this->nodeDetails = null;
        $this->selectedNode = null;
    }

    public function handleKpSelected($kpCode)
    {
        $this->selectedNode = $kpCode;
        $this->loadNodeDetails($kpCode);
    }

    private function loadNodeDetails($kpCode)
    {
        $this->isLoading = true;
        try {
            // 从知识图谱服务获取节点详情
            $knowledgeApiBase = config('services.knowledge_api.base_url', 'http://localhost:5011');

            // 获取节点基本信息
            $detailResponse = Http::timeout(10)
                ->get($knowledgeApiBase . "/knowledge-points/{$kpCode}");

            if ($detailResponse->successful()) {
                $detail = $detailResponse->json();

                // 获取上游和下游节点（一级子知识点）
                $upstreamResponse = Http::timeout(10)
                    ->get($knowledgeApiBase . "/knowledge-points/{$kpCode}/upstream", ['levels' => 1]);

                $downstreamResponse = Http::timeout(10)
                    ->get($knowledgeApiBase . "/knowledge-points/{$kpCode}/downstream", ['levels' => 1]);

                $detail['upstream_nodes'] = $upstreamResponse->successful() ? $upstreamResponse->json()['nodes'] ?? [] : [];
                $detail['downstream_nodes'] = $downstreamResponse->successful() ? $downstreamResponse->json()['nodes'] ?? [] : [];

                $detail['question_stats'] = app(\App\Services\QuestionServiceApi::class)
                    ->getStatistics(['kp_code' => $kpCode]);

                $this->nodeDetails = $detail;
                $this->activeTab = 'overview';
            }
        } catch (\Exception $e) {
            // 错误处理
            Log::error('加载节点详情失败', [
                'kp_code' => $kpCode,
                'error' => $e->getMessage()
            ]);
        }
        $this->isLoading = false;
    }

    public function setActiveTab($tab)
    {
        $this->activeTab = $tab;
    }

    public function getTotalQuestionsProperty()
    {
        if (!$this->nodeDetails) return 0;
        return $this->nodeDetails['question_stats']['total_questions'] ?? 0;
    }

    public function getDirectQuestionsProperty()
    {
        if (!$this->nodeDetails) return 0;
        return $this->nodeDetails['question_stats']['direct_questions'] ?? 0;
    }

    public function getChildrenQuestionsProperty()
    {
        if (!$this->nodeDetails) return 0;
        return $this->nodeDetails['question_stats']['children_questions'] ?? 0;
    }

    public function getSkillsQuestionsProperty()
    {
        if (!$this->nodeDetails) return 0;
        return $this->nodeDetails['question_stats']['skills_total_questions'] ?? 0;
    }

    public function getSkillsCountProperty()
    {
        if (!$this->nodeDetails) return 0;
        return $this->nodeDetails['question_stats']['skills_count'] ?? 0;
    }

    public function getChildrenNodesProperty()
    {
        if (!$this->nodeDetails) return [];
        return array_merge(
            $this->nodeDetails['upstream_nodes'] ?? [],
            $this->nodeDetails['downstream_nodes'] ?? []
        );
    }

    public function render()
    {
        return view('livewire.integrations.knowledge-point-details');
    }
}
