<template>
  <div class="disaster-form-page">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="140px" class="disaster-form" @submit.prevent>
      <!-- 基础信息区块 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <span class="section-title">基础信息</span>
          </div>
        </template>

        <el-row :gutter="24">
          <!-- 填报人员信息 -->
          <el-col :span="24">
            <div class="sub-section-title">填报人员信息</div>
          </el-col>
          <el-col :span="8">
            <el-form-item label="填报单位" prop="reportUnit">
              <el-input v-model="formData.reportUnit" placeholder="请输入填报单位" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>

          <!-- 路况事件信息 -->
          <el-col :span="24">
            <div class="sub-section-title">路况事件信息</div>
          </el-col>
          <el-col :span="8">
            <el-form-item label="事件类型" prop="eventType">
              <el-select v-model="formData.eventType" placeholder="请选择" style="width: 100%">
                <el-option label="水毁灾害" value="水毁灾害" />
                <el-option label="冰雪灾害" value="冰雪灾害" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="路况类别" prop="blockedMileage">
              <el-input-number v-model="formData.blockedMileage" :min="0" :precision="3" style="width: 100%" placeholder="请填写" />
              <span class="unit-suffix">公里</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="是否阻断" prop="isBlocked">
              <el-select v-model="formData.isBlocked" placeholder="请选择" style="width: 100%">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="抢险进度" prop="isBlocked">
              <el-select v-model="formData.isBlocked" placeholder="请选择" style="width: 100%">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="处理措施" prop="measure">
              <el-select v-model="formData.measure" placeholder="请选择" style="width: 100%">
                <el-option label="正常通行" value="正常通行" />
                <el-option label="交通管制" value="交通管制" />
                <el-option label="封闭施工" value="封闭施工" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="水毁处数" prop="waterDamageCount">
              <el-input-number v-model="formData.waterDamageCount" :min="0" :step="1" style="width: 100%" placeholder="请填写" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-row>
              <el-col :span="8">
                <el-form-item label="阻断里程" prop="blockedMileage">
                  <el-input-number v-model="formData.blockedMileage" :min="0" :precision="3" style="width: 100%" placeholder="请填写" />
                  <span class="unit-suffix">公里</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="8">
            <el-form-item label="发现时间" prop="discoverTime">
              <el-date-picker v-model="formData.discoverTime" type="datetime" placeholder="请选择日期时间" style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计恢复" prop="predictRecoverTime">
              <el-date-picker v-model="formData.predictRecoverTime" type="datetime" placeholder="请选择日期时间" style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="现场描述" prop="siteDescription">
              <el-input v-model="formData.siteDescription" type="textarea" :rows="3" placeholder="请输入现场描述及续行方案" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 位置信息区块 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <span class="section-title">位置信息</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="路线类型" prop="routeType">
              <el-select v-model="formData.routeType" placeholder="请选择" style="width: 100%">
                <el-option label="国省道" value="国省道" />
                <el-option label="县乡道" value="县乡道" />
                <el-option label="高速" value="高速" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属区县" prop="district">
              <el-select v-model="formData.district" placeholder="请选择" style="width: 100%">
                <el-option label="万州区" value="万州区" />
                <el-option label="开州区" value="开州区" />
                <el-option label="黔江区" value="黔江区" />
                <el-option label="涪陵区" value="涪陵区" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="地点路线" prop="routeCode">
              <el-input v-model="formData.routeCode" placeholder="请输入地点路线" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="起点桩号" prop="startPile">
              <el-input v-model="formData.startPile" placeholder="K_请填写" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="止点桩号" prop="endPile">
              <el-input v-model="formData.endPile" placeholder="K_请填写" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="路况位置" prop="locationPath">
              <el-cascader v-model="formData.locationPath" :options="locationOptions" placeholder="请选择" style="width: 100%" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="阻断点小地名" prop="smallPlaceName">
              <el-input v-model="formData.smallPlaceName" placeholder="请填写" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="formData.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="formData.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 附件上传区块 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <span class="section-title">附件上传</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="图片上传" prop="images">
              <el-upload
                v-model:file-list="formData.images"
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :limit="9"
                :on-preview="handlePicturePreview"
                :on-remove="handlePictureRemove"
                :before-upload="beforeImageUpload"
                accept="image/jpeg,image/png"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">只能上传jpg/png格式，且不超过500kb</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视频上传" prop="videos">
              <el-upload v-model:file-list="formData.videos" action="#" :auto-upload="false" :limit="3" :before-upload="beforeVideoUpload" accept="video/*">
                <el-button type="primary"
                  ><el-icon><Upload /></el-icon> 选择文件</el-button
                >
              </el-upload>
              <div class="upload-tip">仅支持3M以内的视频</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 灾毁损失区块 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <span class="section-title">灾毁损失</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :span="24">
            <div class="sub-section-title">路况事件信息</div>
          </el-col>
          <el-col :span="8">
            <el-form-item label="受伤人员" prop="injuredCount">
              <el-input-number v-model="formData.injuredCount" :min="0" :step="1" style="width: 100%" />
              <span class="unit-suffix">个</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="死亡人员" prop="deathCount">
              <el-input-number v-model="formData.deathCount" :min="0" :step="1" style="width: 100%" />
              <span class="unit-suffix">个</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="滞留人员" prop="deathCount">
              <el-input-number v-model="formData.deathCount" :min="0" :step="1" style="width: 100%" />
              <span class="unit-suffix">个</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="滞留车辆" prop="strandedVehicles">
              <el-input-number v-model="formData.strandedVehicles" :min="0" :step="1" style="width: 100%" />
              <span class="unit-suffix">辆</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="损坏车辆" prop="damagedVehicles">
              <el-input-number v-model="formData.damagedVehicles" :min="0" :step="1" style="width: 100%" />
              <span class="unit-suffix">辆</span>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <div class="sub-section-title">道路损失及其他</div>
          </el-col>
          <el-col :span="8">
            <el-form-item label="清理方量" prop="clearVolume">
              <el-input-number v-model="formData.clearVolume" :min="0" :precision="2" style="width: 100%" />
              <span class="unit-suffix">立方米</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="填方及损失" prop="fillLoss">
              <el-input v-model="formData.fillLoss" placeholder="填方及损失" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="路面及损失" prop="roadLoss">
              <el-input v-model="formData.roadLoss" placeholder="路面及损失" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="护坡及损失" prop="slopeLoss">
              <el-input v-model="formData.slopeLoss" placeholder="护坡及损失" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="桥梁及损失" prop="bridgeLoss">
              <el-input v-model="formData.bridgeLoss" placeholder="桥梁及损失" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="隧道及损失" prop="tunnelLoss">
              <el-input v-model="formData.tunnelLoss" placeholder="隧道及损失" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="涵洞及损失" prop="culvertLoss">
              <el-input v-model="formData.culvertLoss" placeholder="涵洞及损失" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="护栏" prop="guardrailLength">
              <el-input-number v-model="formData.guardrailLength" :min="0" :precision="3" style="width: 100%" />
              <span class="unit-suffix">公里</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="行道树" prop="roadsideTrees">
              <el-input-number v-model="formData.roadsideTrees" :min="0" :step="1" style="width: 100%" />
              <span class="unit-suffix">棵</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="其他损失" prop="otherLossAmount">
              <el-input-number v-model="formData.otherLossAmount" :min="0" :precision="2" style="width: 100%" />
              <span class="unit-suffix">万元</span>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="其他损失描述" prop="otherLossDesc">
              <el-input v-model="formData.otherLossDesc" type="textarea" :rows="2" placeholder="请输入" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <div class="sub-section-title">已投入机械</div>
          </el-col>
          <el-col :span="8">
            <el-form-item label="投入机械" prop="inputMachinery">
              <el-input-number v-model="formData.inputMachinery" :min="0" :precision="1" style="width: 100%" />
              <span class="unit-suffix">台/班</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="投入人力" prop="inputLabor">
              <el-input-number v-model="formData.inputLabor" :min="0" :step="1" style="width: 100%" />
              <span class="unit-suffix">人</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="投入资金" prop="inputFunds">
              <el-input-number v-model="formData.inputFunds" :min="0" :precision="2" style="width: 100%" />
              <span class="unit-suffix">万元</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 恢复重建预估费用区块 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <span class="section-title">恢复重建预估费用</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="是否需要恢复重建" prop="needReconstruction">
              <el-radio-group v-model="formData.needReconstruction">
                <el-radio label="是">是</el-radio>
                <el-radio label="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="恢复重建预估费用" prop="reconstructionCost">
              <el-input-number v-model="formData.reconstructionCost" :min="0" :precision="2" style="width: 100%" />
              <span class="unit-suffix">万元</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <el-button @click="handleBack">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
      </div>
    </el-form>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="图片预览" width="600px">
      <img :src="previewImageUrl" style="width: 100%" alt="预览图片" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload } from '@element-plus/icons-vue'
import { request } from '@/utils/request'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const submitting = ref(false)

// 是否为编辑模式
const isEdit = computed(() => !!route.query.id)

// 图片预览
const previewDialogVisible = ref(false)
const previewImageUrl = ref('')

// 地点级联选择器选项（示例数据）
const locationOptions = [
  {
    value: 'chongqing',
    label: '重庆市',
    children: [
      {
        value: 'wanzhou',
        label: '万州区',
        children: [
          { value: 'shuanghekou', label: '双河口街道' },
          { value: 'zhoujiaba', label: '周家坝街道' }
        ]
      },
      {
        value: 'kaizhou',
        label: '开州区',
        children: [
          { value: 'hanfeng', label: '汉丰街道' },
          { value: 'wenfeng', label: '文峰街道' }
        ]
      }
    ]
  }
]

// 表单数据
const formData = reactive({
  // 填报人员信息
  reportUnit: '',
  contactPerson: '',
  contactPhone: '',
  // 路况事件信息
  eventType: '',
  dangerDesc: '',
  measure: '',
  isBlocked: '',
  waterDamageCount: 0,
  blockedMileage: 0,
  discoverTime: '',
  predictRecoverTime: '',
  siteDescription: '',
  // 位置信息
  routeType: '国省道',
  district: '',
  routeCode: '',
  routeName: '',
  startPile: '',
  endPile: '',
  locationPath: [],
  smallPlaceName: '',
  longitude: '',
  latitude: '',
  // 附件
  images: [],
  videos: [],
  // 灾毁损失
  injuredCount: 0,
  deathCount: 0,
  strandedVehicles: 0,
  damagedVehicles: 0,
  clearVolume: 0,
  fillLoss: '',
  roadLoss: '',
  slopeLoss: '',
  bridgeLoss: '',
  tunnelLoss: '',
  culvertLoss: '',
  guardrailLength: 0,
  roadsideTrees: 0,
  otherLossAmount: 0,
  otherLossDesc: '',
  inputMachinery: 0,
  inputLabor: 0,
  inputFunds: 0,
  // 恢复重建
  needReconstruction: '是',
  reconstructionCost: 0
})

// 表单校验规则
const formRules = {
  reportUnit: [{ required: true, message: '请输入填报单位', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  eventType: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  isBlocked: [{ required: true, message: '请选择是否阻断', trigger: 'change' }],
  discoverTime: [{ required: true, message: '请选择发现时间', trigger: 'change' }],
  routeType: [{ required: true, message: '请选择路线类型', trigger: 'change' }],
  district: [{ required: true, message: '请选择所属区县', trigger: 'change' }],
  routeCode: [{ required: true, message: '请输入路线编号', trigger: 'blur' }]
}

// 图片上传前校验
const beforeImageUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt500k = file.size / 1024 < 500

  if (!isJpgOrPng) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  if (!isLt500k) {
    ElMessage.error('图片大小不能超过 500KB!')
    return false
  }
  return false // 返回false阻止自动上传，由提交时统一处理
}

// 视频上传前校验
const beforeVideoUpload = (file) => {
  const isLt3M = file.size / 1024 / 1024 < 3
  if (!isLt3M) {
    ElMessage.error('视频大小不能超过 3MB!')
    return false
  }
  return false // 返回false阻止自动上传，由提交时统一处理
}

// 图片预览
const handlePicturePreview = (file) => {
  previewImageUrl.value = file.url
  previewDialogVisible.value = true
}

// 图片移除
const handlePictureRemove = (file, fileList) => {
  formData.images = fileList
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }

    submitting.value = true
    try {
      // 构建提交数据
      const submitData = {
        ...formData,
        // 处理级联选择器值
        locationPath: formData.locationPath.join('/'),
        // 处理附件列表
        imageList: formData.images.map((item) => item.raw),
        videoList: formData.videos.map((item) => item.raw)
      }

      // 模拟提交，实际使用时取消注释
      // if (isEdit.value) {
      //   await request({ url: `/api/water-damage/events/${route.query.id}`, method: 'put', data: submitData })
      //   ElMessage.success('编辑成功')
      // } else {
      //   await request({ url: '/api/water-damage/events', method: 'post', data: submitData })
      //   ElMessage.success('新增成功')
      // }

      await new Promise((resolve) => setTimeout(resolve, 500))
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      router.back()
    } catch (error) {
      ElMessage.error('提交失败，请重试')
      console.error(error)
    } finally {
      submitting.value = false
    }
  })
}

// 加载编辑数据
const loadEditData = async () => {
  if (!isEdit.value) return

  try {
    // 模拟获取详情数据，实际使用时取消注释
    // const response = await request({ url: `/api/water-damage/events/${route.query.id}`, method: 'get' })
    // const data = response.data
    // Object.assign(formData, data)

    // 模拟数据
    await new Promise((resolve) => setTimeout(resolve, 300))
    Object.assign(formData, {
      reportUnit: '万州区公路中心',
      contactPerson: '王强',
      contactPhone: '15978906789',
      eventType: '水毁事件',
      dangerDesc: '抢险中',
      measure: '交通管制',
      isBlocked: '是',
      waterDamageCount: 3,
      blockedMileage: 1.25,
      discoverTime: '2024-07-11 16:00:00',
      predictRecoverTime: '2024-08-12 16:30:00',
      siteDescription: '边坡塌方导致道路中断，正在组织抢通',
      routeType: '国省道',
      district: '万州区',
      routeCode: 'S202',
      routeName: '开云路',
      startPile: 'K17.200',
      endPile: 'K17.350',
      locationPath: ['chongqing', 'wanzhou', 'shuanghekou'],
      smallPlaceName: '三汇口',
      longitude: '108.408',
      latitude: '30.808',
      injuredCount: 0,
      deathCount: 0,
      strandedVehicles: 5,
      damagedVehicles: 1,
      clearVolume: 1200,
      guardrailLength: 0.15,
      roadsideTrees: 8,
      otherLossAmount: 10,
      otherLossDesc: '部分边沟损毁',
      inputMachinery: 6,
      inputLabor: 25,
      inputFunds: 8,
      needReconstruction: '是',
      reconstructionCost: 50
    })
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error(error)
  }
}

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

<style scoped lang="scss">
.disaster-form-page {
  padding: 20px;
  background-color: #f5f7fa;

  .disaster-form {
    .form-section {
      margin-bottom: 20px;

      :deep(.el-card__header) {
        padding: 12px 20px;
        background-color: #fafafa;
        border-bottom: 1px solid #ebeef5;
      }

      :deep(.el-card__body) {
        padding: 20px;
      }
    }

    .section-header {
      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        position: relative;
        padding-left: 10px;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 3px;
          height: 16px;
          background-color: #409eff;
          border-radius: 2px;
        }
      }
    }

    .sub-section-title {
      font-size: 14px;
      font-weight: 500;
      color: #606266;
      margin: 8px 0 16px 0;
      padding-left: 8px;
      border-left: 3px solid #409eff;
    }

    .unit-suffix {
      margin-left: 8px;
      color: #909399;
      font-size: 12px;
    }

    .upload-tip {
      font-size: 12px;
      color: #909399;
      margin-top: 8px;
    }

    .form-actions {
      display: flex;
      justify-content: center;
      gap: 16px;
      padding: 20px 0 40px;
    }
  }
}
</style>
