<template>
  <div class="app-container gzjc-page">
    <!-- 搜索区 -->
    <div class="filter-panel">
      <div class="filter-form">
        <el-select v-model="searchForm.eventStatus" placeholder="事件状态" clearable style="width:140px">
          <el-option label="处置中" value="处置中" />
          <el-option label="已解除" value="已解除" />
          <el-option label="已关闭" value="已关闭" />
        </el-select>
        <el-select v-model="searchForm.category" placeholder="事件类别" clearable style="width:140px">
          <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-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="140" />
        <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="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 prop="lastVisitTime" label="最近回访时间" min-width="150" />
        <el-table-column prop="nextVisitTime" label="下次回访时间" min-width="150" />
        <el-table-column prop="handler" label="负责人" min-width="100" />
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status === '处置中'" type="primary" link size="small" @click="handleTrack(row)">跟踪</el-button>
            <el-button v-if="row.status === '处置中'" type="primary" link size="small" @click="handleClose(row)">解除</el-button>
            <el-button v-if="row.status === '已解除'" type="primary" link size="small" @click="handleClose(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="trackVisible" title="事件跟踪" width="700px" :close-on-click-modal="false">
      <div v-if="currentRow">
        <div class="section-title">事件进展时间线</div>
        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in currentRow.timeline"
            :key="index"
            :type="item.type"
            :timestamp="item.time"
          >
            <div style="font-weight:600">{{ item.title }}</div>
            <div style="color:#606266;font-size:13px">{{ item.content }}</div>
          </el-timeline-item>
        </el-timeline>

        <div class="section-title">新增跟踪记录</div>
        <el-form :model="trackForm" :rules="trackRules" ref="trackFormRef" label-width="120px">
          <el-form-item label="跟踪内容" prop="content">
            <el-input v-model="trackForm.content" type="textarea" :rows="3" placeholder="请输入跟踪内容" />
          </el-form-item>
          <el-form-item label="当前态势评估" prop="assessment">
            <el-radio-group v-model="trackForm.assessment">
              <el-radio label="趋于平稳">趋于平稳</el-radio>
              <el-radio label="仍在发展">仍在发展</el-radio>
              <el-radio label="明显恶化">明显恶化</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否需要升级" prop="needUpgrade">
            <el-radio-group v-model="trackForm.needUpgrade">
              <el-radio label="否">否</el-radio>
              <el-radio label="是">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="下次回访时间" prop="nextVisitTime">
            <el-date-picker v-model="trackForm.nextVisitTime" type="datetime" placeholder="选择日期时间" style="width:100%" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="trackVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmTrack">保存跟踪记录</el-button>
      </template>
    </el-dialog>

    <!-- 解除/关闭弹窗 -->
    <el-dialog v-model="closeVisible" :title="closeTitle" width="500px" :close-on-click-modal="false">
      <el-form :model="closeForm" :rules="closeRules" ref="closeFormRef" label-width="100px">
        <el-form-item label="事件编号">{{ closeForm.eventNo }}</el-form-item>
        <el-form-item label="事件摘要">{{ closeForm.summary }}</el-form-item>
        <el-form-item label="解除原因" prop="reason">
          <el-select v-model="closeForm.reason" placeholder="请选择" style="width:100%">
            <el-option label="事件不存在" value="事件不存在" />
            <el-option label="处置完成" value="处置完成" />
            <el-option label="误报" value="误报" />
          </el-select>
        </el-form-item>
        <el-form-item label="解除说明" prop="remark">
          <el-input v-model="closeForm.remark" type="textarea" :rows="4" placeholder="请输入解除说明" />
        </el-form-item>
        <el-form-item label="损失(万元)">
          <el-input-number v-model="closeForm.lossAmount" :min="0" :precision="2" style="width:100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmClose">确认</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="8">
              <el-form-item label="事件编号">{{ currentRow.eventNo }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="事件类别">{{ currentRow.category }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="事件等级">
                <el-tag v-if="currentRow.level" :type="levelTagType(currentRow.level)" size="small">{{ currentRow.level }}</el-tag>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <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-col :span="8">
              <el-form-item label="负责人">{{ currentRow.handler || '-' }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发生地点">{{ currentRow.location || '-' }}</el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="最近回访">{{ currentRow.lastVisitTime || '-' }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="下次回访">{{ currentRow.nextVisitTime || '-' }}</el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="事件描述">
            <div class="desc-text">{{ currentRow.description || '-' }}</div>
          </el-form-item>
          <div class="section-title">处置时间线</div>
          <el-timeline>
            <el-timeline-item
              v-for="(item, index) in currentRow.timeline"
              :key="index"
              :type="item.type"
              :timestamp="item.time"
            >
              <div style="font-weight:600">{{ item.title }}</div>
              <div style="color:#606266;font-size:13px">{{ item.content }}</div>
            </el-timeline-item>
          </el-timeline>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Gzjc">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEventPage, deleteEventInfo, trackEvent, releaseEventInfo, closeEventInfo, getTrackLogs } from '@/api/dispatch'

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

// ==================== 加载数据 ====================
async function loadData() {
  loading.value = true
  try {
    const params = { statusList: ['处置中', '已解除', '已关闭'] }
    if (searchForm.value.eventStatus) params.statusList = [searchForm.value.eventStatus]
    if (searchForm.value.category) params.category = searchForm.value.category
    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 = { eventStatus: '', category: '', dateRange: null }
  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 trackVisible = ref(false)
const trackFormRef = ref(null)
const currentTrackId = ref(null)
const trackForm = ref({ eventNo: '', content: '', assessment: '趋于平稳', needUpgrade: '否', nextVisitTime: '' })
const trackRules = {
  content: [{ required: true, message: '请输入跟踪内容', trigger: 'blur' }],
  assessment: [{ required: true, message: '请选择态势评估', trigger: 'change' }],
  needUpgrade: [{ required: true, message: '请选择是否升级', trigger: 'change' }],
  nextVisitTime: [{ required: true, message: '请选择下次回访时间', trigger: 'change' }]
}

function handleTrack(row) {
  currentRow.value = row
  currentTrackId.value = row.id
  trackForm.value = { eventNo: row.eventNo, content: '', assessment: '趋于平稳', needUpgrade: '否', nextVisitTime: '' }
  // 加载跟踪日志（按最近跟踪记录ID）
  if (row.trackId) {
    loadTrackLogs(row.trackId)
  }
  trackVisible.value = true
}

async function loadTrackLogs(trackId) {
  try {
    const res = await getTrackLogs(trackId)
    if (res.data && currentRow.value) {
      currentRow.value = { ...currentRow.value, timeline: res.data || [] }
    }
  } catch {
    // 使用行内已有数据
  }
}

async function confirmTrack() {
  try {
    await trackFormRef.value.validate()
  } catch {
    return
  }
  try {
    await trackEvent({
      relEventId: currentTrackId.value,
      description: trackForm.value.content,
      assessment: trackForm.value.assessment,
      needUpgrade: trackForm.value.needUpgrade,
      nextVisitTime: trackForm.value.nextVisitTime
    })
    ElMessage.success('跟踪记录保存成功')
    trackVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('保存失败：' + (error.message || '未知错误'))
  }
}

// ==================== 解除/关闭 ====================
const closeVisible = ref(false)
const closeFormRef = ref(null)
const currentCloseRow = ref(null)
const closeForm = ref({ eventNo: '', summary: '', reason: '', remark: '', lossAmount: undefined })
const closeRules = {
  reason: [{ required: true, message: '请选择解除原因', trigger: 'change' }],
  remark: [{ required: true, message: '请输入解除说明', trigger: 'blur' }]
}
const closeTitle = ref('事件解除')

function handleClose(row) {
  currentCloseRow.value = row
  closeTitle.value = row.status === '处置中' ? '事件解除' : '事件关闭'
  closeForm.value = { eventNo: row.eventNo, summary: row.description || '', reason: '', remark: '', lossAmount: row.lossAmount ? Number(row.lossAmount) : undefined }
  closeVisible.value = true
}

async function confirmClose() {
  try {
    await closeFormRef.value.validate()
  } catch {
    return
  }
  try {
    if (currentCloseRow.value.status === '处置中') {
      await releaseEventInfo(currentCloseRow.value.id)
      ElMessage.success('事件已解除')
    } else if (currentCloseRow.value.status === '已解除') {
      await closeEventInfo({
        id: currentCloseRow.value.id,
        closeReason: closeForm.value.reason,
        closeRemark: closeForm.value.remark,
        lossAmount: closeForm.value.lossAmount
      })
      ElMessage.success('事件已关闭')
    }
    closeVisible.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 || '未知错误'))
    }
  }
}

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

async function handleDetail(row) {
  currentRow.value = row
  detailVisible.value = true
  // 加载最新的跟踪日志（按最近跟踪记录ID）
  if (row.trackId) {
    try {
      const res = await getTrackLogs(row.trackId)
      if (res.data && res.data.length) {
        currentRow.value = { ...row, timeline: res.data }
      }
    } catch {
      // 使用行内已有数据
    }
  }
}
</script>

<style scoped>
.gzjc-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>
