<template>
  <div class="ticket-templates-page">
    <div class="page-header">
      <h3>回复模板管理</h3>
      <div class="header-actions">
        <el-input
          v-model="keyword"
          placeholder="搜索模板名称或内容"
          clearable
          :prefix-icon="Search"
          style="width: 240px"
          @clear="loadList"
          @keyup.enter="loadList"
        />
        <el-button type="primary" :icon="Plus" @click="openAdd">新增模板</el-button>
      </div>
    </div>

    <el-table :data="templateList" v-loading="loading" stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="模板名称" min-width="160" />
      <el-table-column prop="content" label="模板内容" min-width="300" show-overflow-tooltip />
      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.CreatedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.UpdatedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="openEdit(row)">编辑</el-button>
          <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrap">
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑模板' : '新增模板'"
      width="560px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入模板内容" maxlength="2000" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getReplyTemplateList, createReplyTemplate, updateReplyTemplate, deleteReplyTemplate } from '@/api/ticket.js'

const loading = ref(false)
const templateList = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const keyword = ref('')
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)

const form = ref({
  id: null,
  name: '',
  content: ''
})

const rules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  content: [{ required: true, message: '请输入模板内容', trigger: 'blur' }]
}

const formatTime = (time) => {
  if (!time) return '—'
  const d = new Date(time)
  if (isNaN(d.getTime())) return '—'
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

const loadList = async () => {
  loading.value = true
  try {
    const params = { count: pageSize.value, page: currentPage.value }
    if (keyword.value.trim()) params.keyword = keyword.value.trim()
    const res = await getReplyTemplateList(params)
    if (res.code === 200) {
      templateList.value = res.data?.data || []
      total.value = res.data?.all_count || 0
    }
  } catch (e) {
    console.error('加载模板列表失败', e)
  }
  loading.value = false
}

const handlePageChange = (page) => {
  currentPage.value = page
  loadList()
}

const openAdd = () => {
  isEdit.value = false
  form.value = { id: null, name: '', content: '' }
  dialogVisible.value = true
}

const openEdit = (row) => {
  isEdit.value = true
  form.value = { id: row.id, name: row.name, content: row.content }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  await formRef.value.validate()
  submitting.value = true
  try {
    let res
    if (isEdit.value) {
      res = await updateReplyTemplate({ id: form.value.id, name: form.value.name, content: form.value.content })
    } else {
      res = await createReplyTemplate({ name: form.value.name, content: form.value.content })
    }
    if (res.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
      dialogVisible.value = false
      loadList()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (e) {
    ElMessage.error('操作失败')
  }
  submitting.value = false
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除模板「${row.name}」吗？`, '删除确认', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const res = await deleteReplyTemplate({ id: row.id })
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (e) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

onMounted(() => { loadList() })
</script>

<style scoped>
.ticket-templates-page {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.page-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.pagination-wrap {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
