<template>
  <PageContainer title="灾毁详情" @click-back="handleClickBack" class="page-container">
    <!-- 当前站点信息 -->
    <CurrentSite />

    <!-- 基本信息 -->
    <PanelItem title="基本信息">
      <template #headerExtra>
        <div class="status-wrapper">
          <van-tag :type="getEventStatusType()" size="medium" plain>
            {{ getEventStatusText() }}
          </van-tag>
        </div>
      </template>

      <!-- 事件类型 -->
      <div class="info-row">
        <span class="info-label">事件类型：</span>
        <span class="info-value">水毁事件</span>
      </div>

      <!-- 路况类别 -->
      <div class="info-row">
        <span class="info-label">路况类别：</span>
        <span class="info-value">{{ detailData.roadConditionType || '-' }}</span>
      </div>

      <!-- 是否阻断 -->
      <div class="info-row">
        <span class="info-label">是否阻断：</span>
        <span class="info-value">{{ detailData.event?.isBlocked ? '是' : '否' }}</span>
      </div>

      <!-- 抢险进度 -->
      <div class="info-row">
        <span class="info-label">抢险进度：</span>
        <span class="info-value">{{ detailData.event?.repairProgress || '-' }}</span>
      </div>

      <!-- <div class="info-row">
        <span class="info-label">处理措施：</span>
        <span class="info-value">{{ formatDisposalMeasures(detailData.event?.disposalMeasures) || '-' }}</span>
      </div> -->

      <!-- 水毁处数 -->
      <div class="info-row">
        <span class="info-label">水毁处数：</span>
        <span class="info-value">{{ detailData.event?.damageCount || 0 }}</span>
      </div>

      <!-- 阻断里程 -->
      <div class="info-row">
        <span class="info-label">阻断里程：</span>
        <span class="info-value">{{ detailData.event?.blockedMileage ? detailData.event.blockedMileage + '公里' : '-' }}</span>
      </div>

      <!-- 发生时间 -->
      <div class="info-row">
        <span class="info-label">发生时间：</span>
        <span class="info-value">{{ detailData.occurTime || '-' }}</span>
      </div>

      <!-- 线路编号 -->
      <div class="info-row">
        <span class="info-label">线路编号：</span>
        <span class="info-value">{{ detailData.routeNo || '-' }}</span>
      </div>

      <!-- 地点路线 -->
      <div class="info-row">
        <span class="info-label">地点路线：</span>
        <span class="info-value">{{ detailData.occurLocation || '-' }}</span>
      </div>

      <!-- 起点桩号及经纬度 -->
      <div class="info-row">
        <span class="info-label">起点桩号：</span>
        <span class="info-value">{{ detailData.event?.startStakeNo || '-' }}</span>
      </div>
      <div class="info-row sub-row">
        <span class="info-label">起点桩经度：</span>
        <span class="info-value">{{ detailData.event?.startStakeLng || '-' }}</span>
      </div>
      <div class="info-row sub-row">
        <span class="info-label">起点桩纬度：</span>
        <span class="info-value">{{ detailData.event?.startStakeLat || '-' }}</span>
      </div>

      <!-- 止点桩号及经纬度 -->
      <div class="info-row">
        <span class="info-label">止点桩号：</span>
        <span class="info-value">{{ detailData.event?.endStakeNo || '-' }}</span>
      </div>
      <div class="info-row sub-row">
        <span class="info-label">止点桩经度：</span>
        <span class="info-value">{{ detailData.event?.endStakeLng || '-' }}</span>
      </div>
      <div class="info-row sub-row">
        <span class="info-label">止点桩纬度：</span>
        <span class="info-value">{{ detailData.event?.endStakeLat || '-' }}</span>
      </div>

      <!-- 路况位置（使用阻断点小地名或发生地点） -->
      <div class="info-row">
        <span class="info-label">路况位置：</span>
        <span class="info-value">{{ detailData.event?.blockedPointName || detailData.occurLocation || '-' }}</span>
      </div>

      <!-- 阻断点小地名 -->
      <div class="info-row">
        <span class="info-label">阻断点小地名：</span>
        <span class="info-value">{{ detailData.event?.blockedPointName || '-' }}</span>
      </div>

      <!-- 上报区县 -->
      <div class="info-row">
        <span class="info-label">上报区县：</span>
        <span class="info-value">{{ detailData.event?.district || '-' }}</span>
      </div>

      <!-- 巡查里程 -->
      <div class="info-row">
        <span class="info-label">巡查里程：</span>
        <span class="info-value">{{ detailData.event?.inspectionMileage ? detailData.event.inspectionMileage + '公里' : '-' }}</span>
      </div>

      <!-- 是否恢复重建 -->
      <div class="info-row">
        <span class="info-label">是否恢复重建：</span>
        <span class="info-value">{{ detailData.event?.needsRecovery ? '是' : '否' }}</span>
      </div>

      <!-- 恢复重建预估费用 -->
      <div class="info-row">
        <span class="info-label">恢复重建预估费用：</span>
        <span class="info-value">{{ detailData.event?.estimatedRecoveryCost ? detailData.event.estimatedRecoveryCost + '万元' : '-' }}</span>
      </div>

      <!-- 联系人 -->
      <div class="info-row">
        <span class="info-label">联系人：</span>
        <span class="info-value">{{ detailData.event?.contactPerson || '-' }}</span>
      </div>

      <!-- 联系电话 -->
      <div class="info-row">
        <span class="info-label">联系电话：</span>
        <span class="info-value">{{ detailData.event?.contactPhone || '-' }}</span>
      </div>

      <!-- 填报单位 -->
      <div class="info-row">
        <span class="info-label">填报单位：</span>
        <span class="info-value">{{ detailData.event?.reporterUnit || '-' }}</span>
      </div>
    </PanelItem>

    <!-- 填报信息 -->
    <PanelItem title="填报信息">
      <!-- 遍历所有填报记录（首报 + 续报） -->
      <div v-for="(report, index) in allReports" :key="index" class="report-section">
        <div class="report-header">
          <span class="report-title">{{ report?.title }}</span>
          <span class="report-meta">{{ report.reporterName || '-' }} {{ report.reportTime || '-' }}</span>
        </div>
        <div class="report-content">
          <div class="info-row">
            <span class="info-label">处置措施：</span>
            <span class="info-value">{{ formatDisposalMeasures(report.disposalMeasures) || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">塌方及损失：</span>
            <span class="info-value">{{ getLossDescription(report) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">路产损失：</span>
            <span class="info-value">{{ report.totalLossAmount ? report.totalLossAmount + '万元' : '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">有无车辆滞留：</span>
            <span class="info-value">{{ getVehicleStrandedText(report) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">滞留车辆：</span>
            <span class="info-value">{{ report.strandedVehicleCount || 0 }}辆</span>
          </div>
          <div class="info-row">
            <span class="info-label">预计恢复时间：</span>
            <span class="info-value">{{ report.expectRecoverTime || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">实际恢复时间：</span>
            <span class="info-value">{{ report.actualRecoverTime || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">现场描述：</span>
            <span class="info-value">{{ report.siteDescription || '-' }}</span>
          </div>
          <!-- 附件 -->
          <div class="info-row" v-if="report.fileList && report.fileList.length > 0">
            <span class="info-label">附件：</span>
            <div class="attachment-list">
              <div v-for="(file, fileIndex) in report.fileList" :key="fileIndex" class="attachment-item">
                <van-icon :name="file.fileType === 1 ? 'photo-o' : 'video-o'" />
                <span class="file-name">{{ file.fileName }}</span>
                <van-button size="mini" type="primary" plain @click="previewFile(file)">预览</van-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 无填报信息时显示 -->
      <EmptyBox v-if="!hasReportData" placeholder="暂无填报信息" />
    </PanelItem>

    <!-- 底部按钮：未解除状态显示续报按钮 -->
    <div class="footer-buttons">
      <van-button type="primary" class="footer-btn"  @click="handleContinueReport">续报</van-button>
    </div>
  </PageContainer>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import PageContainer from '@/components/PageContainer.vue'
import PanelItem from '@/components/PanelItem.vue'
import CurrentSite from '@/components/CurrentSite.vue'
import EmptyBox from '@/components/EmptyBox.vue'
import { request } from '@shared/utils/request'

const router = useRouter()
const route = useRoute()

// 详情数据（对应 Data 接口）
const detailData = ref({
  event: null,           // Event 对象
  reportList: [],        // 填报列表（包含首报和续报）
  fileList: [],          // 附件列表
  lossList: [],          // 损失列表
  occurLocation: '',
  occurTime: '',
  roadConditionType: '',
  routeNo: ''
})

const allReports = computed(() => {
  const reports = detailData.value.reportList?.map((item, index)=>{
    item.title = index == 0 ? '首报' : ('续报' + index)
    return item
  }) || []
  return reports.reverse()
})

// 是否有填报数据
const hasReportData = computed(() => {
  return allReports.value.length > 0
})


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

// 获取事件状态类型
const getEventStatusType = () => {
  return detailData.eventStatus === 1 ? 'success' : 'danger'
}

// 格式化处置措施（逗号分隔转中文）
const formatDisposalMeasures = (measures) => {
  if (!measures) return ''
  const measureMap = {
    '半幅封闭': '半幅封闭',
    '全副封闭': '全副封闭',
    '便道通行': '便道通行',
    '正常通行': '正常通行'
  }
  return measures
    .split(',')
    .map((m) => measureMap[m.trim()] || m.trim())
    .join('、')
}

// 获取损失描述（从 lossList 计算塌方体积和总损失）
const getLossDescription = (report) => {
  const lossList = report?.lossList
  if (!lossList || lossList.length === 0) return '-'

  const totalVolume = lossList.reduce((sum, loss) => {
    const volume = (loss.length || 0) * (loss.width || 0) * (loss.height || 0)
    return sum + volume
  }, 0)

  const totalAmount = lossList.reduce((sum, loss) => sum + (loss.totalAmount || 0), 0)

  return `${totalVolume}方，共损失${totalAmount}万元`
}

// 获取车辆滞留文本
const getVehicleStrandedText = (report) => {
  const count = report?.strandedVehicleCount || 0
  return count > 0 ? `有车滞留，共${count}辆` : '无车滞留'
}

// 获取灾毁详情
const getDisasterDetail = async () => {
  const id = route.query.id
  if (!id) {
    showToast('缺少灾毁ID')
    return
  }

  try {
    const result = await request({
      url: `/snow-ops-platform/water-damage/getById`,
      method: 'get',
      params: { id }
    })

    if (result?.data) {
      // 接口返回 Data 结构
      const data = result.data
      detailData.value = {
        event: data.event || null,
        reportList: data.report || [],  // 直接使用 reportList，包含首报和续报
        fileList: data.fileList || [],
        lossList: data.lossList || [],
        occurLocation: data.occurLocation || '',
        occurTime: data.occurTime || '',
        roadConditionType: data.roadConditionType || '',
        routeNo: data.routeNo || ''
      }
    } else {
      showToast(result.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取灾毁详情失败:', error)
    showToast('获取详情失败，请稍后重试')
  }
}

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

// 续报
const handleContinueReport = () => {
  router.push({
    path: '/disasterReport',
    query: {
      id: route.query.id,
      eventId: detailData.value.event?.id,
      isContinue: 'true'
    }
  })
}

// 预览附件
const previewFile = (file) => {
  if (file.fileUrl) {
    window.open(file.fileUrl, '_blank')
  }
}

onMounted(() => {
  getDisasterDetail()
})
</script>

<style scoped lang="scss">
.page-container {
  padding-bottom: 80px;
}

.status-wrapper {
  border-bottom: 1px solid #ebedf0;
}

.info-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  line-height: 1.4;

  &.sub-row {
    margin-left: 20px;
    margin-top: -8px;
  }
}

.info-label {
  width: 110px;
  flex-shrink: 0;
  color: #969799;
  font-size: 14px;
}

.info-value {
  flex: 1;
  color: #323233;
  font-size: 14px;
  word-break: break-all;
}

.report-section {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebedf0;

  &:last-child {
    border-bottom: none;
    margin-bottom: 0;
  }
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #ebedf0;

  .report-title {
    font-size: 16px;
    font-weight: 500;
    color: #1989fa;
  }

  .report-meta {
    font-size: 12px;
    color: #969799;
  }
}

.report-content {
  .info-row {
    margin-bottom: 10px;
  }
}

.attachment-list {
  flex: 1;

  .attachment-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    padding: 8px;
    background: #f7f8fa;
    border-radius: 4px;

    .van-icon {
      font-size: 20px;
      color: #1989fa;
    }

    .file-name {
      flex: 1;
      font-size: 13px;
      color: #323233;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.footer-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 12px;
  padding: 12px 16px;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 10;

  .footer-btn {
    flex: 1;
    height: 44px;
    border-radius: 22px;
    font-size: 16px;
  }
}
</style>