<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getWarningList, type WarningRecord } from './api/warningApi'
import { generateListItemData } from './utils/common'
import { http } from '@/utils/request'
import { onShow,onLoad } from '@dcloudio/uni-app'
// 定义页面配置
definePage({
  title: '预警记录列表'
})

// 列表数据
const loading = ref(false)
const loadingMore = ref(false)
const pageNum = ref(1)
const hasMore = ref(true)

// 筛选相关变量
const filterStationId = ref('')
const filterStartTime = ref('')
const filterEndTime = ref('')
const filterAlertType = ref('')

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

// 预警场站列表
const stationList = ref<Array<{ value: string; label: string }>>([
  { value: '', label: '全部场站' }
])

// 预警场景列表
const alertTypeList = ref<Array<{ value: string; label: string }>>([
  { value: '', label: '全部场景' }
])

// 获取预警场站列表
async function fetchStationList() {
  try {
    const response = await http.get<any[]>('/sysStation/station/selectAllSysStationList')
    const stationOptions = response.map(item => ({
      value: item.id.toString(),
      label: item.stationName || ''
    }))
    stationList.value = [{ value: '', label: '全部场站' }, ...stationOptions]
  } catch (error) {
    console.error('获取预警场站列表失败:', error)
  }
}

// 获取预警场景列表
async function fetchAlertTypeList() {
  try {
    const response = await http.get<any[]>('/system/dict/data/type/warning_type')
    const alertTypeOptions = response.map(item => ({
      value: item.dictValue,
      label: item.dictLabel || ''
    }))
    alertTypeList.value = [{ value: '', label: '全部场景' }, ...alertTypeOptions]
  } catch (error) {
    console.error('获取预警场景列表失败:', error)
  }
}

// 格式化后的列表数据
const formattedListData = ref<any[]>([])

// 获取预警记录列表
async function fetchWarningList(isLoadMore = false) {
  if (isLoadMore) {
    loadingMore.value = true
  } else {
    loading.value = true
    pageNum.value = 1
    hasMore.value = true
  }

  try {
    const params = {
      pageSize: 10,
      pageNum: pageNum.value,
      stationId: filterStationId.value ? Number(filterStationId.value) : undefined,
      startTime: filterStartTime.value,
      endTime: filterEndTime.value,
      alertType: filterAlertType.value
    }

    const response = await getWarningList(params)
    const newData = response.rows || []

    // 格式化数据
    const formattedData = newData.map(item => generateListItemData(item))

    if (isLoadMore) {
      formattedListData.value = [...formattedListData.value, ...formattedData]
    } else {
      formattedListData.value = formattedData
    }
    // 检查是否还有更多数据
    hasMore.value = newData.length === 10
    // 增加页码
    pageNum.value++
  } catch (error) {
    console.error('获取预警记录列表失败:', error)
    uni.showToast({
      title: '获取预警记录列表失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 处理刷新
function handleRefresh() {
  fetchWarningList()
}

// 处理加载更多
function handleLoadMore() {
  if (!loadingMore.value && hasMore.value) {
    fetchWarningList(true)
  }
}

// 处理日期选择
function handleConfirm(date: any, type: 'start' | 'end') {
  let formattedDate = ''
  if (typeof date === 'object' && date.value) {
    const dateObj = new Date(date.value)
    const year = dateObj.getFullYear()
    const month = String(dateObj.getMonth() + 1).padStart(2, '0')
    const day = String(dateObj.getDate()).padStart(2, '0')
    formattedDate = `${year}-${month}-${day} 00:00:00`
  } else if (typeof date === 'number') {
    const dateObj = new Date(date)
    const year = dateObj.getFullYear()
    const month = String(dateObj.getMonth() + 1).padStart(2, '0')
    const day = String(dateObj.getDate()).padStart(2, '0')
    formattedDate = `${year}-${month}-${day} 00:00:00`
  } else if (typeof date === 'string') {
    if (date.includes('T')) {
      formattedDate = date.replace('T', ' ').substring(0, 19)
    } else if (date.length === 10) {
      formattedDate = date + ' 00:00:00'
    } else {
      formattedDate = date
    }
  }
  
  if (type === 'start') {
    filterStartTime.value = formattedDate
  } else if (type === 'end') {
    filterEndTime.value = formattedDate
  }
}

// 处理筛选确定
function handleFilterConfirm() {
  showFilter.value = false
  fetchWarningList()
}

// 处理重置
function handleReset() {
  filterStationId.value = ''
  filterStartTime.value = ''
  filterEndTime.value = ''
  filterAlertType.value = ''
  fetchWarningList()
}

// 点击跳转到详情
function navigateToDetail(alertId: number) {
  uni.navigateTo({
    url: `/pages/warning/detail?alertId=${alertId}`
  })
}

// 页面加载时获取数据
// onMounted(async () => {})
onLoad(async () => {
  // 获取预警场站列表
  await fetchStationList()
  // 获取预警场景列表
  await fetchAlertTypeList()
})
onShow(() => {
  fetchWarningList()
})
</script>

<template>
  <view class="page min-h-screen bg-gray-100">
    <!-- 列表区域 -->
    <scroll-view
      scroll-y
      class="scroll-container"
      :refresher-enabled="true"
      @refresherrefresh="handleRefresh"
      @scrolltolower="handleLoadMore"
    >
      <!-- 加载中 -->
      <view v-if="loading" class="loading-container">
        <text>加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="formattedListData.length === 0" class="empty-container">
        <text>暂无预警记录</text>
      </view>

      <!-- 列表 -->
      <view v-else class="list">
        <view
          v-for="item in formattedListData"
          :key="item.id"
          class="list-item bg-white mb-2 p-4 flex gap-4"
          @click="navigateToDetail(item.id)"
        >
          <!-- 左侧图片 -->
          <view class="image-container w-24 h-24 flex-shrink-0">
            <image
              :src="(item.snapshotPathUrl[0]) || 'https://via.placeholder.com/100'"
              mode="aspectFill"
              class="w-full h-full rounded"
            ></image>
          </view>

          <!-- 右侧内容 -->
          <view class="content-container flex-1">
            <!-- 上部分：预警类型和状态 -->
            <view class="flex justify-between items-center mb-2">
              <text class="font-medium">{{ item.alertTypeName }}</text>
              <view :class="['status-tag px-2 py-1 rounded text-xs', item.statusStyle]">
                {{ item.statusName }}
              </view>
            </view>

            <!-- 下部分：油站和预警时间 -->
            <view class="flex justify-between items-center">
              <text class="text-gray-600">{{ item.stationName }}</text>
              <text class="text-gray-600 text-sm">{{ item.alertTime }}</text>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="loadingMore" class="loading-more">
          <text>加载中...</text>
        </view>

        <!-- 没有更多数据 -->
        <view v-else-if="!hasMore && formattedListData.length > 0" class="no-more">
          <text>没有更多数据</text>
        </view>
      </view>
    </scroll-view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <view class="filter-btn" @click="showFilter = true">
        <wd-button type="icon" icon="filter" style="color: #fff;"></wd-button>
      </view>
      <view class="refresh-btn" @click="handleRefresh">
        <wd-button type="icon" icon="refresh" style="color: #fff;"></wd-button>
      </view>
    </view>

    <!-- 筛选框 -->
    <wd-popup
      v-model="showFilter"
      position="bottom"
      round
      :overlay="true"
      :close-on-click-overlay="true"
      overlay-class="popup-overlay"
      class="filter-popup-container"
    >
      <view class="filter-popup" style="min-height: 400rpx;">
        <view class="p-4">
          <view class="text-lg font-medium mb-4">筛选条件</view>
          
          <!-- 预警场站 -->
          <view class="mb-4">
            <text class="block mb-2">预警场站</text>
            <wd-picker 
              :columns="[stationList]" 
              v-model="filterStationId" 
            />
          </view>
          
          <!-- 开始时间选择 -->
          <view class="mb-4">
            <text class="block mb-2">开始时间</text>
            <view class="relative">
              <wd-calendar 
                v-model="filterStartTime" 
                @confirm="(date) => handleConfirm(date, 'start')" 
              />
            </view>
          </view>
          
          <!-- 结束时间选择 -->
          <view class="mb-4">
            <text class="block mb-2">结束时间</text>
            <view class="relative">
              <wd-calendar 
                v-model="filterEndTime" 
                @confirm="(date) => handleConfirm(date, 'end')" 
              />
            </view>
          </view>
          
          <!-- 预警场景 -->
          <view class="mb-4">
            <text class="block mb-2">预警场景</text>
            <wd-picker 
              :columns="[alertTypeList]" 
              v-model="filterAlertType" 
            />
          </view>
        </view>
        <view class="flex justify-end m-3">
          <wd-button size="large" type="info" @click="handleReset" style="margin-right: 16rpx;">
            重置
          </wd-button>
          <wd-button size="large" type="primary" @click="handleFilterConfirm">
            确定
          </wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style scoped>
.page {
  background-color: #f5f5f5;
  position: relative;
}

.scroll-container {
  height: 100vh;
  padding-bottom: 200rpx;
}

.list-item {
  background-color: #ffffff;
  border-radius: 8rpx;
  box-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 16rpx;
}

.image-container {
  width: 120rpx;
  height: 120rpx;
  flex-shrink: 0;
}

.content-container {
  flex: 1;
  min-width: 0;
}

.status-tag {
  font-size: 20rpx;
}

.loading-container,
.empty-container,
.loading-more,
.no-more {
  padding: 40rpx 0;
  text-align: center;
  color: #999999;
}

/* 操作按钮 */
.action-buttons {
  position: fixed;
  bottom: 150rpx;
  right: 32rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  z-index: 9;
}

.refresh-btn,
.filter-btn {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #3194F2;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 筛选弹窗 */
.filter-popup {
  width: 100%;
  max-height: 80vh;
}

/* 通用样式 */
.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.gap-2 {
  gap: 16rpx;
}

.gap-4 {
  gap: 32rpx;
}

.mb-2 {
  margin-bottom: 16rpx;
}

.mb-4 {
  margin-bottom: 32rpx;
}

.p-4 {
  padding: 16rpx;
}

.font-medium {
  font-weight: 500;
}

.text-gray-600 {
  color: #666666;
}

.text-sm {
  font-size: 24rpx;
}

.text-lg {
  font-size: 32rpx;
}

.rounded {
  border-radius: 8rpx;
}
</style>
