<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="设备名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.deviceId`" :rules="formRules.deviceId" class="mb-0px!">
            <el-select
              v-model="row.deviceId"
              placeholder="请选择设备"
              @change="handleDeviceChange($event, row)"
              clearable
              filterable
            >
              <el-option
                v-for="device in deviceList"
                :key="device.id"
                :label="device.deviceName"
                :value="device.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="设备编码" min-width="150">
        <template #default="{ row }">
          <el-input
v-model="row.deviceNumber"
                    placeholder="请选择设备"
                    readonly
                    disabled />
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加设备巡检计划范围</el-button>
  </el-row>
</template>

<script setup lang="ts">
import { InspectionPlanApi } from '@/api/device/inspectionplan'
import { InfoApi } from '@/api/device/info'

const props = defineProps<{
  planId: number // 计划id（主表的关联字段）
}>()

const formLoading = ref(false) // 表单的加载中
const formData = ref<any[]>([])
const formRules = reactive({
  deviceId: [{ required: true, message: '设备不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

// 设备列表
const deviceList = ref<any[]>([])

/** 获取设备列表 */
const loadDeviceList = async () => {
  try {
    const res = await InfoApi.getInfoPage({
      pageNo: 1,
      pageSize: 100,
    })
    deviceList.value = res.list || []
  } catch (error) {
    console.error('获取设备列表失败:', error)
  }
}

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.planId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return
    }
    try {
      formLoading.value = true
      // 并行加载设备列表和计划范围列表
      const [deviceRes, planScopeData] = await Promise.all([
        InfoApi.getInfoPage({
          pageNo: 1,
          pageSize: 100,
        }),
        InspectionPlanApi.getInspectionPlanScopeListByPlanId(val)
      ])
      deviceList.value = deviceRes.list || []

      // 处理回显数据，根据deviceId查找设备信息并填充deviceNumber
      const processedData = planScopeData.map(item => {
        const device = deviceList.value.find(d => d.id === item.deviceId)
        return {
          ...item,
          deviceNumber: device ? device.deviceNumber : item.deviceNumber
        }
      })
      formData.value = processedData
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    planId: undefined,
    deviceId: undefined,
    deviceNumber: undefined
  }
  row.planId = props.planId as any
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 设备选择变化处理 */
const handleDeviceChange = (deviceId, row) => {
  if (deviceId) {
    const selectedDevice = deviceList.value.find(device => device.id === deviceId)
    if (selectedDevice) {
      row.deviceNumber = selectedDevice.deviceNumber
    }
  } else {
    row.deviceNumber = undefined
  }
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 - 过滤掉deviceNumber，只传递必要的字段 */
const getData = () => {
  return formData.value.map(item => {
    const { deviceNumber, ...rest } = item
    return rest
  })
}

// 初始化时加载设备列表
loadDeviceList()

defineExpose({ validate, getData })
</script>

<style scoped>
:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  color: #606266;
}
</style>
