/**
 * 模板管理 Composable
 * 负责模板的 CRUD 操作和状态管理
 */

import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTemplateStore, useEditorStore } from '@/stores'
import * as templateApi from '@/api/template'

export function useTemplate() {
  const templateStore = useTemplateStore()
  const editorStore = useEditorStore()
  
  // 状态
  const isLoading = ref(false)
  const isCreating = ref(false)
  const selectedTemplate = ref<string | null>(null)
  const showCreateDialog = ref(false)
  const createForm = ref({
    name: '',
    description: ''
  })
  
  // 计算属性
  const templates = computed(() => templateStore.templates)
  const hasTemplates = computed(() => templateStore.hasTemplates)
  const isPreviewMode = computed(() => templateStore.isPreviewMode)
  const previewStructure = computed(() => templateStore.previewStructure)
  const previewTemplateName = computed(() => templateStore.previewTemplateName)
  
  /**
   * 加载模板列表
   */
  async function loadTemplates() {
    isLoading.value = true
    try {
      const templates = await templateApi.listTemplates()
      templateStore.setTemplates(templates)
      return templates
    } catch (error: any) {
      ElMessage.error(`加载模板失败: ${error.message}`)
      throw error
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 创建新模板
   */
  async function createTemplate() {
    if (!createForm.value.name.trim()) {
      ElMessage.warning('请输入模板名称')
      return false
    }
    
    isCreating.value = true
    try {
      await templateApi.createTemplate(
        createForm.value.name.trim(),
        editorStore.structure,
        editorStore.imageSize,
        createForm.value.description
      )
      ElMessage.success('模板创建成功')
      showCreateDialog.value = false
      createForm.value = { name: '', description: '' }
      await loadTemplates()
      return true
    } catch (error: any) {
      ElMessage.error(`创建模板失败: ${error.message}`)
      return false
    } finally {
      isCreating.value = false
    }
  }
  
  /**
   * 选择模板（用于批量操作）
   */
  function selectTemplate(name: string) {
    const newValue = selectedTemplate.value === name ? null : name
    selectedTemplate.value = newValue
    templateStore.selectTemplate(newValue)
  }
  
  /**
   * 预览模板
   */
  async function previewTemplate(name: string) {
    try {
      const structure = await templateApi.previewApplyTemplate(
        name,
        editorStore.imageSize,
        editorStore.tableBbox,
        'relative'
      )
      templateStore.setPreview(structure, name)
      editorStore.updateStructure(structure)
      return structure
    } catch (error: any) {
      ElMessage.error(`预览失败: ${error.message}`)
      throw error
    }
  }
  
  /**
   * 确认应用模板
   */
  function confirmApply() {
    if (templateStore.previewStructure) {
      editorStore.updateStructure(templateStore.previewStructure)
      templateStore.clearPreview()
      ElMessage.success('模板已应用')
      return true
    }
    return false
  }
  
  /**
   * 取消预览
   */
  function cancelPreview() {
    templateStore.clearPreview()
  }
  
  /**
   * 删除模板
   */
  async function deleteTemplate(name: string) {
    try {
      await ElMessageBox.confirm(
        `确定要删除模板 "${name}" 吗？`,
        '确认删除',
        { type: 'warning' }
      )
      await templateApi.deleteTemplate(name)
      templateStore.removeTemplate(name)
      ElMessage.success('模板已删除')
      return true
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(`删除失败: ${error.message}`)
      }
      return false
    }
  }
  
  /**
   * 重置创建表单
   */
  function resetCreateForm() {
    createForm.value = { name: '', description: '' }
    showCreateDialog.value = false
  }
  
  return {
    // 状态
    isLoading,
    isCreating,
    selectedTemplate,
    showCreateDialog,
    createForm,
    
    // 计算属性
    templates,
    hasTemplates,
    isPreviewMode,
    previewStructure,
    previewTemplateName,
    
    // 方法
    loadTemplates,
    createTemplate,
    selectTemplate,
    previewTemplate,
    confirmApply,
    cancelPreview,
    deleteTemplate,
    resetCreateForm
  }
}
