<template>
  <div class="page-container">
    <!-- 筛选栏 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" label-width="100px" @submit.prevent>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="所属单位">
              <el-input v-model="filterForm.unit" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="发生地点">
              <el-input v-model="filterForm.occurLocation" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="路线编号">
              <el-input v-model="filterForm.routeNo" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="事件类别">
              <el-select v-model="filterForm.disasterType" placeholder="请选择" clearable>
                <el-option label="水毁事件" value="水毁事件" />
                <el-option label="塌方事件" value="塌方事件" />
                <el-option label="泥石流" value="泥石流" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="事件状态">
              <el-select v-model="filterForm.eventStatus" placeholder="请选择" clearable>
                <el-option label="未解除" :value="0" />
                <el-option label="已解除" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="是否阻断">
              <el-select v-model="filterForm.isBlocked" placeholder="请选择" clearable>
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="路线类型">
              <el-select v-model="filterForm.roadConditionType" placeholder="请选择" clearable>
                <el-option label="国省道" value="国省道" />
                <el-option label="县乡道" value="县乡道" />
                <el-option label="高速" value="高速" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="日期">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="toReport">新增</el-button>
              <el-button type="success" @click="handleExport">导出Excel</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格卡片 -->
    <el-card class="table-card" shadow="never">
      <div class="table-container">
        <el-table :data="tableData" border stripe v-loading="loading" style="width: 100%" height="100%">
          <el-table-column label="序号" width="60">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="routeNo" label="所属区县" min-width="120" />
          <el-table-column prop="routeNo" label="路线编号" min-width="120" />
          <el-table-column prop="routeName" label="路线名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="startPile" label="起点桩号" min-width="110" />
          <el-table-column prop="endPile" label="终点桩号" min-width="110" />
          <el-table-column prop="occurLocation" label="发生地点" min-width="180" show-overflow-tooltip />
          <el-table-column prop="isBlocked" label="是否阻断" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isBlocked === '是' ? 'danger' : 'success'" size="small">
                {{ row.isBlocked || '—' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="disasterType" label="灾害类型" min-width="120" />
          <el-table-column prop="roadConditionType" label="路线类别" min-width="110" />
          <el-table-column prop="eventStatus" label="事件状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.eventStatus === 1 ? 'success' : 'danger'" size="small">
                {{ row.eventStatus === 1 ? '已解除' : '未解除' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="measure" label="处理措施" min-width="120" show-overflow-tooltip />
          <el-table-column prop="occurTime" label="发生时间" width="170" />
          <el-table-column prop="expectRecoverTime" label="预计恢复时间" width="170" />
          <el-table-column prop="contactPerson" label="联系人" width="110" />
          <el-table-column prop="contactPhone" label="联系电话" width="120" />
          <el-table-column label="图片" width="80" align="center">
            <template #default="{ row }">
              <el-button v-if="row.hasImage" link type="primary" size="small" @click="viewImages(row)">查看</el-button>
              <span v-else>—</span>
            </template>
          </el-table-column>
          <el-table-column label="视频" width="80" align="center">
            <template #default="{ row }">
              <el-button v-if="row.hasVideo" link type="primary" size="small" @click="viewVideos(row)">播放</el-button>
              <span v-else>—</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="handleDetail(row)">详情</el-button>
              <el-button link type="warning" size="small" @click="handleEdit(row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { request } from '@/utils/request'

const router = useRouter()

// 筛选表单
const filterForm = reactive({
  unit: '', // 所属单位
  occurLocation: '', // 发生地点
  routeNo: '', // 路线编号
  disasterType: '', // 灾害类型/事件类别
  eventStatus: '', // 事件状态 (0-未解除, 1-已解除)
  isBlocked: '', // 是否阻断
  roadConditionType: '', // 路线类型
  pushStatus: '' // 推送状态
})

// 日期范围
const dateRange = ref(null)

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 构建查询参数
const buildQueryParams = () => {
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    unit: filterForm.unit,
    occurLocation: filterForm.occurLocation,
    routeNo: filterForm.routeNo,
    disasterType: filterForm.disasterType,
    eventStatus: filterForm.eventStatus,
    isBlocked: filterForm.isBlocked,
    roadConditionType: filterForm.roadConditionType
  }

  if (dateRange.value && dateRange.value.length === 2) {
    params.startDate = dateRange.value[0]
    params.endDate = dateRange.value[1]
  }

  // 过滤空字符串或null的参数
  Object.keys(params).forEach((key) => {
    if (params[key] === '' || params[key] === null || params[key] === undefined) {
      delete params[key]
    }
  })
  return params
}

// 查询数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = buildQueryParams()

    // 实际接口调用
    const response = await request({
      url: '/snow-ops-platform/unified-disaster/list',
      method: 'get',
      params
    })

    if (response.code === '00000') {
      const records = response.data.records || response.data || []
      tableData.value = records.map((item) => ({
        ...item,
        // 转换状态显示
        eventStatusText: item.eventStatus === 1 ? '已解除' : '未解除',
        // 保留原始数据
        ...item
      }))
      pagination.total = response.data.total || records.length
    } else {
      ElMessage.error(response.message || '查询失败')
    }
  } catch (error) {
    ElMessage.error('数据加载失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  pagination.currentPage = 1
  fetchData()
}

// 导出Excel
const handleExport = async () => {
  try {
    const params = buildQueryParams()
    const response = await request({
      url: '/api/disaster/record/export',
      method: 'post',
      data: params,
      responseType: 'blob'
    })

    // 创建下载链接
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = `水毁事件列表_${new Date().getTime()}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
    console.error(error)
  }
}

// 重置筛选条件
const resetFilters = () => {
  filterForm.unit = ''
  filterForm.occurLocation = ''
  filterForm.routeNo = ''
  filterForm.disasterType = ''
  filterForm.eventStatus = ''
  filterForm.isBlocked = ''
  filterForm.roadConditionType = ''
  filterForm.pushStatus = ''
  dateRange.value = null
  handleQuery()
}

// 查看详情
const handleDetail = (row) => {
  router.push({ path: '/disasterDetail', query: { id: row.id } })
}

// 编辑
const handleEdit = (row) => {
  router.push({ path: '/disasterReport', query: { id: row.id, mode: 'edit' } })
}

// 新增跳转
const toReport = () => {
  router.push('/disasterReport')
}

// 查看图片
const viewImages = (row) => {
  if (row.images && row.images.length) {
    // 打开图片预览
    ElMessage.info('图片预览功能开发中')
  } else {
    ElMessage.info('暂无图片')
  }
}

// 查看视频
const viewVideos = (row) => {
  if (row.videos && row.videos.length) {
    ElMessage.info('视频播放功能开发中')
  } else {
    ElMessage.info('暂无视频')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchData()
}

// 页码改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchData()
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
  background-color: #f5f7fa;
  box-sizing: border-box;
  overflow: hidden;

  .filter-card {
    flex-shrink: 0;
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .table-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 0;
      overflow: hidden;
    }
  }

  .table-container {
    flex: 1;
    overflow: hidden;
    padding: 0 20px;

    :deep(.el-table) {
      --el-table-border-color: #ebeef5;
    }
  }

  .pagination-container {
    flex-shrink: 0;
    padding: 16px 20px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #ebeef5;
  }
}
</style>
