<template>
  <div class="template-page">
    <el-card>
      <!-- 工具栏 -->
      <el-row class="toolbar">
        <el-button type="primary" @click="handleAdd">新增模板</el-button>
      </el-row>
      
      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="templateName" label="模板名称" width="200" />
        <el-table-column prop="content" label="内容" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="180" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleStatus(row)">
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板内容">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="10"
            placeholder="请输入模板内容（支持Markdown格式）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listAllTemplates, createTemplate, updateTemplate, updateTemplateStatus, deleteTemplate } from '@/api/template'
import type { Template } from '@/api/template'
import type { FormInstance, FormRules } from 'element-plus'

const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<Template[]>([])

const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
  id: '',
  templateName: '',
  content: ''
})

const dialogTitle = computed(() => form.id ? '编辑模板' : '新增模板')

const rules: FormRules = {
  templateName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }]
}

// 加载数据
async function loadData() {
  loading.value = true
  try {
    tableData.value = await listAllTemplates()
  } finally {
    loading.value = false
  }
}

// 新增
function handleAdd() {
  form.id = ''
  form.templateName = ''
  form.content = ''
  dialogVisible.value = true
}

// 编辑
function handleEdit(row: Template) {
  form.id = row.id
  form.templateName = row.templateName
  form.content = row.content || ''
  dialogVisible.value = true
}

// 提交
async function handleSubmit() {
  const valid = await formRef.value?.validate()
  if (!valid) return
  
  submitLoading.value = true
  try {
    if (form.id) {
      await updateTemplate(form.id, {
        templateName: form.templateName,
        content: form.content
      })
      ElMessage.success('更新成功')
    } else {
      await createTemplate({
        templateName: form.templateName,
        content: form.content
      })
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    loadData()
  } finally {
    submitLoading.value = false
  }
}

// 更新状态
async function handleStatus(row: Template) {
  const newStatus = row.status === 1 ? 0 : 1
  await ElMessageBox.confirm(
    `确定要${newStatus === 1 ? '启用' : '禁用'}该模板吗？`,
    '提示',
    { type: 'warning' }
  )
  await updateTemplateStatus(row.id, newStatus)
  ElMessage.success('操作成功')
  loadData()
}

// 删除
async function handleDelete(row: Template) {
  await ElMessageBox.confirm('确定要删除该模板吗？', '提示', { type: 'warning' })
  await deleteTemplate(row.id)
  ElMessage.success('删除成功')
  loadData()
}

// 初始化
loadData()
</script>

<style scoped>
.template-page {
  height: 100%;
}

.toolbar {
  margin-bottom: 16px;
}
</style>
