<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import KnowledgeGraph from './KnowledgeGraph.vue'

interface KnowledgeNode {
  id: string
  label: string
  children?: KnowledgeNode[]
  course_id?: string
  chapter_id?: string
  section_id?: string
}

const props = defineProps<{
  isShowKnowledgeGraphPreview: boolean
  courseId: string
  chapterId?: string // 可选的章节ID，如果提供则只显示该章节的知识点
  title?: string // 弹框标题
}>()

const emit = defineEmits<{
  (e: 'update:isShowKnowledgeGraphPreview', value: boolean): void
}>()

// 知识图谱数据
const knowledgeData = ref<KnowledgeNode[]>([])
const loading = ref(false)

// 获取localStorage key
const getStorageKey = () => `knowledge`

// 获取知识图谱数据
const fetchKnowledgeData = async () => {
  if (!props.courseId) return

  loading.value = true
  try {
    // 从localStorage读取数据
    const allData = JSON.parse(localStorage.getItem(getStorageKey()) || '[]')

    if (allData && allData.length > 0) {
      // 如果提供了章节ID，则筛选该章节的数据
      if (props.chapterId) {
        knowledgeData.value = allData.filter((item: any) => item.chapter_id === props.chapterId) || []
      } else {
        // 否则显示所有属于该课程的数据
        knowledgeData.value = allData.filter((item: any) => item.course_id === props.courseId) || []
      }
    } else {
      knowledgeData.value = []
    }
  } catch (error) {
    console.error('获取知识图谱数据失败:', error)
    knowledgeData.value = []
  } finally {
    loading.value = false
  }
}

// 关闭弹框
const handleClose = () => {
  emit('update:isShowKnowledgeGraphPreview', false)
}

// 监听弹框显示状态
watch(
  () => props.isShowKnowledgeGraphPreview,
  (newVal) => {
    if (newVal) {
      fetchKnowledgeData()
    }
  }
)

// 监听课程ID变化
watch(
  () => props.courseId,
  () => {
    if (props.isShowKnowledgeGraphPreview) {
      fetchKnowledgeData()
    }
  }
)

// 监听章节ID变化
watch(
  () => props.chapterId,
  () => {
    if (props.isShowKnowledgeGraphPreview) {
      fetchKnowledgeData()
    }
  }
)

onMounted(() => {
  if (props.isShowKnowledgeGraphPreview) {
    fetchKnowledgeData()
  }
})
</script>

<template>
  <el-dialog
    :model-value="isShowKnowledgeGraphPreview"
    :title="title || '知识点脑图预览'"
    width="1000px"
    :before-close="handleClose"
    draggable
    destroy-on-close
    @update:model-value="(val) => emit('update:isShowKnowledgeGraphPreview', val)">
    <div v-loading="loading" style="min-height: 500px">
      <div v-if="!loading && knowledgeData.length === 0" class="empty-state">
        <el-empty description="暂无知识点数据" />
      </div>
      <div v-else-if="!loading" style="width: 100%; height: 500px">
        <KnowledgeGraph :treeData="knowledgeData" />
      </div>
    </div>

    <template #footer>
      <span>
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
}
</style>
