<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\Student;
use Illuminate\Foundation\Testing\LazilyRefreshDatabase;
use Illuminate\Support\Facades\Http;

class StudentKnowledgeGraphIntegrationTest extends TestCase
{
    use LazilyRefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        // 创建测试学生数据
        Student::create([
            'student_id' => 1001,
            'name' => '张三',
            'grade' => '高一',
            'class_name' => '1班',
            'teacher_id' => 1,
        ]);

        Student::create([
            'student_id' => 1002,
            'name' => '李四',
            'grade' => '高一',
            'class_name' => '1班',
            'teacher_id' => 1,
        ]);
    }

    /** @test */
    public function student_knowledge_graph_page_can_be_loaded()
    {
        $response = $this->get('/admin/student-knowledge-graph-page');

        $response->assertStatus(200);
        $response->assertSee('学生知识图谱');
        $response->assertSee('选择学生');
        $response->assertSee('知识点依赖关系图');
    }

    /** @test */
    public function page_displays_student_dropdown()
    {
        $response = $this->get('/admin/student-knowledge-graph-page');

        $response->assertSee('张三 (高一-1班)');
        $response->assertSee('李四 (高一-1班)');
    }

    /** @test */
    public function selecting_student_loads_knowledge_graph_data()
    {
        // 模拟API响应
        Http::fake([
            'localhost:5010/api/mastery/1001' => Http::response([
                'masteries' => [
                    [
                        'student_id' => 1001,
                        'kp_code' => 'R01',
                        'mastery_level' => 0.85,
                        'confidence_level' => 0.8,
                    ],
                    [
                        'student_id' => 1001,
                        'kp_code' => 'R02',
                        'mastery_level' => 0.72,
                        'confidence_level' => 0.75,
                    ],
                ],
            ], 200),
            'localhost:5010/api/knowledge/dependencies' => Http::response([
                'dependencies' => [
                    [
                        'prerequisite_kp' => 'R01',
                        'dependent_kp' => 'R02',
                        'influence_weight' => 0.9,
                        'dependency_type' => 'must',
                    ],
                ],
            ], 200),
            'localhost:5010/api/mastery/1001/statistics' => Http::response([
                'total_knowledge_points' => 2,
                'average_mastery' => 0.785,
                'high_mastery_count' => 2,
                'medium_mastery_count' => 0,
                'low_mastery_count' => 0,
            ], 200),
        ]);

        // 模拟Livewire请求
        $this->actingAsAdmin()
            ->get('/admin/student-knowledge-graph-page')
            ->assertStatus(200);

        // 使用Livewire测试器
        $this->livewire(\App\Livewire\StudentKnowledgeGraph::class)
            ->set('selectedStudentId', 1001)
            ->assertSet('selectedStudentId', 1001)
            ->call('loadStudentData', 1001)
            ->assertSee('张三')
            ->assertSee('78.5%'); // 平均掌握度
    }

    /** @test */
    public function api_failure_shows_mock_data()
    {
        // 模拟API失败
        Http::fake([
            'localhost:5010/*' => Http::response([], 500),
        ]);

        $this->livewire(\App\Livewire\StudentKnowledgeGraph::class)
            ->set('selectedStudentId', 1001)
            ->call('loadStudentData', 1001)
            ->assertSee('有理数'); // 模拟数据中的知识点
    }

    /** @test */
    public function mastery_statistics_display_correctly()
    {
        // 模拟API响应
        Http::fake([
            'localhost:5010/api/mastery/1001' => Http::response([
                'masteries' => [
                    ['kp_code' => 'R01', 'mastery_level' => 0.9, 'confidence_level' => 0.8],
                    ['kp_code' => 'R02', 'mastery_level' => 0.6, 'confidence_level' => 0.7],
                    ['kp_code' => 'R03', 'mastery_level' => 0.3, 'confidence_level' => 0.6],
                ],
            ], 200),
            'localhost:5010/api/mastery/1001/statistics' => Http::response([
                'total_knowledge_points' => 3,
                'average_mastery' => 0.6,
                'high_mastery_count' => 1,
                'medium_mastery_count' => 1,
                'low_mastery_count' => 1,
            ], 200),
        ]);

        $component = $this->livewire(\App\Livewire\StudentKnowledgeGraph::class)
            ->set('selectedStudentId', 1001)
            ->call('loadStudentData', 1001);

        $component->assertSee('60.0%'); // 平均掌握度
        $component->assertSee('1'); // 优秀数量
        $component->assertSee('1'); // 中等数量
        $component->assertSee('1'); // 待提高数量
    }

    /** @test */
    public function knowledge_graph_renders_with_correct_colors()
    {
        // 模拟API响应
        Http::fake([
            'localhost:5010/api/mastery/1001' => Http::response([
                'masteries' => [
                    ['kp_code' => 'R01', 'mastery_level' => 0.85, 'confidence_level' => 0.8],
                ],
            ], 200),
            'localhost:5010/api/knowledge/dependencies' => Http::response([
                'dependencies' => [],
            ], 200),
        ]);

        $response = $this->actingAsAdmin()
            ->get('/admin/student-knowledge-graph-page');

        $response->assertStatus(200);

        // 验证图例显示
        $response->assertSee('掌握度');
        $response->assertSee('优秀 (≥80%)');
        $response->assertSee('良好 (60-80%)');
        $response->assertSee('中等 (40-60%)');
        $response->assertSee('待提高 (20-40%)');
        $response->assertSee('薄弱 (<20%)');
    }

    /** @test */
    public function refresh_button_works()
    {
        $component = $this->livewire(\App\Livewire\StudentKnowledgeGraph::class);

        // 设置学生ID
        $component->set('selectedStudentId', 1001);

        // 验证刷新按钮存在
        $component->assertSee('刷新');
    }

    /** @test */
    public function no_student_selected_shows_prompt()
    {
        $component = $this->livewire(\App\Livewire\StudentKnowledgeGraph::class);

        $component->assertSee('选择学生查看知识图谱');
        $component->assertSee('从上方下拉列表中选择一个学生');
    }

    /** @test */
    public function knowledge_points_list_displays_correctly()
    {
        // 模拟API响应
        Http::fake([
            'localhost:5010/api/mastery/1001' => Http::response([
                'masteries' => [
                    ['kp_code' => 'R01', 'mastery_level' => 0.85, 'confidence_level' => 0.8],
                    ['kp_code' => 'R02', 'mastery_level' => 0.72, 'confidence_level' => 0.75],
                ],
            ], 200),
            'localhost:5010/api/knowledge/dependencies' => Http::response([
                'dependencies' => [],
            ], 200),
        ]);

        $component = $this->livewire(\App\Livewire\StudentKnowledgeGraph::class)
            ->set('selectedStudentId', 1001)
            ->call('loadStudentData', 1001);

        // 验证知识点列表
        $component->assertSee('知识点列表');
        $component->assertSee('R01');
        $component->assertSee('R02');
        $component->assertSee('85.0%');
        $component->assertSee('72.0%');
    }

    /** @test */
    public function loading_state_displays_correctly()
    {
        // 模拟慢速API响应
        Http::fake([
            'localhost:5010/*' => Http::response([
                'masteries' => [],
            ], 200),
        ]);

        $component = $this->livewire(\App\Livewire\StudentKnowledgeGraph::class)
            ->set('selectedStudentId', 1001)
            ->call('loadStudentData', 1001);

        // 验证加载状态
        $this->assertNotNull($component->isLoading);
    }

    /** @test */
    public function reset_data_when_no_student_selected()
    {
        $component = $this->livewire(\App\Livewire\StudentKnowledgeGraph::class);

        // 先选择一个学生
        $component->set('selectedStudentId', 1001);
        $component->assertNotNull($component->selectedStudentId);

        // 然后取消选择
        $component->set('selectedStudentId', null);

        // 验证数据被重置
        $component->assertNull($component->selectedStudent);
        $component->assertEmpty($component->knowledgePoints);
        $component->assertEmpty($component->masteryData);
        $component->assertEmpty($component->statistics);
    }

    /** @test */
    public function livewire_form_validation_works()
    {
        $component = $this->livewire(\App\Livewire\StudentKnowledgeGraph::class);

        // 验证规则
        $component->assertValidationPassesFor('selectedStudentId', 1001);
        $component->assertValidationFailsFor('selectedStudentId', 'invalid-id');
    }

    /** @test */
    public function multiple_students_can_be_loaded()
    {
        // 模拟不同学生的数据
        Http::fake([
            'localhost:5010/api/mastery/1001' => Http::response([
                'masteries' => [
                    ['kp_code' => 'R01', 'mastery_level' => 0.9, 'confidence_level' => 0.8],
                ],
            ], 200),
            'localhost:5010/api/mastery/1002' => Http::response([
                'masteries' => [
                    ['kp_code' => 'R01', 'mastery_level' => 0.6, 'confidence_level' => 0.7],
                ],
            ], 200),
        ]);

        $component = $this->livewire(\App\Livewire\StudentKnowledgeGraph::class);

        // 加载第一个学生
        $component->set('selectedStudentId', 1001);
        $component->call('loadStudentData', 1001);
        $this->assertNotNull($component->selectedStudent);
        $this->assertEquals(1001, $component->selectedStudent->student_id);

        // 切换到第二个学生
        $component->set('selectedStudentId', 1002);
        $component->call('loadStudentData', 1002);
        $this->assertEquals(1002, $component->selectedStudent->student_id);
    }

    /** @test */
    public function error_handling_displays_message()
    {
        // 模拟网络异常
        Http::fake([
            'localhost:5010/*' => Http::throw(new \Exception('Network error')),
        ]);

        $component = $this->livewire(\App\Livewire\StudentKnowledgeGraph::class)
            ->set('selectedStudentId', 1001)
            ->call('loadStudentData', 1001);

        // 应该使用模拟数据
        $component->assertSee('有理数');
    }

    protected function actingAsAdmin()
    {
        return $this->actingAs(\App\Models\User::factory()->create(), 'admin');
    }
}
