<!-- 应急预案编辑 -->
<template>
  <div class="app-container">
    <!-- 顶部操作区 -->
    <el-form :model="queryParams" :inline="true" class="search-form">
      <el-form-item label="预案名称">
        <el-input v-model="queryParams.planName" placeholder="请输入预案名称" clearable style="width: 200px" />
      </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-button type="primary" @click="handleDownloadTemplate">下载模版</el-button>
      </el-form-item>
    </el-form>

    <!-- 主体：左侧树 + 右侧表格 -->
    <div class="main-layout">
      <!-- 左侧预案分类树 -->
      <div class="left-tree">
        <div class="tree-title">预案分类</div>
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="treeProps"
          node-key="id"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
        />
      </div>

      <!-- 右侧表格 -->
      <div class="right-table">
        <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="planName" label="预案名称" min-width="180" show-overflow-tooltip />
          <el-table-column prop="planType" label="预案类型" width="130" />
          <el-table-column prop="planLevel" label="预案级别" width="100" align="center" />
          <el-table-column prop="attachName" label="附件名称" min-width="200" show-overflow-tooltip />
          <el-table-column label="附件下载" width="90" align="center">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleDownload(row)" :disabled="!row.attachPath">
                <el-icon><Download /></el-icon>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="publishDate" label="发布时间" width="120" align="center" />
          <el-table-column prop="compileUnit" label="编制单位" width="100" />
          <el-table-column label="操作" width="200" 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>
              <el-button v-if="row.status !== '已发布'" link type="success" @click="handleSubmitApproval(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"
        />
      </div>
    </div>

    <!-- 新增/修改预案弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="580px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="预案分类" prop="categoryId">
          <el-tree-select
            v-model="form.categoryId"
            :data="treeData"
            :props="treeProps"
            node-key="id"
            placeholder="请选择预案分类"
            check-strictly
            :render-after-expand="false"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="预案名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入预案名称" />
        </el-form-item>
        <el-form-item label="预案级别" prop="planLevel">
          <el-select v-model="form.planLevel" 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="planType">
          <el-input v-model="form.planType" placeholder="请输入预案类型" />
        </el-form-item>
        <el-form-item label="预案版本" prop="version">
          <el-input v-model="form.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="编制单位" prop="compileUnit">
          <el-input v-model="form.compileUnit" placeholder="请输入编制单位" />
        </el-form-item>
        <el-form-item label="附件上传">
          <el-upload
            ref="uploadRef"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :limit="1"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-exceed="() => ElMessage.warning('只能上传一个文件')"
            :file-list="form.fileList"
            :before-upload="handleBeforeUpload"
          >
            <el-button type="primary">添加文件</el-button>
          </el-upload>
          <div class="upload-tip">支持上传任意格式文件，单个文件不超过 50MB</div>
        </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 { Download } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import { getEventPlanPage, getEventPlanById, addEventPlan, updateEventPlan, deleteEventPlan, getPlanCategoryTree, createPlanApproval } from '@/api/dispatch'

// ---------- 常量 ----------
const levelOptions = ['一级', '二级', '三级', '四级']

// ---------- 分类树 ----------
const treeRef = ref(null)
const treeProps = { children: 'children', label: 'label' }
const treeData = ref([])

async function loadCategoryTree() {
  try {
    const res = await getPlanCategoryTree()
    treeData.value = res?.data ?? res ?? []
  } catch {
    ElMessage.error('加载分类树失败')
  }
}

const selectedTreeNode = ref(null)
const handleNodeClick = (node) => {
  selectedTreeNode.value = node
  pagination.value.page = 1
  loadData()
}

// ---------- 查询 ----------
const queryParams = ref({ planName: '' })

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

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

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

// ---------- 分页 ----------
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.planName = ''
  selectedTreeNode.value = null
  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, planName: '', planLevel: '', planType: '', version: '1.0', compileUnit: '', categoryId: selectedTreeNode.value?.id || null, attachName: '', attachPath: '', fileList: []
})
const form = ref(defaultForm())

const formRules = {
  planName: [{ required: true, message: '请输入预案名称', trigger: 'blur' }],
  planLevel: [{ required: true, message: '请选择预案级别', trigger: 'change' }],
  planType: [{ required: true, message: '请输入预案类型', trigger: 'blur' }],
}

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/common/upload'
const uploadHeaders = { Authorization: 'Bearer ' + getToken() }

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

const handleEdit = (row) => {
  form.value = {
    ...row,
    fileList: row.attachName ? [{ name: row.attachName, url: row.attachPath }] : []
  }
  dialogTitle.value = '修改预案'
  dialogVisible.value = true
}

function handleBeforeUpload(file) {
  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB')
    return false
  }
  return true
}

function handleUploadSuccess(res) {
  if (res.code === 200) {
    form.value.attachName = res.originalFilename
    form.value.attachPath = res.url
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

function handleUploadError() {
  ElMessage.error('文件上传失败')
}

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

// ---------- 删除 ----------
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该条预案?', '提示', { type: 'warning' }).then(async () => {
    try {
      await deleteEventPlan(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 => deleteEventPlan(i.id)))
      ElMessage.success('删除成功')
      loadData()
    } catch {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// ---------- 下载 / 导出 ----------
const handleDownload = (row) => {
  if (!row.attachPath) return
  window.open(row.attachPath, '_blank')
}

const handleExport = () => {
  if (!tableData.value.length) return ElMessage.warning('暂无数据可导出')
  const headers = ['预案名称', '预案类型', '预案级别', '附件名称', '发布时间', '编制单位']
  const keys = ['planName', 'planType', 'planLevel', 'attachName', 'publishDate', 'compileUnit']
  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('导出成功')
}

const handleSubmitApproval = (row) => {
  ElMessageBox.confirm('确认将该预案提交审批？', '提示', { type: 'warning' }).then(async () => {
    try {
      await createPlanApproval(row.id)
      ElMessage.success('提交审批成功')
      loadData()
    } catch {
      ElMessage.error('提交审批失败')
    }
  }).catch(() => {})
}

const handleDownloadTemplate = () => { ElMessage.success('模版下载成功（Mock）') }
</script>

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

.main-layout {
  display: flex;
  gap: 16px;
}

.left-tree {
  width: 25%;
  min-width: 200px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 12px;
  flex-shrink: 0;

  .tree-title {
    font-weight: bold;
    font-size: 15px;
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
  }
}

.right-table {
  flex: 1;
  min-width: 0;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
