<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="900px">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <el-form-item :label="t('MoldManagement.MoldRepairItems.dialogSubjectCode')" prop="subjectCode">
        <el-input
          v-model="formData.subjectCode"
          :placeholder="t('MoldManagement.MoldRepairItems.placeholderDialogSubjectCode')"
        />
      </el-form-item>
      <el-form-item :label="t('MoldManagement.MoldRepairItems.dialogSubjectName')" prop="subjectName">
        <el-input
          v-model="formData.subjectName"
          :placeholder="t('MoldManagement.MoldRepairItems.placeholderDialogSubjectName')"
        />
      </el-form-item>
      <el-form-item :label="t('MoldManagement.MoldRepairItems.dialogMold')" prop="moldId">
        <el-select
          v-model="formData.moldId"
          filterable
          remote
          reserve-keyword
          clearable
          :remote-method="handleDeviceSearch"
          :loading="deviceLoading"
          :placeholder="t('MoldManagement.MoldRepairItems.placeholderDialogMold')"
          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 :label="t('MoldManagement.MoldRepairItems.dialogProjectContent')" prop="projectContent">
        <el-input
          v-model="formData.projectContent"
          :placeholder="t('MoldManagement.MoldRepairItems.placeholderDialogProjectContent')"
          type="textarea"
        />
      </el-form-item>
      <el-form-item :label="t('MoldManagement.MoldRepairItems.dialogIsEnable')" 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 { MoldRepairItemsApi, MoldRepairItemVO } from '@/api/mold/moldRepairItems'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { MoldBrandApi, MoldVO } from '@/api/erp/mold'

defineOptions({ name: 'MoldRepairItemsForm' })

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

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

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

const formData = ref({
  id: undefined as number | undefined,
  subjectCode: undefined as string | undefined,
  subjectName: undefined as string | undefined,
  moldId: undefined as number | undefined,
  projectContent: undefined as string | undefined,
  isEnable: undefined as string | undefined
})

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

const handleDeviceSearch = async (keyword: string) => {
  deviceLoading.value = true
  try {
    const data = await MoldBrandApi.getMoldPage({
      code: keyword || undefined,
      name: keyword || undefined
    })
    const rows = (data?.list ?? []) as MoldVO[]
    deviceOptions.value = rows
      .filter((r) => typeof r?.id === 'number')
      .map((r) => ({ label: `${r.code ?? ''} ${r.name ?? ''}`.trim(), value: r.id }))
  } finally {
    deviceLoading.value = false
  }
}
const validateDeviceId = (_: any, value: any, callback: any) => {
  if (value === undefined || value === null || value === '') {
    callback(new Error(t('MoldManagement.MoldRepairItems.validatorMoldRequired')))
    return
  }
  callback()
}

const formRules = reactive({
  subjectCode: [{ required: true, message: t('MoldManagement.MoldRepairItems.validatorSubjectCodeRequired'), trigger: 'blur' }],
  subjectName: [{ required: true, message: t('MoldManagement.MoldRepairItems.validatorSubjectNameRequired'), trigger: 'blur' }],
  moldId: [{ required: true, validator: validateDeviceId, trigger: 'change' }],
  isEnable: [{ required: true, message: t('MoldManagement.MoldRepairItems.validatorIsEnableRequired'), trigger: 'change' }]
})

const open = async (type: string, row?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  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,
      moldId: row.moldId !== undefined && row.moldId !== null ? Number(row.moldId) : undefined,
      projectContent: row.projectContent,
      isEnable: row.isEnable !== undefined && row.isEnable !== null ? String(row.isEnable) : undefined
    }

    if (typeof formData.value.moldId === 'number') {
      const label = row.moldName ? String(row.moldName) : `ID:${formData.value.moldId}`
      deviceOptions.value = [{ label, value: formData.value.moldId }]
    }
  }
}

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,
      moldId: formData.value.moldId,
      isEnable: formData.value.isEnable,
      projectContent: formData.value.projectContent
    } as unknown as MoldRepairItemVO

    if (formType.value === 'create') {
      await MoldRepairItemsApi.createRepairItem(data)
      message.success(t('common.createSuccess'))
    } else {
      await MoldRepairItemsApi.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,
    moldId: undefined,
    projectContent: undefined,
    isEnable: true
  }
  deviceOptions.value = []
  formRef.value?.resetFields()
}
</script>
