<!--数据查询与统计-->
<template>
  <div class="app-container">
    <div class="inquiry-layout">
      <!-- 左侧条件面板 -->
      <div class="left-panel">
        <el-card shadow="hover">
          <template #header>
            <div class="panel-title">多维条件查询</div>
          </template>
          <el-form :model="queryForm" label-width="80px" label-position="top" size="default">
            <el-form-item label="事件类型">
              <el-select v-model="queryForm.eventType" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in eventTypeOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="发生时间">
              <el-date-picker v-model="queryForm.eventTime" type="date" placeholder="请选择日期"
                value-format="YYYY-MM-DD" style="width: 100%" clearable />
            </el-form-item>
            <el-form-item label="事件等级">
              <el-select v-model="queryForm.eventLevel" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in eventLevelOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="地域">
              <el-select v-model="queryForm.region" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in regionOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="责任部门">
              <el-select v-model="queryForm.department" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in departmentOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="损失情况">
              <el-select v-model="queryForm.lossRange" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in lossRangeOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" style="width: 100%">执行查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button @click="handleReset" style="width: 100%">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 右侧结果区 -->
      <div class="right-panel">
        <!-- 统计卡片行 -->
        <div class="stat-cards">
          <div class="stat-card">
            <div class="stat-value">{{ stats.totalEvents }}</div>
            <div class="stat-label">事件总数</div>
          </div>
          <div class="stat-card stat-card-warning">
            <div class="stat-value">{{ formatLoss(stats.totalLoss) }}</div>
            <div class="stat-label">直接经济损失(万元)</div>
          </div>
          <div class="stat-card stat-card-info">
            <div class="stat-value">{{ formatLoss(stats.avgLoss) }}</div>
            <div class="stat-label">平均损失(万元)</div>
          </div>
          <div class="stat-card stat-card-danger">
            <div class="stat-value">{{ stats.majorEvents }}</div>
            <div class="stat-label">重大及以上事件数</div>
          </div>
        </div>

        <!-- 事件列表表格 -->
        <el-card shadow="hover">
          <template #header>
            <div class="panel-title">事件列表 <span class="total-count">共{{ total }}条数据</span>
              <el-button type="primary" size="small" style="margin-left:auto" @click="openAdd">新增事件</el-button>
            </div>
          </template>
          <el-table :data="tableData" border stripe style="width: 100%" size="default">
            <el-table-column prop="eventName" label="事件名称" min-width="180" show-overflow-tooltip />
            <el-table-column prop="eventType" label="类型" width="100" />
            <el-table-column prop="happenTime" label="发生时间" width="160" />
            <el-table-column prop="level" label="等级" width="100">
              <template #default="{ row }">
                <el-tag :type="levelTagType(row.level)" size="small" effect="dark">{{ row.level }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="region" label="地域" width="90" />
            <el-table-column prop="department" label="责任部门" width="110" />
            <el-table-column prop="status" label="状态" width="90">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.status)" size="small">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="损失(万元)" width="110" align="right">
              <template #default="{ row }">
                {{ formatLoss(row.lossAmount) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140" align="center">
              <template #default="{ row }">
                <el-button link type="primary" @click="openEdit(row)">编辑</el-button>
                <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :total="total"
            layout="total, prev, pager, next, sizes"
            :page-sizes="[10, 20, 50]"
            style="margin-top: 16px; justify-content: flex-end"
            @current-change="loadData"
            @size-change="handleSizeChange"
          />
        </el-card>
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="560px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="事件名称" prop="eventName">
          <el-input v-model="form.eventName" placeholder="请输入事件名称" />
        </el-form-item>
        <el-form-item label="事件类型" prop="eventType">
          <el-select v-model="form.eventType" placeholder="请选择" style="width:100%">
            <el-option v-for="item in eventTypeOptions.filter(o => o !== '全部')" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="发生时间" prop="eventTime">
          <el-date-picker v-model="form.eventTime" type="date" value-format="YYYY-MM-DD" style="width:100%" />
        </el-form-item>
        <el-form-item label="事件等级" prop="eventLevel">
          <el-select v-model="form.eventLevel" placeholder="请选择" style="width:100%">
            <el-option v-for="item in eventLevelOptions.filter(o => o !== '全部')" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="地域" prop="region">
          <el-select v-model="form.region" placeholder="请选择" style="width:100%">
            <el-option v-for="item in regionOptions.filter(o => o !== '全部')" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="责任部门" prop="department">
          <el-select v-model="form.department" placeholder="请选择" style="width:100%">
            <el-option v-for="item in departmentOptions.filter(o => o !== '全部')" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="损失(万元)" prop="lossAmount">
          <el-input-number v-model="form.lossAmount" :min="0" :precision="2" style="width:100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEventPage, getEventStats, saveEventReport, updateEventInfo, deleteEventInfo } from '@/api/dispatch'

// 查询条件选项（与应急预案选择/统一事件口径一致）
const eventTypeOptions = ['全部', '排水', '供水', '燃气', '其他']
const eventLevelOptions = ['全部', '一般', '较大', '重大', '特别重大']
const regionOptions = ['全部', '城南', '城北', '太常']
const departmentOptions = ['全部', '供水局', '燃气公司', '排水公司']
const lossRangeOptions = ['全部', '100万以下', '100-500万', '500-1000万', '1000万以上']

// 查询表单
const queryForm = reactive({
  eventType: '',
  eventTime: '',
  eventLevel: '',
  region: '',
  department: '',
  lossRange: ''
})

// 列表数据（接口分页）
const tableData = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)

// 统计数据（接口计算）
const stats = ref({ totalEvents: 0, totalLoss: 0, avgLoss: 0, majorEvents: 0 })

// 新增/编辑弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const form = reactive({ id: null, eventName: '', eventType: '', eventTime: '', eventLevel: '', region: '', department: '', lossAmount: undefined })

const formRules = {
  eventName: [{ required: true, message: '请输入事件名称', trigger: 'blur' }],
  eventType: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  eventTime: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
  eventLevel: [{ required: true, message: '请选择事件等级', trigger: 'change' }],
  region: [{ required: true, message: '请选择地域', trigger: 'change' }],
  department: [{ required: true, message: '请选择责任部门', trigger: 'change' }],
  lossAmount: [{ required: true, message: '请输入损失金额', trigger: 'blur' }]
}

// 损失金额格式化（保留2位小数）
const formatLoss = (val) => {
  const num = Number(val)
  return isNaN(num) ? '-' : num.toFixed(2)
}

// 打开新增
const openAdd = () => {
  Object.assign(form, { id: null, eventName: '', eventType: '', eventTime: '', eventLevel: '', region: '', department: '', lossAmount: undefined })
  dialogTitle.value = '新增事件记录'
  dialogVisible.value = true
}

// 打开编辑
const openEdit = (row) => {
  Object.assign(form, {
    id: row.id,
    eventName: row.eventName,
    eventType: row.eventType,
    eventTime: row.happenTime ? String(row.happenTime).slice(0, 10) : '',
    eventLevel: row.level,
    region: row.region,
    department: row.department,
    lossAmount: Number(row.lossAmount)
  })
  dialogTitle.value = '编辑事件记录'
  dialogVisible.value = true
}

// 提交新增/修改（统一事件：新增即入主表参与闭环流转）
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    const payload = {
      eventName: form.eventName,
      eventType: form.eventType,
      happenTime: form.eventTime ? form.eventTime + ' 00:00:00' : null,
      level: form.eventLevel,
      region: form.region,
      department: form.department,
      lossAmount: form.lossAmount
    }
    try {
      if (form.id) {
        await updateEventInfo({ id: form.id, ...payload })
        ElMessage.success('修改成功')
      } else {
        await saveEventReport(payload)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      loadData()
    } catch (e) {
      ElMessage.error(form.id ? '修改失败' : '新增失败')
    }
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除事件「${row.eventName}」吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteEventInfo(row.id)
      ElMessage.success('删除成功')
      loadData()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 构建查询参数（空值与'全部'不传）
const buildParams = () => {
  const params = {}
  if (queryForm.eventType && queryForm.eventType !== '全部') params.eventType = queryForm.eventType
  if (queryForm.eventTime) {
    params.startDate = queryForm.eventTime
    params.endDate = queryForm.eventTime
  }
  if (queryForm.eventLevel && queryForm.eventLevel !== '全部') params.level = queryForm.eventLevel
  if (queryForm.region && queryForm.region !== '全部') params.region = queryForm.region
  if (queryForm.department && queryForm.department !== '全部') params.department = queryForm.department
  if (queryForm.lossRange && queryForm.lossRange !== '全部') params.lossRange = queryForm.lossRange
  return params
}

// 加载列表与统计（并行请求）
const loadData = async () => {
  try {
    const params = buildParams()
    const [pageRes, statsRes] = await Promise.all([
      getEventPage(pageNum.value, pageSize.value, params),
      getEventStats(params)
    ])
    tableData.value = pageRes.data?.records || []
    total.value = pageRes.data?.total || 0
    stats.value = statsRes.data || { totalEvents: 0, totalLoss: 0, avgLoss: 0, majorEvents: 0 }
  } catch (e) {
    ElMessage.error('查询失败')
  }
}

// 等级tag颜色
const levelTagType = (level) => {
  const map = { '一般': 'info', '较大': 'warning', '重大': 'danger', '特别重大': 'danger' }
  return map[level] || 'info'
}

// 状态tag颜色
const statusTagType = (status) => {
  const map = { '待受理': 'warning', '待核实': 'warning', '已核实': 'primary', '处置中': 'primary', '已解除': 'warning', '已关闭': 'success', '不实事件': 'info' }
  return map[status] || 'info'
}

// 查询
const handleQuery = () => {
  pageNum.value = 1
  loadData()
}

// 每页条数变化
const handleSizeChange = () => {
  pageNum.value = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    eventType: '', eventTime: '', eventLevel: '', region: '', department: '', lossRange: ''
  })
  pageNum.value = 1
  loadData()
}

// 初始化查询
loadData()
</script>

<style scoped lang="scss">
.app-container {
  padding: 16px;
}

.inquiry-layout {
  display: flex;
  gap: 16px;
  min-height: calc(100vh - 120px);
}

.left-panel {
  width: 25%;
  min-width: 260px;
  flex-shrink: 0;

  .el-card {
    height: 100%;
  }
}

.right-panel {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.panel-title {
  font-weight: 600;
  font-size: 15px;
  display: flex;
  align-items: center;
  gap: 8px;

  .total-count {
    font-weight: 400;
    font-size: 13px;
    color: #909399;
  }
}

// 统计卡片
.stat-cards {
  display: flex;
  gap: 16px;
}

.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #ebeef5;
  text-align: center;
  transition: box-shadow 0.3s;

  &:hover {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }

  .stat-value {
    font-size: 28px;
    font-weight: 700;
    color: #303133;
    line-height: 1.2;
  }

  .stat-label {
    font-size: 13px;
    color: #909399;
    margin-top: 8px;
  }
}

.stat-card-warning {
  border-left: 3px solid #e6a23c;

  .stat-value { color: #e6a23c; }
}

.stat-card-info {
  border-left: 3px solid #409eff;

  .stat-value { color: #409eff; }
}

.stat-card-danger {
  border-left: 3px solid #f56c6c;

  .stat-value { color: #f56c6c; }
}

// 左侧表单间距调整
.left-panel {
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  :deep(.el-form-item__label) {
    padding-bottom: 4px;
  }
}
</style>
