<script setup lang="ts">
import type { FormInstance } from 'antdv-next'
import apiBaseModel from '@/api/modules/baseModel'
import apiBaseManufacturer from '@/api/modules/baseManufacturer'
import apiBaseCategory from '@/api/modules/baseCategory'

export interface Props { id?: number | string }
const props = withDefaults(defineProps<Props>(), { id: '' })

const loading = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  id: props.id as number | string,
  name: '',
  model_number: '',
  manufacturer_id: undefined as number | undefined,
  category_id: undefined as number | undefined,
})

const rules = {
  name: [{ required: true, message: '请输入型号名称', trigger: 'blur' }],
}

const manufacturerOptions = ref<{ value: number; label: string }[]>([])
const categoryOptions = ref<{ value: number; label: string }[]>([])

onMounted(() => {
  apiBaseManufacturer.list().then((res: any) => {
    manufacturerOptions.value = (res.data || []).map((item: any) => ({ value: item.id, label: item.name }))
  })
  apiBaseCategory.list().then((res: any) => {
    categoryOptions.value = (res.data || []).map((item: any) => ({ value: item.id, label: item.name }))
  })
  if (form.value.id !== '') getInfo()
})

function getInfo() {
  loading.value = true
  apiBaseModel.detail(form.value.id as number).then((res: any) => {
    loading.value = false
    const d = res.data
    Object.assign(form.value, {
      name: d.name, model_number: d.model_number,
      manufacturer_id: d.manufacturer_id, category_id: d.category_id,
    })
  }).catch(() => { loading.value = false })
}

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      formRef.value?.validate().then(() => {
        apiBaseModel.save(form.value).then(() => { faToast.success(form.value.id ? '编辑成功' : '新增成功'); resolve() })
      }).catch(() => {})
    })
  },
})
</script>

<template>
  <div v-if="loading" class="flex-center py-12">
    <ASpin />
  </div>
  <AForm v-else ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
    <AFormItem label="型号名称" name="name">
      <AInput v-model:value="form.name" placeholder="请输入型号名称" />
    </AFormItem>
    <AFormItem label="型号编号" name="model_number">
      <AInput v-model:value="form.model_number" placeholder="请输入型号编号" />
    </AFormItem>
    <AFormItem label="所属厂商" name="manufacturer_id">
      <ASelect v-model:value="form.manufacturer_id" placeholder="请选择厂商" show-search :filter-option="(input: string, option: any) => option.label?.toLowerCase().includes(input.toLowerCase())" :options="manufacturerOptions" />
    </AFormItem>
    <AFormItem label="所属分类" name="category_id">
      <ASelect v-model:value="form.category_id" placeholder="请选择分类" show-search :filter-option="(input: string, option: any) => option.label?.toLowerCase().includes(input.toLowerCase())" :options="categoryOptions" />
    </AFormItem>
  </AForm>
</template>
