<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="900px">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item :label="t('EquipmentManagement.RepairItems.subjectCode')" prop="subjectCode">
        <el-input
          v-model="formData.subjectCode"
          :placeholder="t('EquipmentManagement.RepairItems.placeholderSubjectCode')"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.RepairItems.subjectName')" prop="subjectName">
        <el-input
          v-model="formData.subjectName"
          :placeholder="t('EquipmentManagement.RepairItems.placeholderSubjectName')"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.RepairItems.deviceType')" prop="deviceType">
        <el-radio-group v-model="formData.deviceType">
          <el-radio :label="1">{{ t('EquipmentManagement.RepairItems.deviceTypeDevice') }}</el-radio>
          <el-radio :label="2">{{ t('EquipmentManagement.RepairItems.deviceTypeComponent') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="showDeviceSelect" :label="t('EquipmentManagement.RepairItems.device')" prop="deviceId">
        <el-select
          v-model="formData.deviceId"
          filterable
          remote
          reserve-keyword
          clearable
          :remote-method="handleDeviceSearch"
          :loading="deviceLoading"
          :placeholder="t('EquipmentManagement.RepairItems.placeholderDevice')"
          class="!w-full"
        >
          <el-option v-for="opt in deviceOptions" :key="String(opt.value)" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="showComponentSelect" :label="t('EquipmentManagement.RepairItems.component')" prop="componentId">
        <el-select
          v-model="formData.componentId"
          clearable
          :loading="componentLoading"
          :placeholder="t('EquipmentManagement.RepairItems.placeholderComponent')"
          class="!w-full"
        >
          <el-option v-for="opt in componentOptions" :key="String(opt.value)" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <!--
      <el-form-item label="检验方式" prop="inspectionMethod">
        <el-select v-model="formData.inspectionMethod" placeholder="请选择检验方式" clearable filterable class="!w-full">
          <el-option v-for="dict in inspectionMethodOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="值类型" prop="valueType">
        <el-select v-model="formData.valueType" placeholder="请选择值类型" clearable filterable class="!w-full">
          <el-option v-for="dict in valueTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="判定基准" prop="judgmentCriteria">
        <el-input v-model="formData.judgmentCriteria" placeholder="请输入判定基准" type="textarea" />
      </el-form-item>
      -->
      <el-form-item :label="t('EquipmentManagement.RepairItems.projectContent')" prop="projectContent">
        <el-input
          v-model="formData.projectContent"
          :placeholder="t('EquipmentManagement.RepairItems.placeholderProjectContent')"
          type="textarea"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.RepairItems.isEnable')" prop="isEnable">
        <el-radio-group v-model="formData.isEnable">
          <el-radio v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)" :key="dict.value" :label="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('common.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { RepairItemsApi, RepairItemVO } from '@/api/mes/repairItems'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { DeviceLedgerApi, DeviceLedgerVO } from '@/api/mes/deviceledger'

defineOptions({ name: 'RepairItemsForm' })

const { t } = useI18n()
const message = useMessage()

const dictStore = useDictStoreWithOut()
const dictReady = ref(false)

// const inspectionMethodOptions = computed(() => (dictReady.value ? getStrDictOptions('Inspection_method') : []))
// const valueTypeOptions = computed(() => (dictReady.value ? getStrDictOptions('value_types') : []))

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()

const isInitializing = ref(false)
const isSwitchingDeviceType = ref(false)

const formData = ref({
  id: undefined as number | undefined,
  subjectCode: undefined as string | undefined,
  subjectName: undefined as string | undefined,
  deviceType: undefined as number | undefined,
  deviceId: undefined as number | undefined,
  componentId: undefined as number | undefined,
  inspectionMethod: undefined as string | undefined,
  valueType: undefined as string | undefined,
  judgmentCriteria: undefined as string | undefined,
  projectContent: undefined as string | undefined,
  isEnable: undefined as string | undefined
})

const showDeviceSelect = computed(() => formData.value.deviceType === 1 || formData.value.deviceType === 2)
const showComponentSelect = computed(() => formData.value.deviceType === 2)

const deviceLoading = ref(false)
const deviceOptions = ref<{ label: string; value: number }[]>([])

const componentLoading = ref(false)
const componentOptions = ref<{ label: string; value: number }[]>([])

const upsertOption = (options: { label: string; value: number }[], option: { label: string; value: number }) => {
  const existed = options.some((o) => o.value === option.value)
  return existed ? options : [option, ...options]
}

const handleDeviceSearch = async (keyword: string) => {
  deviceLoading.value = true
  try {
    const data = await DeviceLedgerApi.getDeviceLedgerPage({
      pageNo: 1,
      pageSize: 50,
      deviceCode: keyword || undefined,
      deviceName: keyword || undefined
    })
    const rows = (data?.list ?? []) as DeviceLedgerVO[]
    deviceOptions.value = rows
      .filter((r) => typeof r?.id === 'number')
      .map((r) => ({ label: `${r.deviceCode ?? ''} ${r.deviceName ?? ''}`.trim(), value: r.id }))
  } finally {
    deviceLoading.value = false
  }
}

const toComponentOption = (item: any) => {
  const id = typeof item?.id === 'number' ? item.id : Number(item?.id)
  if (Number.isNaN(id)) return undefined
  const code = item?.code ?? item?.componentCode ?? item?.subjectCode
  const name = item?.name ?? item?.componentName ?? item?.subjectName
  const label = `${code ?? ''} ${name ?? ''}`.trim() || String(id)
  return { label, value: id }
}

const loadComponentOptionsByDeviceId = async (deviceId: number) => {
  componentLoading.value = true
  try {
    const data = await RepairItemsApi.getComponentList(deviceId)
    const rows = (Array.isArray(data) ? data : data?.list ?? data?.data ?? []) as any[]
    componentOptions.value = rows.map(toComponentOption).filter(Boolean) as { label: string; value: number }[]
  } finally {
    componentLoading.value = false
  }
}

watch(
  () => formData.value.deviceType,
  async () => {
    if (isInitializing.value) return
    isSwitchingDeviceType.value = true
    formData.value.deviceId = undefined
    deviceOptions.value = []
    formData.value.componentId = undefined
    componentOptions.value = []
    await nextTick()
    formRef.value?.clearValidate?.(['deviceId', 'componentId'])
    isSwitchingDeviceType.value = false
  }
)

watch(
  () => formData.value.deviceId,
  async (deviceId) => {
    if (formData.value.deviceType !== 2) return
    formData.value.componentId = undefined
    componentOptions.value = []
    if (typeof deviceId !== 'number') return
    await loadComponentOptionsByDeviceId(deviceId)
  }
)

const validateDeviceId = (_: any, value: any, callback: any) => {
  if (isSwitchingDeviceType.value) {
    callback()
    return
  }
  const dt = formData.value.deviceType
  if ((dt === 1 || dt === 2) && (value === undefined || value === null || value === '')) {
    callback(new Error(t('EquipmentManagement.RepairItems.validatorDeviceRequired')))
    return
  }
  callback()
}

const validateComponentId = (_: any, value: any, callback: any) => {
  if (isSwitchingDeviceType.value) {
    callback()
    return
  }
  const dt = formData.value.deviceType
  if (dt === 2 && (value === undefined || value === null || value === '')) {
    callback(new Error(t('EquipmentManagement.RepairItems.validatorComponentRequired')))
    return
  }
  callback()
}

const formRules = reactive({
  subjectCode: [{ required: true, message: t('EquipmentManagement.RepairItems.validatorSubjectCodeRequired') }],
  subjectName: [{ required: true, message: t('EquipmentManagement.RepairItems.validatorSubjectNameRequired') }],
  deviceType: [{ required: true, message: t('EquipmentManagement.RepairItems.validatorDeviceTypeRequired') }],
  deviceId: [{ validator: validateDeviceId }],
  componentId: [{ validator: validateComponentId }],
  isEnable: [{ required: true, message: t('EquipmentManagement.RepairItems.validatorIsEnableRequired') }]
})

const open = async (type: string, row?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  isInitializing.value = true
  resetForm()
  if (!dictReady.value) {
    await dictStore.setDictMap()
    dictReady.value = true
  }
  if (type === 'update' && row) {
    formData.value = {
      id: row.id,
      subjectCode: row.subjectCode,
      subjectName: row.subjectName,
      deviceType: row.deviceType !== undefined && row.deviceType !== null ? Number(row.deviceType) : undefined,
      deviceId: row.deviceId !== undefined && row.deviceId !== null ? Number(row.deviceId) : undefined,
      componentId: row.componentId !== undefined && row.componentId !== null ? Number(row.componentId) : undefined,
      inspectionMethod: row.inspectionMethod !== undefined && row.inspectionMethod !== null ? String(row.inspectionMethod) : undefined,
      valueType: row.valueType !== undefined && row.valueType !== null ? String(row.valueType) : undefined,
      judgmentCriteria: row.judgmentCriteria,
      projectContent: row.projectContent,
      isEnable: row.isEnable !== undefined && row.isEnable !== null ? String(row.isEnable) : undefined
    }

    if (typeof formData.value.deviceId === 'number') {
      const label = row.deviceName ? String(row.deviceName) : `ID:${formData.value.deviceId}`
      deviceOptions.value = upsertOption(deviceOptions.value, { label, value: formData.value.deviceId })
    }
    if (formData.value.deviceType === 2 && typeof formData.value.deviceId === 'number') {
      await loadComponentOptionsByDeviceId(formData.value.deviceId)
      if (typeof formData.value.componentId === 'number') {
        const label = row.componentName ? String(row.componentName) : `ID:${formData.value.componentId}`
        componentOptions.value = upsertOption(componentOptions.value, { label, value: formData.value.componentId })
      }
    }
  }
  await nextTick()
  formRef.value?.clearValidate?.()
  isInitializing.value = false
}

defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = {
      id: formType.value === 'update' ? formData.value.id : undefined,
      subjectCode: formData.value.subjectCode,
      subjectName: formData.value.subjectName,
      deviceType: formData.value.deviceType,
      deviceId: formData.value.deviceId,
      componentId: formData.value.componentId,
      inspectionMethod: formData.value.inspectionMethod,
      valueType: formData.value.valueType,
      judgmentCriteria: formData.value.judgmentCriteria,
      isEnable: formData.value.isEnable,
      projectContent: formData.value.projectContent
    } as unknown as RepairItemVO

    if (formType.value === 'create') {
      await RepairItemsApi.createRepairItem(data)
      message.success(t('common.createSuccess'))
    } else {
      await RepairItemsApi.updateRepairItem(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    subjectCode: undefined,
    subjectName: undefined,
    deviceType: undefined,
    deviceId: undefined,
    componentId: undefined,
    inspectionMethod: undefined,
    valueType: undefined,
    judgmentCriteria: undefined,
    projectContent: undefined,
    isEnable: true
  }
  deviceOptions.value = []
  componentOptions.value = []
  formRef.value?.resetFields()
}
</script>
