<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="720px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('MoldManagement.MoldInspectionPlan.planName')" prop="planName" required>
        <el-input
          v-model="formData.planName"
          :placeholder="t('MoldManagement.MoldInspectionPlan.placeholderPlanName')"
        />
      </el-form-item>

      <el-form-item :label="t('MoldManagement.MoldInspectionPlan.planType')" prop="planType" required>
        <el-select
          v-model="formData.planType"
          :placeholder="t('MoldManagement.MoldInspectionPlan.placeholderPlanType')"
          class="!w-full"
        >
          <el-option :value="1" :label="t('MoldManagement.MoldInspectionPlan.planTypeMaintain')" />
          <el-option :value="2" :label="t('MoldManagement.MoldInspectionPlan.planTypeInspect')" />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('MoldManagement.MoldInspectionPlan.description')" prop="description">
        <el-input
          v-model="formData.description"
          :placeholder="t('MoldManagement.MoldInspectionPlan.placeholderDescription')"
          type="textarea"
        />
      </el-form-item>

      <el-form-item :label="t('MoldManagement.MoldInspectionPlan.subjectName')" prop="subjectIds">
        <el-select
          v-model="formData.subjectIds"
          multiple
          filterable
          clearable
          :placeholder="t('MoldManagement.MoldInspectionPlan.placeholderSubjectSelect')"
          class="!w-full"
        >
          <el-option v-for="item in subjectOptions" :key="item.id" :label="item.subjectName" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="submitForm" :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 type { FormRules } from 'element-plus'
import { DvSubjectApi, DvSubjectVO } from '@/api/mold/inspectionItems'
import { PlanMaintenanceApi, PlanMaintenanceVO } from '@/api/mold/planmaintenance'

defineOptions({ name: 'MoldInspectionPlanForm' })

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

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')

const subjectOptions = ref<DvSubjectVO[]>([])
const ensureSubjectOptionsLoaded = async () => {
  if (subjectOptions.value.length) return
  const res = await DvSubjectApi.getMoldSubjectAllList()
  const list = Array.isArray(res) ? res : res?.list
  subjectOptions.value = (list ?? []) as DvSubjectVO[]
}

const parseIds = (value: any): Array<number | string> => {
  if (!value) return []
  const raw = Array.isArray(value)
    ? value
    : String(value)
        .split(',')
        .map((v) => v.trim())
        .filter((v) => v !== '')

  return raw
    .map((v) => {
      if (typeof v === 'number') return v
      const s = String(v).trim()
      if (!s) return undefined
      const n = Number(s)
      if (Number.isFinite(n) && String(n) === s) return n
      return s
    })
    .filter((v): v is number | string => v !== undefined)
}

const initFormData = () => ({
  id: undefined as PlanMaintenanceVO['id'],
  planName: '' as string,
  planType: undefined as any,
  description: '' as string,
  subjectIds: [] as Array<number | string>
})

const formData = ref(initFormData())
const formRules = reactive<FormRules>({
  planName: [
    {
      required: true,
      message: t('MoldManagement.MoldInspectionPlan.validatorPlanNameRequired'),
      trigger: 'blur'
    }
  ],
  planType: [
    {
      required: true,
      message: t('MoldManagement.MoldInspectionPlan.validatorPlanTypeRequired'),
      trigger: 'change'
    }
  ]
})
const formRef = ref()

const open = async (type: 'create' | 'update', row?: Partial<PlanMaintenanceVO>) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await ensureSubjectOptionsLoaded()

  if (type === 'update' && row) {
    formData.value = {
      ...initFormData(),
      id: row.id,
      planName: (row.planName as any) ?? '',
      planType: (row.planType as any) ?? undefined,
      description: (row.description as any) ?? '',
      subjectIds: parseIds((row as any).subjectIds ?? (row as any).subjectIdS)
    }
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = {
      id: formData.value.id,
      planName: formData.value.planName,
      planType: formData.value.planType,
      description: formData.value.description,
      subjectIdS: formData.value.subjectIds?.length ? formData.value.subjectIds.join(',') : undefined
    }
    if (formType.value === 'create') {
      await PlanMaintenanceApi.createPlanMaintenance(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlanMaintenanceApi.updatePlanMaintenance(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = initFormData()
  formRef.value?.resetFields()
}
</script>
