import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { templateApi, sourceFileApi, variableApi } from '@/api'

export const useTemplateStore = defineStore('template', () => {
  // 状态
  const templates = ref([])
  const currentTemplate = ref(null)
  const sourceFiles = ref([])
  const variables = ref([])
  const groupedVariables = ref({})
  const loading = ref(false)

  // 类别配置
  const categoryConfig = {
    entity: { label: '核心实体', color: '#1890ff', icon: '🏢' },
    concept: { label: '概念/技术', color: '#722ed1', icon: '💡' },
    data: { label: '数据/指标', color: '#52c41a', icon: '📊' },
    location: { label: '地点/组织', color: '#faad14', icon: '📍' },
    asset: { label: '资源模板', color: '#eb2f96', icon: '📑' },
    other: { label: '其他', color: '#8c8c8c', icon: '📌' }
  }

  // 计算属性
  const variableCount = computed(() => variables.value.length)
  const sourceFileCount = computed(() => sourceFiles.value.length)

  // 方法
  async function fetchTemplates(page = 1, size = 20) {
    loading.value = true
    try {
      const data = await templateApi.list(page, size)
      templates.value = data.records || data
      return data
    } finally {
      loading.value = false
    }
  }

  async function fetchTemplateDetail(id) {
    loading.value = true
    try {
      currentTemplate.value = await templateApi.getById(id)
      // 同时获取来源文件和变量
      await Promise.all([
        fetchSourceFiles(id),
        fetchVariables(id)
      ])
      return currentTemplate.value
    } finally {
      loading.value = false
    }
  }

  async function fetchSourceFiles(templateId) {
    sourceFiles.value = await sourceFileApi.list(templateId)
    return sourceFiles.value
  }

  async function fetchVariables(templateId) {
    variables.value = await variableApi.list(templateId)
    return variables.value
  }

  async function fetchGroupedVariables(templateId) {
    groupedVariables.value = await variableApi.listGrouped(templateId)
    return groupedVariables.value
  }

  async function createTemplate(data) {
    const template = await templateApi.create(data)
    templates.value.unshift(template)
    return template
  }

  async function updateTemplate(id, data) {
    const template = await templateApi.update(id, data)
    if (currentTemplate.value?.id === id) {
      currentTemplate.value = { ...currentTemplate.value, ...template }
    }
    return template
  }

  async function deleteTemplate(id) {
    await templateApi.delete(id)
    templates.value = templates.value.filter(t => t.id !== id)
    if (currentTemplate.value?.id === id) {
      currentTemplate.value = null
    }
  }

  async function addVariable(templateId, data) {
    const variable = await variableApi.add(templateId, data)
    variables.value.push(variable)
    return variable
  }

  async function updateVariable(id, data) {
    const variable = await variableApi.update(id, data)
    const index = variables.value.findIndex(v => v.id === id)
    if (index !== -1) {
      variables.value[index] = variable
    }
    return variable
  }

  async function deleteVariable(id) {
    await variableApi.delete(id)
    variables.value = variables.value.filter(v => v.id !== id)
  }

  async function addSourceFile(templateId, data) {
    const sourceFile = await sourceFileApi.add(templateId, data)
    sourceFiles.value.push(sourceFile)
    return sourceFile
  }

  async function updateSourceFile(id, data) {
    const sourceFile = await sourceFileApi.update(id, data)
    const index = sourceFiles.value.findIndex(s => s.id === id)
    if (index !== -1) {
      sourceFiles.value[index] = sourceFile
    }
    return sourceFile
  }

  async function deleteSourceFile(id) {
    await sourceFileApi.delete(id)
    sourceFiles.value = sourceFiles.value.filter(s => s.id !== id)
  }

  function resetState() {
    currentTemplate.value = null
    sourceFiles.value = []
    variables.value = []
    groupedVariables.value = {}
  }

  return {
    // 状态
    templates,
    currentTemplate,
    sourceFiles,
    variables,
    groupedVariables,
    loading,
    categoryConfig,

    // 计算属性
    variableCount,
    sourceFileCount,

    // 方法
    fetchTemplates,
    fetchTemplateDetail,
    fetchSourceFiles,
    fetchVariables,
    fetchGroupedVariables,
    createTemplate,
    updateTemplate,
    deleteTemplate,
    addVariable,
    updateVariable,
    deleteVariable,
    addSourceFile,
    updateSourceFile,
    deleteSourceFile,
    resetState
  }
})
