import { ref } from 'vue'
import { defineStore } from 'pinia'
import {
  getTagGroups, createTagGroup, editTagGroup, deleteTagGroup,
  getTags, createTag, editTag, deleteTag as apiDeleteTag, moveTag
} from '../api/tag'

export const useTagStore = defineStore('tag', () => {
  const groups = ref([])
  const loading = ref(false)
  /** 当前选中的标签组 ID */
  const activeGroupId = ref(null)
  /** 当前标签组的标签（扁平列表） */
  const currentTags = ref([])

  async function fetchGroups() {
    loading.value = true
    try {
      const { data } = await getTagGroups()
      groups.value = data
    } finally {
      loading.value = false
    }
  }

  async function createGroup(name, description) {
    const { data } = await createTagGroup({ name, description })
    groups.value.push(data)
    return data
  }

  async function updateGroup(id, name, description) {
    const { data } = await editTagGroup(id, { name, description })
    const idx = groups.value.findIndex(g => g.id === id)
    if (idx >= 0) groups.value[idx] = data
    return data
  }

  async function removeGroup(id) {
    await deleteTagGroup(id)
    groups.value = groups.value.filter(g => g.id !== id)
    if (activeGroupId.value === id) {
      activeGroupId.value = null
      currentTags.value = []
    }
  }

  async function fetchTags(groupId) {
    activeGroupId.value = groupId
    const { data } = await getTags(groupId)
    currentTags.value = data
  }

  async function addTag(groupId, parentId, name) {
    const { data } = await createTag(groupId, { parentId, name })
    currentTags.value.push(data)
    return data
  }

  async function updateTag(id, name) {
    const { data } = await editTag(id, { name })
    const idx = currentTags.value.findIndex(t => t.id === id)
    if (idx >= 0) currentTags.value[idx] = data
    return data
  }

  async function removeTag(id) {
    await apiDeleteTag(id)
    // 递归移除子孙
    const toRemove = new Set()
    function collectDescendants(tagId) {
      toRemove.add(tagId)
      currentTags.value.filter(t => t.parentId === tagId).forEach(c => collectDescendants(c.id))
    }
    collectDescendants(id)
    currentTags.value = currentTags.value.filter(t => !toRemove.has(t.id))
  }

  async function moveTagNode(id, parentId, sortOrder) {
    const { data } = await moveTag(id, { parentId, sortOrder })
    const idx = currentTags.value.findIndex(t => t.id === id)
    if (idx >= 0) currentTags.value[idx] = data
    return data
  }

  /** 将扁平标签列表转为树结构（跳过虚拟根节点，直接展示一级标签） */
  function buildTree() {
    const map = {}
    const roots = []
    currentTags.value.forEach(t => {
      map[t.id] = { ...t, children: [] }
    })
    currentTags.value.forEach(t => {
      if (t.parentId == null) {
        // 虚拟根节点：将其子节点提升为顶层
        currentTags.value.forEach(child => {
          if (child.parentId === t.id && map[child.id]) {
            roots.push(map[child.id])
          }
        })
      } else if (map[t.parentId]) {
        map[t.parentId].children.push(map[t.id])
      }
    })
    return roots
  }

  return {
    groups, loading, activeGroupId, currentTags,
    fetchGroups, createGroup, updateGroup, removeGroup,
    fetchTags, addTag, updateTag, removeTag, moveTagNode,
    buildTree
  }
})
