<template>
  <div class="templates-page">
    <div class="page-header">
      <h1>🎨 模板管理</h1>
      <el-button type="primary" :icon="Plus" @click="showCreateDialog = true">
        创建模板
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="🔍 搜索模板..."
        clearable
        style="width: 280px"
        @input="handleSearch"
      />
      <el-radio-group v-model="filterType" @change="handleFilterChange">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="official">官方模板</el-radio-button>
        <el-radio-button label="mine">我的模板</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 模板列表 -->
    <el-row :gutter="16" v-loading="loading">
      <el-col :span="6" v-for="tpl in filteredTemplates" :key="tpl.id">
        <div class="tpl-card card">
          <div class="tpl-preview" @click="goToDetail(tpl)">
            {{ getTemplateIcon(tpl) }}
          </div>
          <div class="tpl-info">
            <div class="tpl-name">{{ tpl.name }}</div>
            <div class="tpl-meta">
              <span>📊 {{ tpl.useCount || 0 }}次</span>
              <span>
                <el-tag size="small" :type="getStatusType(tpl.status)">
                  {{ getStatusLabel(tpl.status) }}
                </el-tag>
              </span>
            </div>
            <div class="tpl-tags">
              <span class="tpl-tag" v-if="tpl.isPublic">公开</span>
              <span class="tpl-tag" v-else>私有</span>
            </div>
            <div class="tpl-actions">
              <el-button type="primary" size="small" @click="useTemplate(tpl)">
                使用
              </el-button>
              <el-dropdown trigger="click" @command="(cmd) => handleCommand(cmd, tpl)">
                <el-button size="small" :icon="More" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="duplicate">复制</el-dropdown-item>
                    <el-dropdown-item command="publish" v-if="tpl.status === 'draft'">发布</el-dropdown-item>
                    <el-dropdown-item command="archive" v-if="tpl.status === 'published'">归档</el-dropdown-item>
                    <el-dropdown-item command="delete" divided>
                      <span style="color: #ff4d4f">删除</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 空状态 -->
    <el-empty v-if="!loading && filteredTemplates.length === 0" description="暂无模板">
      <el-button type="primary" @click="showCreateDialog = true">创建模板</el-button>
    </el-empty>

    <!-- 创建模板对话框 -->
    <el-dialog v-model="showCreateDialog" title="创建新模板" width="500">
      <el-form :model="newTemplate" label-width="80px">
        <el-form-item label="模板名称" required>
          <el-input v-model="newTemplate.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="newTemplate.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateTemplate" :loading="creating">
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, More } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTemplateStore } from '@/stores/template'

const router = useRouter()
const templateStore = useTemplateStore()

const loading = ref(false)
const creating = ref(false)
const searchKeyword = ref('')
const filterType = ref('all')
const showCreateDialog = ref(false)

const newTemplate = reactive({
  name: '',
  description: ''
})

// 模板列表数据（从 API 获取）
const templates = ref([])

const filteredTemplates = computed(() => {
  let result = templates.value

  if (searchKeyword.value) {
    result = result.filter(t => 
      t.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  if (filterType.value === 'official') {
    result = result.filter(t => t.isPublic)
  } else if (filterType.value === 'mine') {
    result = result.filter(t => !t.isPublic)
  }

  return result
})

onMounted(async () => {
  loading.value = true
  try {
    // 从 API 获取模板列表
    await templateStore.fetchTemplates()
    templates.value = templateStore.templates
  } catch (error) {
    console.error('获取模板列表失败:', error)
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
})

function getTemplateIcon(tpl) {
  const icons = ['📊', '🏢', '📅', '💼', '📋', '📈']
  return icons[parseInt(tpl.id) % icons.length]
}

function getStatusType(status) {
  const map = {
    draft: 'info',
    published: 'success',
    archived: 'warning'
  }
  return map[status] || 'info'
}

function getStatusLabel(status) {
  const map = {
    draft: '草稿',
    published: '已发布',
    archived: '已归档'
  }
  return map[status] || status
}

function handleSearch() {
  // 搜索逻辑已在 computed 中处理
}

function handleFilterChange() {
  // 筛选逻辑已在 computed 中处理
}

function goToDetail(tpl) {
  router.push(`/templates/${tpl.id}`)
}

function useTemplate(tpl) {
  router.push(`/editor/${tpl.id}`)
}

async function handleCommand(command, tpl) {
  switch (command) {
    case 'edit':
      router.push(`/editor/${tpl.id}`)
      break
    case 'duplicate':
      try {
        await templateStore.createTemplate({
          ...tpl,
          name: `${tpl.name} (副本)`
        })
        ElMessage.success('复制成功')
      } catch (error) {
        ElMessage.error('复制失败')
      }
      break
    case 'publish':
      try {
        await templateStore.updateTemplate(tpl.id, { status: 'published' })
        tpl.status = 'published'
        ElMessage.success('发布成功')
      } catch (error) {
        ElMessage.error('发布失败')
      }
      break
    case 'archive':
      try {
        await templateStore.updateTemplate(tpl.id, { status: 'archived' })
        tpl.status = 'archived'
        ElMessage.success('归档成功')
      } catch (error) {
        ElMessage.error('归档失败')
      }
      break
    case 'delete':
      ElMessageBox.confirm('确定要删除该模板吗？此操作不可恢复。', '删除确认', {
        type: 'warning',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }).then(async () => {
        try {
          await templateStore.deleteTemplate(tpl.id)
          templates.value = templates.value.filter(t => t.id !== tpl.id)
          ElMessage.success('删除成功')
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      break
  }
}

async function handleCreateTemplate() {
  if (!newTemplate.name) {
    ElMessage.warning('请输入模板名称')
    return
  }

  creating.value = true
  try {
    const template = await templateStore.createTemplate({
      name: newTemplate.name,
      description: newTemplate.description || ''
    })
    showCreateDialog.value = false
    // 重置表单
    Object.assign(newTemplate, { name: '', description: '' })
    ElMessage.success('模板创建成功')
    // 跳转到空白编辑页
    router.push(`/editor/${template.id}`)
  } catch (error) {
    ElMessage.error('创建失败: ' + error.message)
  } finally {
    creating.value = false
  }
}
</script>

<style lang="scss" scoped>
.templates-page {
  max-width: 1200px;
  margin: 0 auto;
}

.filter-bar {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.tpl-card {
  margin-bottom: 16px;

  .tpl-actions {
    display: flex;
    gap: 8px;
    margin-top: 10px;

    .el-button:first-child {
      flex: 1;
    }
  }
}

</style>
