<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getWarningDetail, handleWarning, type WarningRecord } from './api/warningApi'
import { getWarningId, formatDateTime } from './utils/common'
import HandleForm from './components/HandleForm.vue'

// 定义页面配置
definePage({
  title: '预警记录详情'
})

// 预警详情数据
const warningDetail = ref<WarningRecord>({
  alertId: 0,
  alertCode: '',
  cameraId: 0,
  detectRecordId: 0,
  alertType: '',
  alertLevel: '',
  confidence: 0,
  snapshotUrl: [],
  snapshotPathUrl: [],
  alertTime: '',
  status: '',
  handleUserId: 0,
  handleTime: '',
  handleRemark: '',
  location: '',
  stationId: 0,
  stationName: '',
  stationManagerId: 0,
  stationManagerName: '',
  stationManagerPhone: '',
  areaId: 0,
  areaManagerId: 0,
  areaManagerName: '',
  areaManagerPhone: ''
})

const loading = ref(true)
const handleLoading = ref(false)
const showHandleForm = ref(false)

// 获取预警详情
async function fetchWarningDetail() {
  const alertId = getWarningId()
  if (!alertId) {
    uni.showToast({
      title: '预警ID不能为空',
      icon: 'none'
    })
    return
  }

  try {
    loading.value = true
    const response = await getWarningDetail(alertId)
    warningDetail.value = response
  } catch (error) {
    console.error('获取预警详情失败:', error)
    uni.showToast({
      title: '获取预警详情失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 处理预警
function handleWarningRecord() {
  showHandleForm.value = true
}

// 处理表单提交
async function submitHandleForm(data: { handleRemark: string }) {
  try {
    handleLoading.value = true
    await handleWarning({
      alertId: warningDetail.value.alertId,
      handleAction: data.handleAction,
      handleContent: data.handleContent
    })
    uni.showToast({
      title: '处理成功',
      icon: 'success'
    })
    // 重新获取详情
    await fetchWarningDetail()
  } catch (error) {
    console.error('处理预警失败:', error)
    uni.showToast({
      title: '处理失败',
      icon: 'none'
    })
  } finally {
    handleLoading.value = false
  }
}

// 获取预警类型名称
function getAlertTypeName(alertType: string): string {
  const typeMap = {
    fire: '火焰',
    smoke: '烟雾',
    fire_danger: '火灾',
    intrusion: '入侵'
  }
  return typeMap[alertType as keyof typeof typeMap] || alertType
}

// 获取预警级别名称
function getAlertLevelName(alertLevel: string): string {
  const levelMap = {
    '1': '一般',
    '2': '重要',
    '3': '紧急'
  }
  return levelMap[alertLevel as keyof typeof levelMap] || alertLevel
}

// 获取状态名称
function getStatusName(status: string): string {
  const statusMap = {
    unhandled: '未处理',
    handling: '处理中',
    resolved: '已解决',
    false_alarm: '误报'
  }
  return statusMap[status as keyof typeof statusMap] || status
}

// 页面加载时获取预警详情
onMounted(() => {
  fetchWarningDetail()
})
</script>

<template>
  <view class="work-order-detail">
    <!-- 加载中 -->
    <view v-if="loading" class="loading-container">
      <text>加载中...</text>
    </view>

    <!-- 预警详情内容 -->
    <view v-else class="detail-content">
      <!-- 标题区域 -->
      <view class="detail-header bg-white p-4 mb-2">
        <view class="flex justify-between items-center mb-3">
          <view class="flex items-center gap-2">
            <text class="text-2xl font-bold">{{ warningDetail.alertCode }}</text>
          </view>
          <view :class="[
            'status-tag px-3 py-1 rounded-full text-sm',
            warningDetail.status === 'unhandled' ? 'bg-red-100 text-red-600' :
            warningDetail.status === 'handling' ? 'bg-blue-100 text-blue-600' :
            warningDetail.status === 'resolved' ? 'bg-green-100 text-green-600' :
            'bg-gray-100 text-gray-600'
          ]">
            {{ getStatusName(warningDetail.status) }}
          </view>
        </view>

        <!-- 预警基本信息 -->
        <view class="info-grid grid grid-cols-2 gap-3">
          <view class="info-item">
            <text class="text-gray-500">预警类型</text>
            <text class="block">{{ getAlertTypeName(warningDetail.alertType) }}</text>
          </view>
          <view class="info-item">
            <text class="text-gray-500">预警级别</text>
            <text class="block">{{ getAlertLevelName(warningDetail.alertLevel) }}</text>
          </view>
          <view class="info-item">
            <text class="text-gray-500">预警时间</text>
            <text class="block">{{ formatDateTime(warningDetail.alertTime) }}</text>
          </view>
          <view class="info-item">
            <text class="text-gray-500">识别置信度</text>
            <text class="block">{{ warningDetail.confidence }}%</text>
          </view>
        </view>
      </view>

      <!-- 预警图片 -->
      <view class="image-section bg-white p-4 mb-2">
        <text class="block mb-3 font-medium">预警图片</text>
        <view v-if="warningDetail.snapshotPathUrl" class="image-container">
          <view 
            v-for="(url, index) in warningDetail.snapshotPathUrl" 
            :key="index" 
            class="w-20 h-20 cursor-pointer rounded overflow-hidden"
          >
            <wd-img 
              :width="300" 
              :height="200" 
              :src="url || 'https://via.placeholder.com/100'"  
              :enable-preview="true" 
              class="w-full h-64 object-cover rounded"/>
          </view>
        </view>
        <text v-else class="info-value">无</text>
      </view>

      <!-- 预警位置信息 -->
      <view class="location-section bg-white p-4 mb-2">
        <text class="block mb-3 font-medium">位置信息</text>
        <view class="info-grid grid grid-cols-1 gap-2">
          <view class="info-item">
            <text class="text-gray-500">预警位置</text>
            <text class="block">{{ warningDetail.location || '未知' }}</text>
          </view>
          <view class="info-item">
            <text class="text-gray-500">预警场站</text>
            <text class="block">{{ warningDetail.stationName }}</text>
          </view>
        </view>
      </view>

      <!-- 处理信息 -->
      <view v-if="warningDetail.status !== 'unhandled'" class="handle-section bg-white p-4 mb-2">
        <text class="block mb-3 font-medium">处理信息</text>
        <view class="info-grid grid grid-cols-1 gap-2">
          <view class="info-item">
            <text class="text-gray-500">处理时间</text>
            <text class="block">{{ formatDateTime(warningDetail.handleTime) }}</text>
          </view>
          <view class="info-item">
            <text class="text-gray-500">处理备注</text>
            <text class="block">{{ warningDetail.handleRemark || '无' }}</text>
          </view>
        </view>
      </view>

      <!-- 场站联系人信息 -->
      <view class="contact-section bg-white p-4 mb-2">
        <text class="block mb-3 font-medium">场站联系人</text>
        <view class="info-grid grid grid-cols-1 gap-2">
          <view class="info-item">
            <text class="text-gray-500">站长姓名</text>
            <text class="block">{{ warningDetail.stationManagerName }}</text>
          </view>
          <view class="info-item">
            <text class="text-gray-500">站长电话</text>
            <text class="block">{{ warningDetail.stationManagerPhone }}</text>
          </view>
        </view>
      </view>

      <!-- 底部处理按钮 -->
      <view v-if="warningDetail.status === 'unhandled'" class="bottom-actions">
        <wd-button
          size="medium"
          custom-class="action-btn"
          @click="showHandleForm = true"
        >
          处理
        </wd-button>
      </view>
    </view>

    <!-- 处理表单 -->
    <HandleForm
      v-model:visible="showHandleForm"
      :loading="handleLoading"
      :alert-id="warningDetail.alertId"
      @submit="submitHandleForm"
    />
  </view>
</template>

<style scoped>
.work-order-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}

.detail-content {
  padding-bottom: 120rpx;
}

.detail-header {
  border-bottom: 1rpx solid #e5e7eb;
}

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

.info-grid {
  display: grid;
}

.grid-cols-2 {
  grid-template-columns: repeat(2, 1fr);
}

.grid-cols-1 {
  grid-template-columns: 1fr;
}

.gap-2 {
  gap: 16rpx;
}

.gap-3 {
  gap: 24rpx;
}

.info-item {
  min-width: 0;
}

.info-item text:first-child {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 4rpx;
}

.image-container {
  width: 100%;
}

.image-container image {
  width: 100%;
  height: 256rpx;
  border-radius: 8rpx;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 20rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
}

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

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

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

.gap-2 {
  gap: 16rpx;
}

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

.mb-3 {
  margin-bottom: 24rpx;
}

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

.p-4 {
  padding: 32rpx;
}

.text-2xl {
  font-size: 36rpx;
}

.font-bold {
  font-weight: bold;
}

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

.text-gray-500 {
  color: #999;
}

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

.h-64 {
  height: 256rpx;
}

.object-cover {
  object-fit: cover;
}

.rounded {
  border-radius: 8rpx;
}

.rounded-full {
  border-radius: 9999rpx;
}

.bg-red-100 {
  background-color: #fee2e2;
}

.text-red-600 {
  color: #dc2626;
}

.bg-blue-100 {
  background-color: #dbeafe;
}

.text-blue-600 {
  color: #2563eb;
}

.bg-green-100 {
  background-color: #d1fae5;
}

.text-green-600 {
  color: #059669;
}

.bg-gray-100 {
  background-color: #f3f4f6;
}

.text-gray-600 {
  color: #4b5563;
}

.bg-blue-600 {
  background-color: #2563eb;
}

.text-white {
  color: #ffffff;
}

.w-full {
  width: 100%;
}

.py-3 {
  padding-top: 24rpx;
  padding-bottom: 24rpx;
}
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
  z-index: 9;
}

.action-btn {
  flex: 1;
}

.info-value {
  color: #666;
  font-size: 28rpx;
}
</style>
