<template>
  <div class="water-disaster-pc">
    <!-- 合并后的单个卡片 -->
    <el-card class="form-card" shadow="never">
      <div slot="header" class="card-header">
        <span>续报信息</span>
      </div>

      <!-- 所有表单项合并到一个区域，每行一个 -->
      <el-form :model="formData" label-width="120px" size="small">
        <!-- 处置措施 -->
        <el-form-item label="处置措施">
          <el-select v-model="formData.report.disposalMeasures">
            <el-option label="半幅封闭" value="半幅封闭" />
            <el-option label="全副封闭" value="全副封闭" />
            <el-option label="便道通行" value="便道通行" />
            <el-option label="正常通行" value="正常通行" />
          </el-select>
        </el-form-item>

        <!-- 预计恢复时间 -->
        <el-form-item label="预计恢复时间">
          <el-date-picker
            v-model="formData.report.expectRecoverTime"
            type="datetime"
            placeholder="请选择时间"
            value-format="yyyy-MM-dd HH:mm"
            :picker-options="pickerOptions"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 实际恢复时间 -->
        <el-form-item label="实际恢复时间">
          <el-date-picker
            v-model="formData.report.actualRecoverTime"
            type="datetime"
            placeholder="请选择时间"
            value-format="yyyy-MM-dd HH:mm"
            :picker-options="pickerOptions"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 受伤人员 -->
        <el-form-item label="受伤人员">
          <el-input-number v-model="formData.report.injuredCount" :min="0" :controls="false" placeholder="请填写" style="width: 300px">
            <template slot="append">人</template>
          </el-input-number>
        </el-form-item>

        <!-- 死亡人员 -->
        <el-form-item label="死亡人员">
          <el-input-number v-model="formData.report.deadCount" :min="0" :controls="false" placeholder="请填写" style="width: 300px">
            <template slot="append">人</template>
          </el-input-number>
        </el-form-item>

        <!-- 滞留人员 -->
        <el-form-item label="滞留人员">
          <el-input-number v-model="formData.report.strandedPersonCount" :min="0" :controls="false" placeholder="请填写" style="width: 300px">
            <template slot="append">人</template>
          </el-input-number>
        </el-form-item>

        <!-- 损坏车辆 -->
        <el-form-item label="损坏车辆">
          <el-input-number v-model="formData.report.damagedVehicleCount" :min="0" :controls="false" placeholder="请填写" style="width: 300px">
            <template slot="append">辆</template>
          </el-input-number>
        </el-form-item>

        <!-- 滞留车辆 -->
        <el-form-item label="滞留车辆">
          <el-input-number v-model="formData.report.strandedVehicleCount" :min="0" :controls="false" placeholder="请填写" style="width: 300px">
            <template slot="append">辆</template>
          </el-input-number>
        </el-form-item>

        <!-- 损失列表组件 -->
        <loss-list :col-span="24" v-model="formData.lossList" />

        <!-- 处理情况 -->
        <el-form-item label="处理情况">
          <el-input v-model="formData.report.remark" type="textarea" :rows="2" placeholder="请填写（选填）" style="width: 60%" />
        </el-form-item>

        <!-- 损失总金额 -->
        <el-form-item label="损失总金额">
          <el-input v-model="formData.report.totalLossAmount" placeholder="请填写（选填）" style="width: 300px">
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>

        <!-- 已投机械 -->
        <el-form-item label="已投机械">
          <el-input v-model="formData.report.investedMachinery" placeholder="请填写" style="width: 300px">
            <template slot="append">台/班</template>
          </el-input>
        </el-form-item>

        <!-- 投入人力 -->
        <el-form-item label="投入人力">
          <el-input-number v-model="formData.report.investedManpower" :min="0" :controls="false" placeholder="请填写" style="width: 300px">
            <template slot="append">人次</template>
          </el-input-number>
        </el-form-item>

        <!-- 投入资金 -->
        <el-form-item label="投入资金">
          <el-input v-model="formData.report.investedFunds" placeholder="请填写" style="width: 300px">
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>

        <!-- 现场描述 -->
        <el-form-item label="现场描述">
          <el-input v-model="formData.report.siteDescription" type="textarea" :rows="2" placeholder="请填写" style="width: 60%" />
        </el-form-item>

        <!-- 是否需要恢复重建 -->
        <el-form-item label="是否需要恢复重建">
          <el-radio-group v-model="formData.event.needsRecovery">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">追加记录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { request } from '@shared/utils/request'
import LossList from '../WaterDisasterReport/WaterDisasterLossListPC.vue'

// Props 定义
const props = defineProps({
  value: {
    type: Object,
    default: () => ({})
  }
})

// Emits 定义
const emit = defineEmits(['input', 'change'])

// 表单数据
const formData = reactive({
  occurLocation: '',
  occurTime: '',
  roadConditionType: '',
  routeNo: '',
  event: {
    blockedMileage: '',
    blockedPointName: '',
    contactPerson: '',
    contactPhone: '',
    damageCount: '',
    district: '',
    endStakeNo: '',
    estimatedRecoveryCost: '',
    inspectionMileage: '',
    isBlocked: '',
    needsRecovery: '',
    repairProgress: '',
    reporterUnit: '',
    startStakeNo: ''
  },
  report: {
    actualRecoverTime: '',
    damagedVehicleCount: '',
    deadCount: '',
    disposalMeasures: '',
    expectRecoverTime: '',
    injuredCount: '',
    investedFunds: '',
    investedMachinery: '',
    investedManpower: '',
    remark: '',
    siteDescription: '',
    strandedPersonCount: '',
    strandedVehicleCount: '',
    totalLossAmount: ''
  },
  lossList: [],
  fileList: []
})

// 处置措施单选值
const disposalMeasureValue = ref('')

// 下拉选项
const roadConditionOptions = [
  { label: '高速公路', value: '高速公路' },
  { label: '国道', value: '国道' },
  { label: '省道', value: '省道' },
  { label: '县道', value: '县道' },
  { label: '乡道', value: '乡道' },
  { label: '村道', value: '村道' }
]

const blockedOptions = [
  { label: '是', value: true },
  { label: '否', value: false }
]

const repairProgressOptions = [
  { label: '未抢险', value: '未抢险' },
  { label: '抢险中', value: '抢险中' },
  { label: '已完成', value: '已完成' }
]

// 日期选择器配置
const pickerOptions = {
  disabledDate(time) {
    return time.getTime() < new Date(2020, 0, 1) || time.getTime() > new Date(2030, 11, 31)
  }
}

// 监听处置措施单选值变化
watch(disposalMeasureValue, (newVal) => {
  formData.report.disposalMeasures = newVal
})

// 监听外部传入的值
watch(
  () => props.value,
  (newVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      initFormData(newVal)
    }
  },
  { immediate: true, deep: true }
)

// 监听表单数据变化，向外传递
watch(
  () => formData,
  (newVal) => {
    emit('input', newVal)
    emit('change', newVal)
  },
  { deep: true }
)

// 从 report.disposalMeasures 初始化处置措施单选值
watch(
  () => formData.report.disposalMeasures,
  (newVal) => {
    if (newVal && typeof newVal === 'string') {
      disposalMeasureValue.value = newVal
    }
  },
  { immediate: true }
)

// 初始化表单数据
const initFormData = (data) => {
  Object.assign(formData, {
    occurLocation: data.occurLocation || '',
    occurTime: data.occurTime || '',
    roadConditionType: data.roadConditionType || '',
    routeNo: data.routeNo || '',
    event: { ...formData.event, ...(data.event || {}) },
    report: { ...formData.report, ...(data.report || {}) },
    lossList: data.lossList || [],
    fileList: data.fileList || []
  })

  if (data.report?.disposalMeasures) {
    disposalMeasureValue.value = data.report.disposalMeasures
  }
}

// 校准时间
const calibrateTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  formData.occurTime = `${year}-${month}-${day} ${hours}:${minutes}`
  ElMessage.success('时间已校准为当前时间')
}

// 表单验证
const validate = () => {
  return true
}

// 获取表单数据
const getFormData = () => {
  return { ...formData }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    occurLocation: '',
    occurTime: '',
    roadConditionType: '',
    routeNo: '',
    event: {
      blockedMileage: '',
      blockedPointName: '',
      contactPerson: '',
      contactPhone: '',
      damageCount: '',
      district: '',
      endStakeNo: '',
      estimatedRecoveryCost: '',
      inspectionMileage: '',
      isBlocked: '',
      needsRecovery: '',
      repairProgress: '',
      reporterUnit: '',
      startStakeNo: ''
    },
    report: {
      actualRecoverTime: '',
      damagedVehicleCount: '',
      deadCount: '',
      disposalMeasures: '',
      expectRecoverTime: '',
      injuredCount: '',
      investedFunds: '',
      investedMachinery: '',
      investedManpower: '',
      remark: '',
      siteDescription: '',
      strandedPersonCount: '',
      strandedVehicleCount: '',
      totalLossAmount: ''
    },
    lossList: [],
    fileList: []
  })
  disposalMeasureValue.value = ''
}

const handleSubmit = async () => {
  // 验证表单
  if (!validate()) {
    return
  }

  try {
    // 获取表单数据

    // 添加事件类型和站点信息
    const submitData = {
      ...formData
      // 可以在这里添加站点信息等其他数据
    }

    const res = await request({
      url: '/snow-ops-platform/water-damage/addOrUpdate',
      method: 'post',
      data: submitData
    })

    if (res?.code === '00000') {
      ElMessage.success('提交成功')

      emit("refresh")
    } else {
      ElMessage.error(res.message)
    }
  } catch (error) {
    ElMessage.error('提交失败，请重试')
    console.error('提交失败:', error)
  } finally {

  }
}

// 暴露方法给父组件
defineExpose({
  validate,
  initFormData,
  getFormData,
  resetForm,
  calibrateTime,
})
</script>

<style lang="scss" scoped>
.water-disaster-pc {
  background-color: #f5f7fa;
  height: 100%;

  .form-card {
    border-radius: 8px;

    .card-header {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      border-left: 4px solid #409eff;
      padding-left: 12px;
    }
  }

  ::v-deep .el-form-item {
    margin-bottom: 22px;
  }

  ::v-deep .el-input-group__append {
    padding: 0 10px;
  }

  ::v-deep .el-input-number {
    width: 300px;

    .el-input-group__append {
      padding: 0 10px;
    }
  }

  ::v-deep .el-radio-group {
    .el-radio {
      margin-right: 20px;
    }
  }
}
</style>
