<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import KnowledgeGraph from './KnowledgeGraph.vue'

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

const props = defineProps<{
  chapterName: string
  chapterId: string
  courseId: string
  parentId: string
}>()

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

const activeName = ref('first')

// 树形数据
const treeData = ref<KnowledgeNode[]>([])
const treeRef = ref()
const inputRef = ref()

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

// 从localStorage加载数据
const loadFromStorage = () => {
  try {
    const allData = JSON.parse(localStorage.getItem(getStorageKey()) || '[]')
    if (allData) {
      treeData.value = allData?.filter((item: any) => item.section_id === props.chapterId) || []
    }
  } catch (error) {
    console.error('加载知识点数据失败:', error)
    treeData.value = []
  }
}

// 保存到localStorage
const saveToStorage = () => {
  try {
    const allData = JSON.parse(localStorage.getItem(getStorageKey()) || '[]')
    const newData = allData.filter((item: any) => item.section_id !== props.chapterId)
    newData.push(...treeData.value)
    localStorage.setItem(getStorageKey(), JSON.stringify(newData))
  } catch (error) {
    console.error('保存知识点数据失败:', error)
    ElMessage.error('保存失败')
  }
}

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 添加根节点
const addRootNode = () => {
  // if (treeData.value.length > 0) {
  //   ElMessage.warning('只能添加一个根节点')
  //   return
  // }

  const newNode = {
    id: generateId(),
    label: '新知识点',
    children: [],
    isEdit: true,
    course_id: props.courseId,
    chapter_id: props.parentId,
    section_id: props.chapterId,
  }

  treeRef.value?.append(newNode)
  treeRef.value?.setCurrentNode(newNode, true)

  // 确保新节点可见并聚焦
  nextTick(() => {
    setTimeout(() => {
      inputRef.value?.focus()
      inputRef.value?.select()
    }, 100)
  })
  saveToStorage()
}

// 添加子节点
const addChildNode = (parentNode: KnowledgeNode) => {
  const newNode: KnowledgeNode = {
    id: generateId(),
    label: '新知识点',
    children: [],
    isEdit: true,
  }

  treeRef.value?.append(newNode, parentNode)
  treeRef.value?.setCurrentNode(newNode, true)

  nextTick(() => {
    setTimeout(() => {
      inputRef.value?.focus()
      inputRef.value?.select()
    }, 100)
  })
  saveToStorage()
}

// 编辑节点
const editNode = (node: KnowledgeNode) => {
  // 保存原始值，用于取消时恢复
  node.originalLabel = node.label
  node.isEdit = true
  nextTick(() => {
    inputRef.value?.focus()
    inputRef.value?.select()
  })
}

// 保存编辑
const saveEdit = (node: KnowledgeNode) => {
  const trimmedLabel = node.label.trim()
  if (!trimmedLabel) {
    ElMessage.warning('知识点名称不能为空')
    // 恢复原始值
    if (node.originalLabel) {
      node.label = node.originalLabel
    }
    return
  }

  // 检查是否有重复名称（同级节点）
  const parent = findParentNode(treeData.value, node.id)
  const siblings = parent ? parent.children : treeData.value

  if (siblings) {
    const duplicate = siblings.find((sibling) => sibling.id !== node.id && sibling.label.trim() === trimmedLabel)
    if (duplicate) {
      ElMessage.warning('同级节点中已存在相同名称的知识点')
      inputRef.value?.focus()
      inputRef.value?.select()
      return
    }
  }

  node.label = trimmedLabel
  node.isEdit = false
  delete node.originalLabel
  saveToStorage()
}

// 取消编辑
const cancelEdit = (node: KnowledgeNode) => {
  // 恢复原始值
  if (node.originalLabel) {
    node.label = node.originalLabel
    delete node.originalLabel
  }
  node.isEdit = false

  // 如果是新节点且没有子节点，则删除
  if (node.label === '新知识点' && (!node.children || node.children.length === 0)) {
    deleteNode(node)
  }
}

// 删除节点
const deleteNode = async (node: KnowledgeNode) => {
  try {
    await ElMessageBox.confirm('确定要删除这个知识点吗？删除后其子知识点也会被删除。', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    treeRef.value?.remove(node)

    saveToStorage()
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

// 处理键盘事件
const handleKeydown = (event: Event, node: KnowledgeNode) => {
  if ((event as KeyboardEvent).key === 'Enter') {
    saveEdit(node)
  } else if ((event as KeyboardEvent).key === 'Escape') {
    cancelEdit(node)
  }
}

// 查找父节点
const findParentNode = (nodes: KnowledgeNode[], targetId: string): KnowledgeNode | null => {
  for (const node of nodes) {
    if (node.children) {
      const found = node.children.find((child) => child.id === targetId)
      if (found) {
        return node
      }
      const parent = findParentNode(node.children, targetId)
      if (parent) {
        return parent
      }
    }
  }
  return null
}

onMounted(() => {
  loadFromStorage()
})
</script>

<template>
  <el-dialog draggable width="1000px" title="添加知识点" :model-value="true" @close="emit('update:modelValue', false)">
    <el-tabs v-model="activeName">
      <el-tab-pane label="树状结构" name="first">
        <div class="knowledge-tree-container">
          <!-- 工具栏 -->
          <div class="toolbar">
            <div class="toolbar-left">
              <el-button type="primary" @click="addRootNode" :icon="Plus"> 添加根节点 </el-button>
            </div>
            <div class="toolbar-tip">
              <el-icon><Edit /></el-icon>
              <span>提示：双击节点名称可直接编辑</span>
            </div>
          </div>

          <!-- 树形结构 -->
          <div class="tree-wrapper">
            <el-tree
              ref="treeRef"
              node-key="id"
              highlight-current
              :data="treeData"
              :expand-on-click-node="false"
              :default-expand-all="false"
              class="knowledge-tree">
              <template #default="{ data }">
                <div class="knowledge-tree-node" :data-node-id="data.id">
                  <!-- 编辑模式 -->
                  <div v-if="data.isEdit" class="edit-mode">
                    <el-input
                      v-model="data.label"
                      size="small"
                      placeholder="请输入知识点名称"
                      maxlength="50"
                      show-word-limit
                      @keydown="(event: Event) => handleKeydown(event, data)"
                      @blur="saveEdit(data)"
                      ref="inputRef"
                      style="width: 100%" />
                  </div>

                  <!-- 显示模式 -->
                  <div v-else class="display-mode">
                    <span class="node-label" @dblclick="editNode(data)">
                      {{ data.label }}
                    </span>
                    <div class="node-actions">
                      <el-button text size="small" :icon="Plus" @click="addChildNode(data)"> 添加 </el-button>
                      <el-button text size="small" :icon="Edit" @click="editNode(data)"> 编辑 </el-button>
                      <el-button text size="small" :icon="Delete" @click="deleteNode(data)"> 删除 </el-button>
                    </div>
                  </div>
                </div>
              </template>
              <template #empty>
                <el-empty description="暂无知识点，点击上方按钮添加根节点" />
              </template>
            </el-tree>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="脑图预览" name="second" lazy>
        <div style="width: 100%; height: 400px">
          <KnowledgeGraph :treeData="treeData" />
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <span>
        <el-button @click="emit('update:modelValue', false)">取消</el-button>
        <el-button type="primary" @click="emit('update:modelValue', false)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.knowledge-tree-container {
  min-height: 400px;
}

.toolbar {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-left {
  display: flex;
  gap: 12px;
}

.toolbar-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  font-size: 12px;
}

.tree-wrapper {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  min-height: 300px;
  position: relative;
}

.knowledge-tree {
  padding: 16px;
}

.knowledge-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  min-height: 32px;
}

.edit-mode {
  width: 100%;
  padding: 8px;
  border-radius: 4px;
}

.display-mode {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.node-label {
  flex: 1;
  margin-right: 8px;
  font-weight: 500;
  color: #303133;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 2px;
  transition: background-color 0.2s;
}

.node-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.display-mode:hover .node-actions {
  opacity: 1;
}

.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* 覆盖 element-plus 树组件样式 */
:deep(.el-tree-node__content) {
  height: auto;
  padding: 0;
}

:deep(.el-tree-node__expand-icon) {
  margin-right: 8px;
}

:deep(.el-tree-node__label) {
  width: 100%;
}
</style>
