<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" :border="true" 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}.deviceName`" :rules="formRules.deviceId" class="mb-0px!">
            <el-select
                v-model="row.deviceName"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词搜索设备"
                :remote-method="searchDevice"
                :loading="deviceSearchLoading"
                @change="(value) => {
                  row.deviceId = value
                  row.deviceName = deviceOptions.find((item) => item.id === value)?.deviceName
                  row.deviceNumber = deviceOptions.find((item) => item.id === value)?.deviceNumber
                  row.deviceCategoryName = deviceOptions.find((item) => item.id === value)?.deviceCategoryName
                }"
                style="width: 100%"
            >
              <el-option
                  v-for="item in deviceOptions"
                  :key="item.id"
                  :label="`${item.deviceNumber} - ${item.deviceName}`"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="设备编号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.deviceNumber`"  class="mb-0px!">
            <el-input v-model="row.deviceNumber" disabled />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="设备类别" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.deviceCategoryName`"  class="mb-0px!">
            <el-input v-model="row.deviceCategoryName" disabled  />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" style="display: block; text-align: left; ">
    <el-button @click="handleAdd" round>+ 添加保养范围</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { InfoApi } from '@/api/device/info'
import { MaintenancePlanApi } from '@/api/device/maintenanceplan'

const props = defineProps<{
  planId: number // 计划id（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref<any[]>([])
const formRules = reactive({
  planId: [{ required: true, message: '计划id不能为空', trigger: 'change' }],
  deviceId: [{ required: true, message: '设备id不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.planId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await MaintenancePlanApi.getMaintenancePlanScopeListByPlanId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

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

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

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

/** 表单值 */
const getData = () => {
  return formData.value
}

/** 搜索设备 */
const deviceSearchLoading = ref(false) // 设备搜索加载状态
const deviceOptions = ref<any[]>([]) // 设备选项
const searchDevice = async (query: string) => {
  if (!query) {
    deviceOptions.value = []
    return
  }
  deviceSearchLoading.value = true
  try {
    // 调用API搜索设备
    const response = await InfoApi.getInfoPage({
      pageSize: 10,
      pageNo: 1,
      // deviceNumber: query,
      deviceName: query
    })

    deviceOptions.value = response.list || []
  } catch (error) {
    console.error('搜索设备失败:', error)
    deviceOptions.value = []
  } finally {
    deviceSearchLoading.value = false
  }
}

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