<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.type" placeholder="请选择" clearable>
                <el-option label="水毁事件" value="WATER_DAMAGE" />
                <el-option label="冰雪灾害" value="ICE_SNOW" />
              </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.blocked" placeholder="请选择" clearable>
                <el-option v-for="(option, idx) in options['yesOrNoBool']" :label="option.label" :value="option.value" :key="idx" />
              </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.routeType" placeholder="请选择" clearable>
                <el-option v-for="(option, idx) in options['roadType']" :label="option.label" :value="option.value" :key="idx" />
              </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="district" label="所属区县" min-width="120">
            <template #default="{ row }">
              <span>{{ getDistrictName(row.district) }}</span>
            </template>
          </el-table-column>
          <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="startStakeNo" label="起点桩号" min-width="110" show-overflow-tooltip />
          <el-table-column prop="endStakeNo" label="终点桩号" min-width="110" show-overflow-tooltip />
          <el-table-column prop="roadConditionLocation" label="路况位置" min-width="150" show-overflow-tooltip />
          <el-table-column prop="isBlocked" label="是否阻断" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="row.blocked === true ? 'danger' : 'success'" size="small">
                {{ row.blocked === true ? '是' : row.blocked === false ? '否' : '—' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="disasterType" label="事件类型" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.disasterType == 'ICE_SNOW'">冰雪灾害</span>
              <span v-if="row.disasterType == 'WATER_DAMAGE'">水毁灾害</span>
            </template>
          </el-table-column>
          <el-table-column prop="roadConditionType" label="路况类别" min-width="110" show-overflow-tooltip />
          <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="disposalMeasures" label="处理措施" min-width="150" 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-icon style="font-size: 18px; cursor: pointer" v-if="row.images && row.images.length > 0" @click="viewImages(row)"><Picture /></el-icon>
              <span v-else>—</span>
            </template>
          </el-table-column>
          <el-table-column label="视频" width="80" align="center">
            <template #default="{ row }">
              <el-icon v-if="row.videos && row.videos.length > 0" style="font-size: 18px; cursor: pointer" @click="viewVideos(row)"><VideoPlay /></el-icon>
              <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>

    <el-image-viewer v-if="showPreviewImage && selectedRow" :url-list="selectedRow.images" show-progress @close="showPreviewImage = false" />
    <VideoPreviewDialog ref="videoPreviewDialog" />
  </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'
import { Picture, VideoPlay } from '@element-plus/icons-vue'
import VideoPreviewDialog from '@/component/VideoPreviewDialog.vue'
import { useOptions } from '@shared/composables/useOptions'

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

const showPreviewImage = ref(false)
const selectedRow = ref(null)

const videoPreviewDialog = ref(null)

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

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

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

const getDistrictName = (districtId) => {
  if (!options.value.area?.length) return '-'
  return options.value.area.find((item) => item.value === districtId)?.label || '-'
}

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

  if (dateRange.value && dateRange.value.length === 2) {
    params.startTime = dateRange.value[0] + ' 00:00:00'
    params.endTime = dateRange.value[1] + ' 23:59:59'
  }

  // 过滤空字符串或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/pc/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.type = ''
  filterForm.eventStatus = ''
  filterForm.blocked = ''
  filterForm.routeType = ''
  filterForm.pushStatus = ''
  dateRange.value = null
  handleQuery()
}

// 查看详情
const handleDetail = (row) => {
  if (row.disasterType == 'WATER_DAMAGE') {
    router.push({ path: '/waterDisasterDetail', query: { id: row.relationId } })
  }
  if (row.disasterType == 'ICE_SNOW') {
    router.push({ path: '/iceDisasterDetail', query: { id: row.relationId } })
  }
}

// 编辑
const handleEdit = (row) => {
  if (row.disasterType == 'WATER_DAMAGE') {
    router.push({ path: '/waterDisasterDetail', query: { id: row.relationId, mode: 'edit' } })
  }
  if (row.disasterType == 'ICE_SNOW') {
    router.push({ path: '/iceDisasterDetail', query: { id: row.relationId, mode: 'edit' } })
  }
}

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

// 查看图片
const viewImages = (row) => {
  selectedRow.value = row
  showPreviewImage.value = true
}

// 查看视频
const viewVideos = (row) => {
  videoPreviewDialog.value.show({
    url: row.videos[0],
    title: row.eventName
  })
}

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

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

// 初始化加载数据
onMounted(() => {
  getAreaOptions()

  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>
