<template>
  <div class="home">
    <div class="content">
      <PanelItem title="基本信息">
        <van-form class="IceEventAddForm" label-align="left" colon>
          <van-field v-model="form.event.occurTime" label="发生时间" center>
            <template #button>
              <van-button plain round type="primary" size="mini" @click="getCurrentTime">校准时间</van-button>
            </template>
          </van-field>
          <van-field v-model="form.event.occurLocation" label="发生地点" center placeholder="请填写" />
          <van-field v-model="form.event.routeNo" label="线路编号" center placeholder="请填写" />
          <van-field v-model="form.event.startStakeNo" label="起点桩号" center placeholder="请填写" />
          <van-field v-model="form.event.endStakeNo" label="止点桩号" center placeholder="请填写" />
          <van-field v-model="form.event.disasterMileage" label="受灾里程" center type="number" placeholder="请填写" />
        </van-form>
      </PanelItem>

      <PanelItem title="处置情况">
        <van-form class="IceEventAddForm" label-align="left" colon>
          <van-field label="处置措施" center>
            <template #input>
              <div class="disposal-buttons">
                <van-button plain :type="form.event.disposalMeasures === '限速通行' ? 'primary' : 'default'" size="small" @click="toggleDisposal('限速通行')">
                  限速通行
                </van-button>
                <van-button plain :type="form.event.disposalMeasures === '封闭交通' ? 'primary' : 'default'" size="small" @click="toggleDisposal('封闭交通')" class="last-button">
                  封闭交通
                </van-button>
              </div>
            </template>
          </van-field>
          <van-field v-model="form.event.expectRecoverTime" label="预计恢复时间" center placeholder="请选择" readonly clickable @click="showExpectPicker = true" />
          <van-popup :show="showExpectPicker" round position="bottom" close-on-click-overlay @close="showExpectPicker = false">
            <van-picker-group title="选择日期时间" :tabs="['选择日期', '选择时间']" @confirm="handleConfirmExpectTime" @cancel="showExpectPicker = false">
              <van-date-picker v-model="expectDate" :min-date="minDate" :max-date="maxDate" />
              <van-time-picker v-model="expectTime" />
            </van-picker-group>
          </van-popup>
        </van-form>
      </PanelItem>

      <PanelItem title="实施情况">
        <van-form class="IceEventAddForm" label-align="left" colon>
          <van-field v-model="form.material.inputManpower" type="number" label="投入人力" center placeholder="请填写">
            <template #extra> 人次 </template>
          </van-field>
          <van-field v-model="form.material.inputFunds" type="number" label="投入资金" center placeholder="请填写">
            <template #extra> 万元 </template>
          </van-field>
          <van-field v-model="form.material.inputEquipment" type="number" label="投入设备" center placeholder="请填写">
            <template #extra> 台班 </template>
          </van-field>

          <!-- 选择物资列表 -->
          <van-field
            v-for="(material, index) in form.yhzMaterialList"
            :key="material.rid"
            v-model="material.usageAmount"
            type="number"
            @input="checkMaterialAmount(material, index)"
            :label="material.wzmc"
            center
            :placeholder="`余额: ${material.ye} `"
          >
            <template #extra>
              <span style="margin-right: 10px">{{ material.dw }}</span>
              <van-button size="small" type="danger" @click.stop="form.yhzMaterialList.splice(index, 1)"> 删除 </van-button>
            </template>
          </van-field>

          <van-button class="add-wzbtn" type="primary" icon="plus" plain @click="handleOpenAddMaterial">添加物资 </van-button>
          <van-popup :show="showAddMaterialPopup" position="bottom" close-on-click-overlay @close="showAddMaterialPopup = false">
            <div style="padding: 16px">
              <h3 style="text-align: center; margin-bottom: 16px">添加物资</h3>

              <!-- 搜索框 -->
              <van-field v-model="searchText" placeholder="输入物资名称搜索" clearable @update:model-value="handleSearch"> </van-field>

              <van-checkbox-group v-model="checked">
                <van-cell-group inset style="margin: 16px 0">
                  <div style="display: flex; justify-content: space-between; padding: 8px 16px">
                    <span>共 {{ materialList.length }} 项</span>
                    <van-button size="mini" @click="toggleSelectAll" :type="isAllSelected ? 'primary' : 'default'">
                      {{ isAllSelected ? '取消全选' : '全选' }}
                    </van-button>
                  </div>
                  <van-cell v-for="(item, index) in materialList" clickable :key="item.rid" :title="item.wzmc" @click="toggle(index)">
                    <template #right-icon>
                      <van-checkbox :name="item.rid" :ref="(el) => (checkboxRefs[index] = el)" @click.stop />
                    </template>
                  </van-cell>
                </van-cell-group>
              </van-checkbox-group>

              <van-button type="primary" block @click="addSelectedMaterials" style="margin-top: 10px"> 确认添加 </van-button>
            </div>
          </van-popup>

          <van-field label="当前通行情况" center>
            <template #input>
              <div class="disposal-buttons">
                <van-button plain :type="form.traffic.currentStatus === 1 ? 'primary' : 'default'" size="small" @click="form.traffic.currentStatus = 1"> 正常通行 </van-button>
                <van-button plain :type="form.traffic.currentStatus === 2 ? 'primary' : 'default'" size="small" @click="form.traffic.currentStatus = 2"> 限速通行 </van-button>
                <van-button plain :type="form.traffic.currentStatus === 3 ? 'primary' : 'default'" size="small" @click="form.traffic.currentStatus = 3" class="last-button">
                  封闭交通
                </van-button>
              </div>
            </template>
          </van-field>
          <van-field label="有无车辆滞留" center>
            <template #input>
              <div class="disposal-buttons">
                <van-button plain :type="form.traffic.hasStrandedVehicles === 1 ? 'primary' : 'default'" size="small" @click="form.traffic.hasStrandedVehicles = 1">
                  有滞留
                </van-button>
                <van-button
                  plain
                  :type="form.traffic.hasStrandedVehicles === 0 ? 'primary' : 'default'"
                  size="small"
                  @click="
                    () => {
                      form.traffic.hasStrandedVehicles = 0
                      form.traffic.strandedVehicleCount = null
                    }
                  "
                  class="last-button"
                >
                  无滞留
                </van-button>
              </div>
            </template>
          </van-field>
          <van-field v-if="form.traffic.hasStrandedVehicles === 1" v-model="form.traffic.strandedVehicleCount" type="number" label="滞留车辆数" center placeholder="请填写" />

          <van-field v-model="form.traffic.actualRecoverTime" label="实际恢复时间" center placeholder="请选择" readonly clickable @click="showActualPicker = true" />
          <van-popup :show="showActualPicker" round position="bottom" close-on-click-overlay @close="showActualPicker = false">
            <van-picker-group title="选择日期时间" :tabs="['选择日期', '选择时间']" @confirm="handleConfirmActualTime" @cancel="showActualPicker = false">
              <van-date-picker v-model="actualDate" :min-date="minDate" :max-date="maxDate" />
              <van-time-picker v-model="actualTime" />
            </van-picker-group>
          </van-popup>

          <van-field label="附件" center>
            <template #input>
              <van-uploader
                v-model="fileList"
                @delete="handleDelete"
                name="photos"
                :file-list="fileList"
                :file-type="['image/jpeg', 'image/png']"
                :after-read="afterRead"
                multiple
                :max-count="6"
              />
            </template>
          </van-field>
        </van-form>
      </PanelItem>
    </div>

    <van-button type="primary" class="add-btn" @click="handleAdd"> 提交 </van-button>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, toRaw, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showLoadingToast } from 'vant'
import PanelItem from '@/components/PanelItem.vue'
import { request } from '../../../../shared/utils/request'
import { useYHZStore } from '@/stores/yhzStore';

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

// 组件挂载时获取数据
const INIT_FORM = reactive({
  event: {
    occurLocation: '', // 发生地点
    routeNo: '', // 线路编号
    occurTime: '', // 发生时间
    startStakeNo: '', // 起点桩号
    endStakeNo: '', // 止点桩号
    disasterMileage: '', // 受灾里程
    expectRecoverTime: '', // 预计恢复时间
    actualRecoverTime: '', // 实际恢复时间
    serviceStationId: '', // 养护站ID
    district: '', // 所属区县
    reportTime: '', // 填报时间
    reporterPhone: '', // 填报人手机号
    disposalMeasures: '', // 处置措施
    createTime: '', // 创建时间
    updateTime: '', // 更新时间
    isDeleted: '' // 是否删除 0-未删除 1-已删除
  },
  material: {
    inputManpower: null, // 投入人力
    inputFunds: null, // 投入资金
    inputEquipment: null, // 投入设备
    createTime: '', // 创建时间
    updateTime: '' // 更新时间
  },
  traffic: {
    currentStatus: 0, // 当前通行情况 1-正常通行 2-限速通行 3-封闭交通
    hasStrandedVehicles: 0, // 是否有车辆滞留 0-无 1-有
    strandedVehicleCount: null, // 车辆滞留数量
    actualRecoverTime: '', // 实际恢复时间
    createTime: '', // 创建时间
    updateTime: '' // 更新时间
  },
  yhzMaterialList: [], // 养护站物资列表
  photos: []
})
const form = reactive({ ...INIT_FORM })
const fileList = ref([])

// 日期格式化
const formatTime = (date = new Date()) => {
  const pad = (n) => n.toString().padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

const getCurrentTime = () => {
  form.event.occurTime = formatTime()
}

const toggleDisposal = (type) => {
  form.event.disposalMeasures = form.event.disposalMeasures === type ? '' : type
}

// 组件挂载时获取数据
onMounted(() => {
  form.event.occurTime = formatTime() // 初始化为当前时间
})

// 添加物资相关
const showAddMaterialPopup = ref(false)
const materialList = ref([])
const checkboxRefs = ref([])
const checked = ref([])
const toggle = (index) => {
  checkboxRefs.value[index].toggle()
}

const searchText = ref('')
const handleSearch = () => {
  getMaterialList(searchText.value)
}
// 全选功能
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    checked.value = []
  } else {
    checked.value = materialList.value.map((item) => item.rid)
  }
}
// 计算是否全选
const isAllSelected = computed(() => {
  return materialList.value.length > 0 && materialList.value.every((item) => checked.value.includes(item.rid))
})

// 添加物资到表单
const addSelectedMaterials = () => {
  checked.value.forEach((rid) => {
    const material = materialList.value.find((m) => m.rid === rid)
    if (material && !form.yhzMaterialList.some((m) => m.rid === rid)) {
      form.yhzMaterialList.push({
        rid: rid,
        wzmc: material.wzmc,
        usageAmount: null,
        dw: material.dw,
        ye: material.ye
      })
    }
  })
  showAddMaterialPopup.value = false
  checked.value = []
}

// 检查余额
const checkMaterialAmount = (material, index) => {
  if (material.usageAmount > material.ye) {
    showToast({
      type: 'fail',
      message: '输入数量不能超过物资余额'
    })
    // 设置为最大值
    form.yhzMaterialList[index].usageAmount = material.ye
  }
}

// 查询物资列表
const getMaterialList = async (wzmc) => {
  try {
    const data = {
      yhzid: yhzStore.getYHZInfo.id,
      wzmc,
      pageNum: 1,
      pageSize: 9999
    }
    const res = await request({
      url: '/snow-ops-platform/yjwz/list',
      method: 'GET',
      params: data
    })
    if (res.code === '00000') {
      materialList.value = res.data.records
    } else {
      throw new Error(res.message)
    }
  } catch (error) {
    showToast({
      type: 'fail',
      message: error.message
    })
  }
}

// 打开添加物资弹窗
const handleOpenAddMaterial = async () => {
  await getMaterialList()
  showAddMaterialPopup.value = true
}

const handleAdd = async () => {
  try {
    const toast = showLoadingToast({
      message: '上报中...',
      forbidClick: true,
      duration: 0 // 设置为0表示不会自动关闭
    })
    form.event.serviceStationId = yhzStore.getYHZInfo.id
    form.event.district = yhzStore.getYHZInfo.qxmc
    console.log('yhzDetail', toRaw(yhzStore.getYHZInfo))
    console.log('form', toRaw(form))
    const res = await request({
      url: '/snow-ops-platform/event/add',
      method: 'POST',
      data: form
    })
    if (res.code === '00000') {
      toast.close()
      showToast({
        type: 'success',
        message: '上报成功'
      })
      setTimeout(() => {
        router.replace('/disasterManagement')
      }, 500)
    } else {
      toast.close()
      throw new Error(res.message)
    }
  } catch (error) {
    showToast({
      type: 'fail',
      message: error.message
    })
  }
}

const expectDate = ref([])
const expectTime = ref([])
const actualDate = ref([])
const actualTime = ref([])

// 预计恢复时间相关
const showExpectPicker = ref(false)
const minDate = new Date()
const maxDate = new Date(2050, 11, 31)
const handleConfirmExpectTime = () => {
  const [year, month, day] = expectDate.value
  const [hour, minute] = expectTime.value
  form.event.expectRecoverTime =
    `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ` + `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00`
  showExpectPicker.value = false
}
// 实际恢复时间相关
const showActualPicker = ref(false)
const handleConfirmActualTime = () => {
  const [year, month, day] = actualDate.value
  const [hour, minute] = actualTime.value
  form.traffic.actualRecoverTime =
    `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ` + `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00`
  showActualPicker.value = false
}

// 在打开选择器时设置初始值
watch(showExpectPicker, (val) => {
  if (val) {
    const current = form.event.expectRecoverTime ? new Date(form.event.expectRecoverTime) : new Date()
    expectDate.value = [current.getFullYear(), current.getMonth() + 1, current.getDate()]
    expectTime.value = [current.getHours(), current.getMinutes()]
  }
})
watch(showActualPicker, (val) => {
  if (val) {
    const current = form.traffic.actualRecoverTime ? new Date(form.traffic.actualRecoverTime) : new Date()
    actualDate.value = [current.getFullYear(), current.getMonth() + 1, current.getDate()]
    actualTime.value = [current.getHours(), current.getMinutes()]
  }
})

// 文件上传
const afterRead = async (file) => {
  try {
    const toast = showLoadingToast({
      message: '上传中...',
      forbidClick: true,
      duration: 0 // 设置为0表示不会自动关闭
    })
    const formData = new FormData()
    formData.append('file', file.file)
    const res = await request({
      url: '/snow-ops-platform/file/upload',
      method: 'post',
      data: formData
    })
    toast.close()
    if (res.code === '00000') {
      form.photos.push({ photoUrl: res.data })
      const index = fileList.value.findIndex((f) => f.file === file.file)
      if (index !== -1) {
        fileList.value[index].serverUrl = res.data
      }

      console.log('form.photos', toRaw(form.photos))
      console.log('fileList.value', fileList.value)
    } else {
      throw new Error(res.message)
    }
  } catch (error) {
    toast.close()
    showToast({
      type: 'fail',
      message: error.message
    })
  }
}

// 文件删除
const handleDelete = (file) => {
  if (file.serverUrl) {
    const index = form.photos.findIndex((p) => p.photoUrl === file.serverUrl)
    if (index !== -1) {
      form.photos.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.home {
  /* 自动匹配导航栏高度 */
}

.content {
}

.content .van-cell-group .van-cell {
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.add-wzbtn {
  width: calc(100% - 32px);
  margin: 10px 16px;
}

.add-btn {
  position: fixed;
  bottom: 20px;
  left: 16px;
  right: 16px;
  width: calc(100% - 32px);
  margin: 0 auto;
  border-radius: 24px;
  font-size: 16px;
  height: 44px;
  z-index: 999;
}

.grid {
  margin-top: 16px;
}

.btn {
  margin-top: 24px;
}

.status-tag {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
}

.status-good {
  background-color: #07c160;
}

.status-warning {
  background-color: #ff976a;
}

.status-danger {
  background-color: #ee0a24;
}

.disposal-buttons {
  display: flex;
  gap: 10px;
  padding: 8px 0;
}

.disposal-buttons .van-button {
  flex: 1;
}

.last-button {
  margin-right: 16px;
}
</style>
