<template>
  <PageContainer title="灾害管理" @click-back="handleClickBack">
    <div class="filter-wrapper">
      <SearchInput style="margin-top: 0" v-model="searchValue" placeholder="请输入地点关键词" @search="handleSearch" />
      <div class="filter-btn-block">
        <van-button @click="showFilter = true">
          <div class="filter-btn">
            <span style="white-space: nowrap">{{ getShortTypeName(selectedDisasterType) }}</span> <van-icon name="filter-o" />
          </div>
        </van-button>
      </div>
    </div>
    <CurrentSite />
    <div class="list-panel">
      <CardItem v-for="(item, index) in list" :key="index" :title="getEventTitle(item)" @click="handleClickItem(item)">
        <template #headerExtra>
          <van-tag :type="getEventStatusType(item.eventStatus)" plain size="medium">
            {{ getEventStatusText(item.eventStatus) }}
          </van-tag>
        </template>

        <div class="info-block">
          <div class="time-box">
            <span class="info-label">发生时间：</span>
            <span class="info-value">{{ item.occurTime || '-' }}</span>
          </div>
          <div class="time-box">
            <span class="info-label">预计恢复时间：</span>
            <span class="info-value">{{ item.expectRecoverTime || '-' }}</span>
          </div>
          <div class="disaster-type-wrapper">
            <van-tag class="tag" type="primary" size="medium" plain>{{ getDisasterTypeText(item) }}</van-tag>
          </div>
        </div>

        <van-icon class="jump-icon-absolute" name="arrow" />
      </CardItem>

      <div v-if="loading" class="loading-wrapper">
        <van-loading size="24px" vertical>加载中...</van-loading>
      </div>

      <EmptyBox v-if="!loading && list.length === 0" :placeholder="emptyText" />
    </div>

    <van-button type="primary" class="footer-btn" @click="handleAdd">灾害填报</van-button>

    <!-- 筛选组件：v-model 绑定选中的值，visible 控制显示隐藏 -->
    <TagFilter v-model="selectedDisasterType" :visible="showFilter" :tags="disasterTypes" @update:visible="showFilter = $event" @confirm="handleFilterConfirm" />
  </PageContainer>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import { showToast, Tag as VanTag, Loading as VanLoading, Icon as VanIcon, Button as VanButton, showImagePreview } from 'vant'
import PageContainer from '@/components/PageContainer.vue'
import SearchInput from '@/components/SearchInput.vue'
import CardItem from '@/components/CardItem.vue'
import EmptyBox from '@/components/EmptyBox.vue'
import CurrentSite from '@/components/CurrentSite.vue'
import TagFilter from '@/components/TagFilter.vue'
import { request } from '@shared/utils/request'

const router = useRouter()

// 搜索关键词
const searchValue = ref('')

// 列表数据
const list = ref([])

// 加载状态
const loading = ref(false)

// 空状态文本
const emptyText = ref('暂无相关灾毁信息')

// 筛选弹窗显示状态
const showFilter = ref(false)

// 当前选中的灾毁类型（通过 v-model 传给 TagFilter）
const selectedDisasterType = ref(null)

// 灾毁类型列表（根据实际数据中的路况类别或其他字段定义）
const disasterTypes = [
  { label: '全部', value: null },
  { label: '边坡坍塌', value: '边坡坍塌' },
  { label: '泥石流', value: '泥石流' },
  { label: '路基沉陷', value: '路基沉陷' },
  { label: '山体滑坡', value: '山体滑坡' },
  { label: '行道树倒塌', value: '行道树倒塌' },
  { label: '积水', value: '积水' },
  { label: '积雪', value: '积雪' },
  { label: '其他', value: '其他' }
]

// 获取事件标题
const getEventTitle = (item) => {
  const parts = []
  if (item.occurLocation) parts.push(item.occurLocation)
  if (item.routeNo) parts.push(item.routeNo)
  // if(item.disasterType) parts.push(item.disasterType == 'WATER_DAMAGE' ? '发生水毁灾害' : '发生冰雪灾害')
  if (item.roadConditionType) parts.push('发生' + item.roadConditionType)

  if (parts.length > 0) {
    return parts.join('')
  }
  return '未命名事件'
}

// 获取事件状态文本
const getEventStatusText = (status) => {
  // eventStatus: 0-未解除 1-已解除
  return status === 1 ? '已解除' : '未解除'
}

// 获取事件状态类型（用于标签颜色）
const getEventStatusType = (status) => {
  return status === 1 ? 'success' : 'danger'
}

// 获取灾毁类型文本（根据实际情况映射）
const getDisasterTypeText = (item) => {
  if (item.roadConditionType) {
    return item.roadConditionType
  }
}

// 获取简短类型名称
const getShortTypeName = (type) => {
  const typeMap = {
    边坡坍塌: '边坡',
    泥石流: '泥石',
    路基沉陷: '路基',
    山体滑坡: '滑坡',
    行道树倒塌: '树倒',
    积水: '积水',
    积雪: '积雪',
    其他: '其他',
    未抢险: '待抢险',
    抢险中: '抢险中',
    已完成: '已完成',
    高速公路: '高速',
    国道: '国道',
    省道: '省道'
  }
  return typeMap[type] || (type ? type.substring(0, 2) : '全部')
}

// 获取灾毁列表数据
const getDisasterList = async (keyword = '', disasterType = null) => {
  loading.value = true

  try {
    const result = await request({
      url: '/snow-ops-platform/unified-disaster/list',
      method: 'get',
      params: {
        pageSize: 999,
        keyword: keyword.trim(),
        roadConditionType: disasterType || undefined
      }
    })
    if (result?.data?.records) {
      list.value = result.data.records.map((item) => ({
        ...item,
        // 数据转换，确保前端使用的字段存在
        title: getEventTitle(item),
        status: getEventStatusText(item.eventStatus),
        occurTime: item.occurTime,
        estimateRecoverTime: item.expectRecoverTime
      }))
    } else {
      showToast(result.message || '获取数据失败')
      list.value = []
    }
  } catch (error) {
    console.error('获取灾毁列表失败:', error)
    showToast('获取数据失败，请稍后重试')
    list.value = []
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  getDisasterList(searchValue.value, selectedDisasterType.value)
}

// 筛选确认
const handleFilterConfirm = (type) => {
  // selectedDisasterType 已经通过 v-model 更新，这里只需重新请求数据
  getDisasterList(searchValue.value, type)
}

// 点击返回
const handleClickBack = () => {
  router.push('/')
}

// 点击列表项
const handleClickItem = (item) => {
  if (item.disasterType === 'WATER_DAMAGE') {
    router.push({
      path: '/waterDisasterDetail',
      query: {
        id: item.id
      }
    })
  }
  if (item.disasterType === 'ICE_SNOW') {
    router.push({
      name: 'IceEventDetail',
      query: {
        id: item.relationId
      }
    })
  }
}

// 灾毁填报
const handleAdd = () => {
  router.push('/disasterReport')
}

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

<style lang="scss" scoped>
.list-panel {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding-bottom: 80px;
}

.filter-wrapper {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-top: 10px;

  .filter-btn-block {
    display: flex;
    flex-wrap: nowrap;
    .filter-btn {
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
    }
  }
}

:deep(.card-item) {
  position: relative;
}

.info-block {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding-right: 24px;
}

.time-box {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
}

.info-label {
  font-weight: 400;
  font-size: 13px;
  color: #999999;
}

.info-value {
  font-weight: 400;
  font-size: 14px;
  color: #333333;
}

.jump-icon-absolute {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  color: rgba(102, 102, 102, 0.4);
  cursor: pointer;
}

.disaster-type-wrapper {
  margin-top: 4px;
}

.footer-btn {
  position: fixed;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  width: calc(100% - 32px);
  max-width: 340px;
  border-radius: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  cursor: pointer;
  z-index: 10;

  &:active {
    opacity: 0.9;
    transform: translateX(-50%) scale(0.98);
  }
}

.loading-wrapper {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

:deep(.van-button) {
  &.active {
    background-color: #1989fa;
    color: #fff;
    border-color: #1989fa;
  }
}
:deep(.van-tag) {
  white-space: nowrap;
}
</style>
