<template>
  <div class="ticket-types-page">
    <div class="page-header">
      <h3>工单类型管理</h3>
      <el-button type="primary" :icon="Plus" @click="openAdd">新增类型</el-button>
    </div>

    <el-table :data="typeList" 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="note" label="说明" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.note || '—' }}
        </template>
      </el-table-column>
      <el-table-column label="图标" width="80" align="center">
        <template #default="{ row }">
          <el-avatar v-if="row.ico?.savePath" :size="32" :src="row.ico.savePath" shape="square" />
          <span v-else class="no-icon">—</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.CreatedAt) }}
        </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>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑工单类型' : '新增工单类型'"
      width="480px"
      :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="请输入类型名称" />
        </el-form-item>
        <el-form-item label="说明" prop="note">
          <el-input v-model="form.note" type="textarea" :rows="3" placeholder="请输入说明（选填）" />
        </el-form-item>
        <el-form-item label="图标ID" prop="icoId">
          <el-input-number v-model="form.icoId" :min="0" placeholder="文件ID" controls-position="right" />
        </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 } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTicketTypeList, addTicketType, updateTicketType, deleteTicketType } from '@/api/ticket.js'

const loading = ref(false)
const typeList = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref(null)

const form = ref({
  id: null,
  name: '',
  note: '',
  icoId: 0
})

const rules = {
  name: [{ 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 res = await getTicketTypeList()
    if (res?.code === 200) {
      typeList.value = res.data || []
    }
  } catch (e) { /* ignore */ }
  loading.value = false
}

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

const openEdit = (row) => {
  isEdit.value = true
  form.value = {
    id: row.id,
    name: row.name,
    note: row.note || '',
    icoId: row.icoId || 0
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  await formRef.value.validate()
  submitting.value = true
  try {
    const data = { name: form.value.name }
    if (form.value.note) data.note = form.value.note
    if (form.value.icoId) data.icoId = form.value.icoId

    let res
    if (isEdit.value) {
      data.id = form.value.id
      res = await updateTicketType(data)
    } else {
      res = await addTicketType(data)
    }
    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 deleteTicketType({ 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-types-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;
}

.no-icon {
  color: #909399;
}
</style>
