<template>
  <div class="app-container jbgl-page">
    <!-- 搜索区 -->
    <div class="filter-panel">
      <div class="filter-form">
        <el-select v-model="searchForm.source" placeholder="事件来源" clearable style="width:160px">
          <el-option label="巡查上报" value="巡查上报" />
          <el-option label="呼叫中心" value="呼叫中心" />
          <el-option label="视频监控" value="视频监控" />
          <el-option label="上级下达" value="上级下达" />
        </el-select>
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width:260px"
          value-format="YYYY-MM-DD"
        />
        <el-select v-model="searchForm.status" placeholder="事件状态" clearable style="width:140px">
          <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-option label="不实事件" value="不实事件" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      <div class="filter-actions">
        <el-button type="primary" @click="handleAdd">新增接报</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="140" />
        <el-table-column prop="source" label="事件来源" width="110" />
        <el-table-column prop="location" label="发生地点" show-overflow-tooltip />
        <el-table-column prop="happenTime" label="发生时间" width="150" />
        <el-table-column prop="description" label="事件描述" show-overflow-tooltip />
        <el-table-column prop="reporter" label="接报人" width="100" />
        <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="220" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status === '待受理'" type="primary" link size="small" @click="handleAccept(row)">受理</el-button>
            <el-button type="primary" link size="small" @click="handleEdit(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="acceptVisible" title="受理确认" width="400px" :close-on-click-modal="false">
      <div v-if="currentRow">
        <p>事件编号：{{ currentRow.eventNo }}</p>
        <p>事件来源：{{ currentRow.source }}</p>
        <p>发生地点：{{ currentRow.location }}</p>
        <p>事件描述：{{ currentRow.description }}</p>
      </div>
      <template #footer>
        <el-button @click="acceptVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAccept">确认受理</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="事件详情" width="600px" :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="12">
              <el-form-item label="事件编号">{{ currentRow.eventNo }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="事件来源">{{ currentRow.source }}</el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发生地点">{{ currentRow.location }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发生时间">{{ currentRow.happenTime }}</el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="事件描述">
            <div class="desc-text">{{ currentRow.description }}</div>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="接报人">{{ currentRow.reporter }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="接报时间">{{ currentRow.reportTime }}</el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="来源渠道">{{ currentRow.channel }}</el-form-item>
          <el-form-item label="状态">
            <el-tag :type="statusTagType(currentRow.status)" size="small">{{ currentRow.status }}</el-tag>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑接报弹窗 -->
    <el-dialog v-model="addVisible" :title="editingId ? '编辑接报' : '新增接报'" width="600px" :close-on-click-modal="false">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
        <el-form-item label="事件来源" prop="source">
          <el-select v-model="addForm.source" placeholder="请选择" style="width:100%">
            <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="发生地点" prop="location">
          <el-input v-model="addForm.location" placeholder="请输入发生地点" />
        </el-form-item>
        <el-form-item label="发生时间" prop="happenTime">
          <el-date-picker v-model="addForm.happenTime" type="datetime" placeholder="选择日期时间" style="width:100%" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="事件描述" prop="description">
          <el-input v-model="addForm.description" type="textarea" :rows="3" placeholder="请输入事件描述" />
        </el-form-item>
        <el-form-item label="接报人" prop="reporter">
          <el-input v-model="addForm.reporter" placeholder="请输入接报人" />
        </el-form-item>
        <el-form-item label="接报时间" prop="reportTime">
          <el-date-picker v-model="addForm.reportTime" type="datetime" placeholder="选择日期时间" style="width:100%" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="来源渠道" prop="channel">
          <el-select v-model="addForm.channel" placeholder="请选择来源渠道" style="width:100%">
            <el-option label="12345市民热线" value="12345市民热线" />
            <el-option label="移动终端巡查系统" value="移动终端巡查系统" />
            <el-option label="省应急管理厅平台" value="省应急管理厅平台" />
            <el-option label="交警监控共享平台" value="交警监控共享平台" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Jbgl">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEventPage, saveEventReport, updateEventInfo, deleteEventInfo, acceptEvent } from '@/api/dispatch'

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

// ==================== 加载数据 ====================
async function loadData() {
  loading.value = true
  try {
    const params = {}
    if (searchForm.value.source) params.source = searchForm.value.source
    if (searchForm.value.status) params.status = searchForm.value.status
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
      params.startDate = searchForm.value.dateRange[0]
      params.endDate = searchForm.value.dateRange[1]
    }
    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 = { source: '', dateRange: null, status: '' }
  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 'warning'
  if (status === '待核实') return 'warning'
  if (status === '已核实') return 'success'
  if (status === '处置中') return 'primary'
  if (status === '已解除') return 'warning'
  if (status === '已关闭') return 'success'
  if (status === '不实事件') return 'info'
  return 'info'
}

// ==================== 受理 ====================
const acceptVisible = ref(false)
const currentRow = ref(null)

function handleAccept(row) {
  currentRow.value = row
  acceptVisible.value = true
}

async function confirmAccept() {
  if (!currentRow.value) return
  try {
    await acceptEvent(currentRow.value.id)
    ElMessage.success('受理成功')
    acceptVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('受理失败：' + (error.message || '未知错误'))
  }
}

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

function handleDetail(row) {
  currentRow.value = row
  detailVisible.value = true
}

// ==================== 新增/编辑接报 ====================
const addVisible = ref(false)
const addFormRef = ref(null)
const editingId = ref(null)
const addForm = ref({ source: '', location: '', happenTime: '', description: '', reporter: '', reportTime: '', channel: '' })
const addRules = {
  source: [{ required: true, message: '请选择事件来源', trigger: 'change' }],
  location: [{ required: true, message: '请输入发生地点', trigger: 'blur' }],
  happenTime: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入事件描述', trigger: 'blur' }],
  reporter: [{ required: true, message: '请输入接报人', trigger: 'blur' }],
  reportTime: [{ required: true, message: '请选择接报时间', trigger: 'change' }],
  channel: [{ required: true, message: '请输入来源渠道', trigger: 'blur' }]
}

function handleAdd() {
  editingId.value = null
  addForm.value = { source: '', location: '', happenTime: '', description: '', reporter: '', reportTime: '', channel: '' }
  addVisible.value = true
}

function handleEdit(row) {
  editingId.value = row.id
  addForm.value = {
    source: row.source,
    location: row.location,
    happenTime: row.happenTime,
    description: row.description,
    reporter: row.reporter,
    reportTime: row.reportTime,
    channel: row.channel
  }
  addVisible.value = true
}

function handleSubmit() {
  addFormRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (editingId.value) {
        await updateEventInfo({ id: editingId.value, ...addForm.value })
        ElMessage.success('编辑成功')
      } else {
        await saveEventReport(addForm.value)
        ElMessage.success('新增成功')
      }
      addVisible.value = false
      loadData()
    } catch (error) {
      ElMessage.error('操作失败：' + (error.message || '未知错误'))
    }
  })
}

// ==================== 删除 ====================
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 || '未知错误'))
    }
  }
}
</script>

<style scoped>
.jbgl-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;
}

.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>
