<!-- 应急事件分级 -->
<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-form :model="queryParams" :inline="true" class="search-form">
      <el-form-item label="事件类别">
        <el-select v-model="queryParams.category" placeholder="请选择" clearable style="width: 160px">
          <el-option v-for="item in categoryOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="事件等级">
        <el-select v-model="queryParams.level" placeholder="请选择" clearable style="width: 140px">
          <el-option v-for="item in levelOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="事件状态">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 120px">
          <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button type="success" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        <el-button type="primary" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="pageList" border stripe @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column prop="category" label="事件类别" min-width="120" />
      <el-table-column prop="level" label="事件等级" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="levelTagType(row.level)" size="small">{{ row.level }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="scenario" label="适用场景" min-width="140" />
      <el-table-column prop="criteria" label="判断标准" min-width="200" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === '启用' ? 'success' : 'info'">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin-top: 16px; justify-content: flex-end"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50]"
      :total="tableData.length"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="onSizeChange"
      @current-change="onPageChange"
    />

    <!-- 新增/修改弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="560px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="140px">
        <el-form-item label="事件类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择事件类别" style="width: 100%">
            <el-option v-for="item in categoryOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="事件等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in levelOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="类别细分" prop="subCategory">
          <el-input v-model="form.subCategory" placeholder="请输入类别细分" />
        </el-form-item>
        <el-form-item label="适用场景" prop="scenario">
          <el-input v-model="form.scenario" placeholder="请输入适用场景" />
        </el-form-item>
        <el-form-item label="分级分类判断标准" prop="criteria">
          <el-input
            v-model="form.criteria"
            type="textarea"
            :rows="4"
            placeholder="填写具体判断规则、适用条件、划分依据"
          />
        </el-form-item>
        <el-form-item label="标准生效状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="停用">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEventGradePage, addEventGrade, updateEventGrade, deleteEventGrade } from '@/api/dispatch'

// ---------- 下拉选项 ----------
const categoryOptions = ['管网泄漏', '路面积水', '设施损坏', '管道堵塞']
const levelOptions = ['一级', '二级', '三级', '四级']
const statusOptions = ['全部', '启用', '停用']

// ---------- 查询参数 ----------
const queryParams = ref({ category: '', level: '', status: '' })

// ---------- 数据 ----------
const tableData = ref([])

async function loadData() {
  try {
    const res = await getEventGradePage(1, 999, queryParams.value)
    tableData.value = res?.data?.records ?? res?.data ?? res ?? []
  } catch {
    ElMessage.error('加载数据失败')
  }
}

onMounted(() => { loadData() })

// ---------- 分页 ----------
const pagination = ref({ page: 1, size: 10 })

const pageList = computed(() => {
  const start = (pagination.value.page - 1) * pagination.value.size
  return tableData.value.slice(start, start + pagination.value.size)
})

const onSizeChange = () => { pagination.value.page = 1 }
const onPageChange = () => {}

// ---------- 搜索 / 重置 ----------
const handleSearch = () => { pagination.value.page = 1; loadData() }
const handleReset = () => {
  queryParams.value = { category: '', level: '', status: '' }
  pagination.value.page = 1
  loadData()
}

// ---------- 多选 ----------
const selectedRows = ref([])
const handleSelectionChange = (rows) => { selectedRows.value = rows }

// ---------- 弹窗 ----------
const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const formRef = ref(null)
const defaultForm = () => ({
  id: null, category: '', level: '', subCategory: '', scenario: '', criteria: '', status: '启用', remark: ''
})
const form = ref(defaultForm())

const formRules = {
  category: [{ required: true, message: '请输入事件类别', trigger: 'blur' }],
  level: [{ required: true, message: '请选择事件等级', trigger: 'change' }],
  scenario: [{ required: true, message: '请输入适用场景', trigger: 'blur' }],
  criteria: [{ required: true, message: '请填写判断标准', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

const handleAdd = () => {
  form.value = defaultForm()
  dialogTitle.value = '新增'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  form.value = { ...row }
  dialogTitle.value = '修改'
  dialogVisible.value = true
}

const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    try {
      if (form.value.id) {
        await updateEventGrade(form.value)
      } else {
        await addEventGrade(form.value)
      }
      dialogVisible.value = false
      ElMessage.success('保存成功')
      loadData()
    } catch {
      ElMessage.error('保存失败')
    }
  })
}

// ---------- 删除 ----------
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该条记录?', '提示', { type: 'warning' }).then(async () => {
    try {
      await deleteEventGrade(row.id)
      ElMessage.success('删除成功')
      loadData()
    } catch {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const handleBatchDelete = () => {
  if (!selectedRows.value.length) return ElMessage.warning('请先选择记录')
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录?`, '提示', { type: 'warning' }).then(async () => {
    try {
      await Promise.all(selectedRows.value.map(i => deleteEventGrade(i.id)))
      ElMessage.success('删除成功')
      loadData()
    } catch {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

function levelTagType(level) {
  if (level === '一级') return 'danger'
  if (level === '二级') return 'warning'
  if (level === '三级') return 'primary'
  return 'info'
}

// ---------- 导出 ----------
const handleExport = () => {
  if (!tableData.value.length) return ElMessage.warning('暂无数据可导出')
  const headers = ['事件类别', '事件等级', '类别细分', '适用场景', '判断标准', '状态', '备注']
  const keys = ['category', 'level', 'subCategory', 'scenario', 'criteria', 'status', 'remark']
  const csvContent = [
    '﻿' + headers.join(','),
    ...tableData.value.map(row => keys.map(k => '"' + (row[k] || '') + '"').join(','))
  ].join('\n')
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '应急事件分级_' + new Date().toISOString().slice(0, 10) + '.csv'
  link.click()
  URL.revokeObjectURL(link.href)
  ElMessage.success('导出成功')
}
</script>

<style scoped lang="scss">
.search-form {
  margin-bottom: 12px;
  :deep(.el-form-item) {
    margin-bottom: 8px;
  }
}
</style>
