<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

import { selectAllSysStationAreaList } from '#/api/system/infoEntry/stationInfo/stationInfo'
import { getFirstAidKitList, updateFirstAidKit } from '#/api/oilstation/firstaidkit/firstaidkit'

// 油站数据
const stations = ref<any[]>([])
// 急救箱用品数据
const firstAidItems = reactive<any[]>([])
// 加载状态
const loading = ref(false)
// 选中的油站
const selectedStation = ref('')
// 是否处于编辑状态
const isEditing = ref(false)

// 获取油站列表
const fetchStations = async () => {
  try {
    const response = await selectAllSysStationAreaList()
    const data = response || []
    stations.value = Array.isArray(data) ? data.map(item => ({
      label: item.stationName,
      value: item.id.toString()
    })) : []
    
    // 默认选中第一个油站
    if (stations.value.length > 0) {
      selectedStation.value = stations.value[0].value
      fetchFirstAidKitList()
    }
  } catch (error) {
    console.error('获取油站列表失败:', error)
    ElMessage.error('获取油站列表失败')
  }
}

// 获取急救箱用品列表
const fetchFirstAidKitList = async () => {
  if (!selectedStation.value) return
  
  loading.value = true
  try {
    const response = await getFirstAidKitList(Number(selectedStation.value))
    console.log('获取急救箱用品列表响应:', response)
    const data = response || []
    
    // 处理数据格式，确保与页面显示字段匹配
    firstAidItems.splice(0, firstAidItems.length)
    if (Array.isArray(data)) {
      data.forEach(item => {
        firstAidItems.push({
          id: item.id,
          itemId: item.itemId,
          name: item.name || `用品${item.itemId}`, // 如果没有名称，使用默认名称
          unit: item.unit || '', // 如果没有单位，使用空字符串
          standardQty: item.standardQuantity || 0, // 标准数量
          checkQty: item.checkedQuantity || 0, // 检查数量
          stationId: item.stationId
        })
      })
    }
  } catch (error) {
    console.error('获取急救箱用品列表失败:', error)
    ElMessage.error('获取急救箱用品列表失败')
  } finally {
    loading.value = false
  }
}

// 保存修改
const saveChanges = async () => {
  if (!selectedStation.value) {
    ElMessage.warning('请选择油站')
    return
  }
  
  loading.value = true
  try {
    // 构建保存数据格式
    const saveData = firstAidItems.map(item => ({
      id: item.id,
      itemId: item.itemId,
      checkedQuantity: item.checkQty,
      stationId: Number(selectedStation.value)
    }))
    
    await updateFirstAidKit(saveData)
    ElMessage.success('保存成功')
    // 保存成功后，退出编辑状态
    isEditing.value = false
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 当油站变更时，重新获取急救箱用品列表
const handleStationChange = () => {
  fetchFirstAidKitList()
  // 切换油站时，重置编辑状态
  isEditing.value = false
}

// 点击修改按钮，进入编辑状态
const handleEdit = () => {
  if (!selectedStation.value) {
    ElMessage.warning('请选择油站')
    return
  }
  isEditing.value = true
}

// 组件挂载时获取油站列表
onMounted(() => {
  fetchStations()
})
</script>

<template>
  <div class="first-aid-kit">
    <div class="search-container">
      <el-form :inline="true" label-position="right">
        <el-form-item label="油站" label-width="80px">
          <el-select 
            v-model="selectedStation" 
            placeholder="请选择油站" 
            style="width: 200px"
            @change="handleStationChange"
          >
            <el-option
              v-for="station in stations"
              :key="station.value"
              :label="station.label"
              :value="station.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <el-table 
        v-loading="loading" 
        :data="firstAidItems" 
        border 
        style="width: 100%"
      >
        <el-table-column prop="name" label="用品名称"/>
        <el-table-column prop="unit" label="单位"/>
        <el-table-column prop="standardQty" label="标准数量"/>
        <el-table-column prop="checkQty" label="检查数量">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.checkQty"
              :min="0"
              size="small"
              style="width: 120px"
              :disabled="!isEditing"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="action-container">
      <el-button 
        v-if="!isEditing"
        type="primary" 
        @click="handleEdit"
      >
        修改
      </el-button>
      <el-button 
        v-else
        type="primary" 
        @click="saveChanges"
        :loading="loading"
      >
        保存
      </el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.first-aid-kit {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  
  .search-container {
    margin-bottom: 20px;
  }
  
  .table-container {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .action-container {
    text-align: left;
  }
}
</style>
