<template>
  <div class="app-container zjbs-page">
    <!-- 搜索区 -->
    <div class="filter-panel">
      <div class="filter-form">
        <el-input v-model="searchForm.eventNo" placeholder="事件编号" clearable style="width:160px" />
        <el-select v-model="searchForm.transferStatus" placeholder="转接状态" clearable style="width:140px">
          <el-option label="已核实" value="已核实" />
          <el-option label="处置中" value="处置中" />
        </el-select>
        <el-select v-model="searchForm.receiveDept" placeholder="接收部门" clearable style="width:160px">
          <el-option label="市政部门" value="市政部门" />
          <el-option label="消防部门" value="消防部门" />
          <el-option label="排水管理部" value="排水管理部" />
          <el-option label="管网维护部" value="管网维护部" />
          <el-option label="设备运维部" value="设备运维部" />
          <el-option label="安全管理部" value="安全管理部" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-panel">
      <el-table :data="tableData" border stripe style="width:100%" v-loading="loading">
        <el-table-column prop="eventNo" label="事件编号" width="150" />
        <el-table-column prop="category" label="事件类别" width="110" />
        <el-table-column prop="level" label="事件等级" width="100">
          <template #default="{ row }">
            <el-tag :type="levelTagType(row.level)" size="small">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="transferDept" label="转接部门" min-width="120" />
        <el-table-column prop="reportTargets" label="报送层级" min-width="120" />
        <el-table-column prop="transferTime" label="转接时间" min-width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)" size="small">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status === '已核实'" type="primary" link size="small" @click="handleTransfer(row)">转接</el-button>
            <el-button v-if="row.status === '处置中' && row.transferId" type="primary" link size="small" @click="handleReport(row)">报送</el-button>
            <el-button type="primary" link size="small" @click="handleDetail(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
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 转接弹窗 -->
    <el-dialog v-model="transferVisible" title="事件转接" width="600px" :close-on-click-modal="false">
      <el-form :model="transferForm" :rules="transferRules" ref="transferFormRef" label-width="120px">
        <el-form-item label="事件摘要">
          <div class="desc-text">{{ transferForm.summary }}</div>
        </el-form-item>
        <el-form-item label="推荐转接部门">
          <el-tag type="success" size="small">{{ transferForm.recommendDept }}</el-tag>
        </el-form-item>
        <el-form-item label="选择转接部门" prop="depts">
          <el-select v-model="transferForm.depts" multiple placeholder="请选择" style="width:100%">
            <el-option label="市政部门" value="市政部门" />
            <el-option label="消防部门" value="消防部门" />
            <el-option label="排水管理部" value="排水管理部" />
            <el-option label="管网维护部" value="管网维护部" />
            <el-option label="设备运维部" value="设备运维部" />
            <el-option label="安全管理部" value="安全管理部" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="transferForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="transferVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmTransfer">确认转接</el-button>
      </template>
    </el-dialog>

    <!-- 报送弹窗 -->
    <el-dialog v-model="reportVisible" title="事件报送" width="600px" :close-on-click-modal="false">
      <el-form :model="reportForm" :rules="reportRules" ref="reportFormRef" label-width="120px">
        <el-form-item label="报送层级" prop="reportTargets">
          <el-checkbox-group v-model="reportForm.reportTargets">
            <el-checkbox label="区级应急办" />
            <el-checkbox label="市级应急办" />
            <el-checkbox label="省级应急厅" />
            <el-checkbox label="国务院应急管理部" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="报送内容摘要">
          <div class="desc-text">{{ reportForm.summary }}</div>
        </el-form-item>
        <el-form-item label="附件上传">
          <el-upload
            ref="uploadRef"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :limit="5"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-exceed="handleUploadExceed"
            :file-list="reportForm.fileList"
            :before-upload="handleBeforeUpload"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">单个文件不超过 50MB，最多上传 5 个文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reportVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReport" :loading="submitting">确认报送</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="流转详情" width="700px" :close-on-click-modal="false">
      <div v-if="currentRow" class="detail-content">
        <el-form label-width="100px" size="default">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="事件编号">{{ currentRow.eventNo }}</el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="事件类别">{{ currentRow.category }}</el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="事件等级">{{ currentRow.level }}</el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="事件来源">{{ currentRow.source || '-' }}</el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="事件等级">{{ currentRow.level }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="转接部门">{{ currentRow.transferDept }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="当前状态">
                <el-tag :type="statusTagType(currentRow.status)" size="small">{{ currentRow.status }}</el-tag>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="转接时间">{{ currentRow.transferTime || '-' }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报送层级">{{ currentRow.reportTargets || '-' }}</el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="事件描述">
            <div class="desc-text">{{ currentRow.description || '-' }}</div>
          </el-form-item>
        </el-form>
        <div class="section-title">流转历史</div>
        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in currentRow.history"
            :key="index"
            :type="item.type"
            :timestamp="item.actionTime"
          >
            {{ item.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Zjbs">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'
import { getEventPage, deleteEventInfo, transferEvent, reportEvent } from '@/api/dispatch'

// ==================== 推荐部门映射 ====================
const recommendMap = {
  '管道泄漏': '市政部门',
  '塌陷': '管网维护部',
  '积水': '排水管理部',
  '设备故障': '设备运维部'
}

// ==================== 数据状态 ====================
const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const searchForm = ref({ eventNo: '', transferStatus: '', receiveDept: '' })
const pagination = ref({ page: 1, pageSize: 10 })

// ==================== 加载数据 ====================
async function loadData() {
  loading.value = true
  try {
    const params = { statusList: ['已核实', '处置中'] }
    if (searchForm.value.eventNo) params.eventNo = searchForm.value.eventNo
    if (searchForm.value.transferStatus) params.statusList = [searchForm.value.transferStatus]
    if (searchForm.value.receiveDept) params.department = searchForm.value.receiveDept
    const res = await getEventPage(pagination.value.page, pagination.value.pageSize, params)
    tableData.value = res.data?.rows || res.data?.records || res.data || []
    total.value = res.data?.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

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

// ==================== 搜索筛选 ====================
function handleSearch() {
  pagination.value.page = 1
  loadData()
}

function handleReset() {
  searchForm.value = { eventNo: '', transferStatus: '', receiveDept: '' }
  pagination.value.page = 1
  loadData()
}

// ==================== 分页 ====================
function handleSizeChange(val) {
  pagination.value.pageSize = val
  pagination.value.page = 1
  loadData()
}

function handleCurrentChange(val) {
  pagination.value.page = val
  loadData()
}

// ==================== 标签样式 ====================
function statusTagType(status) {
  if (status === '已核实') return 'primary'
  if (status === '处置中') return 'warning'
  if (status === '已报送') return 'success'
  return 'info'
}

function levelTagType(level) {
  if (level === '特别重大') return 'danger'
  if (level === '重大') return 'danger'
  if (level === '较大') return 'warning'
  return 'info'
}

// ==================== 转接 ====================
const transferVisible = ref(false)
const transferFormRef = ref(null)
const currentTransferId = ref(null)
const transferForm = ref({ eventNo: '', summary: '', recommendDept: '', depts: [], remark: '' })
const transferRules = {
  depts: [{ required: true, message: '请选择转接部门', trigger: 'change', type: 'array' }]
}

function handleTransfer(row) {
  currentTransferId.value = row.id
  transferForm.value = {
    eventNo: row.eventNo,
    summary: row.summary || row.description || '',
    recommendDept: recommendMap[row.category] || '相关部门',
    depts: [],
    remark: ''
  }
  transferVisible.value = true
}

async function confirmTransfer() {
  try {
    await transferFormRef.value.validate()
  } catch {
    return
  }
  try {
    await transferEvent({
      relEventId: currentTransferId.value,
      transferDept: transferForm.value.depts.join('、'),
      transferRemark: transferForm.value.remark
    })
    ElMessage.success('转接成功')
    transferVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('转接失败：' + (error.message || '未知错误'))
  }
}

// ==================== 报送 ====================
const reportVisible = ref(false)
const reportFormRef = ref(null)
const uploadRef = ref(null)
const currentReportId = ref(null)
const submitting = ref(false)
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/common/upload'
const uploadHeaders = { Authorization: 'Bearer ' + getToken() }
const reportForm = ref({ eventNo: '', summary: '', reportTargets: [], fileList: [], attachments: [] })
const reportRules = {
  reportTargets: [{ required: true, message: '请选择报送层级', trigger: 'change', type: 'array' }]
}

function handleReport(row) {
  currentReportId.value = row.id
  reportForm.value = {
    eventNo: row.eventNo,
    summary: row.summary || row.description || '',
    reportTargets: [],
    fileList: [],
    attachments: []
  }
  reportVisible.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) {
    reportForm.value.attachments.push({
      fileName: res.originalFilename,
      url: res.url
    })
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

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

function handleUploadExceed() {
  ElMessage.warning('附件数量不能超过 5 个')
}

async function confirmReport() {
  try {
    await reportFormRef.value.validate()
  } catch {
    return
  }
  submitting.value = true
  try {
    await reportEvent({
      id: currentReportId.value,
      reportTargets: reportForm.value.reportTargets,
      attachPaths: reportForm.value.attachments.map(a => a.url).join(',')
    })
    ElMessage.success('报送成功')
    reportVisible.value = false
    loadData()
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('报送失败：' + (error.message || '未知错误'))
    }
  } finally {
    submitting.value = false
  }
}

// ==================== 删除 ====================
async function handleDelete(row) {
  try {
    await ElMessageBox.confirm('确定要删除该转接记录吗？', '删除确认', { type: 'warning' })
    await deleteEventInfo(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  }
}

// ==================== 详情 ====================
const detailVisible = ref(false)
const currentRow = ref(null)

function handleDetail(row) {
  currentRow.value = row
  detailVisible.value = true
}
</script>

<style scoped>
.zjbs-page {
  padding: 16px;
  background: #f5f5f5;
  min-height: calc(100vh - 84px);
}

.filter-panel {
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-form {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.table-panel {
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
}

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

.detail-content {
  padding: 0 8px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-left: 8px;
  border-left: 3px solid #409EFF;
}

.desc-text {
  background: #f5f7fa;
  border-radius: 4px;
  padding: 10px;
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  max-height: 120px;
  overflow-y: auto;
}

:deep(.el-form-item__label) {
  color: #909399;
}

:deep(.el-form-item__content) {
  color: #303133;
}
</style>
