<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="720px">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="方案名称" prop="planName" required>
        <el-input v-model="formData.planName" placeholder="请输入方案名称" />
      </el-form-item>

      <el-form-item label="方案类型" prop="planType" required>
        <el-select v-model="formData.planType" placeholder="请选择方案类型" class="!w-full">
          <el-option :value="1" label="保养" />
          <el-option :value="2" label="维护" />
        </el-select>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" placeholder="请输入描述" type="textarea" />
      </el-form-item>

      <el-form-item label="关联项目" prop="subjectIds">
        <el-select
          v-model="formData.subjectIds"
          multiple
          filterable
          clearable
          placeholder="请选择关联项目"
          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">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</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.getDvSubjectPage({})
  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: '方案名称不能为空', trigger: 'blur' }],
  planType: [{ required: true, message: '方案类型不能为空', 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>

