<script setup lang="ts">
import type { FormInstance } from 'antdv-next'
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: '',
  code: '',
  parent_id: undefined as number | undefined,
  category_type: undefined as string | undefined,
})

const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入分类编码', trigger: 'blur' }],
  category_type: [{ required: true, message: '请选择分类大类', trigger: 'change' }],
}

// 父级分类列表
const parentOptions = ref<{ value: number; label: string }[]>([])

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

function getInfo() {
  loading.value = true
  apiBaseCategory.detail(form.value.id as number).then((res: any) => {
    loading.value = false
    const d = res.data
    Object.assign(form.value, {
      name: d.name, code: d.code, parent_id: d.parent_id, category_type: d.category_type,
    })
  }).catch(() => { loading.value = false })
}

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      formRef.value?.validate().then(() => {
        const p = form.value.id ? apiBaseCategory.save(form.value) : apiBaseCategory.save(form.value)
        p.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="code">
      <AInput v-model:value="form.code" placeholder="请输入分类编码" />
    </AFormItem>
    <AFormItem label="分类大类" name="category_type">
      <ASelect v-model:value="form.category_type" placeholder="请选择分类大类" :options="[
        { value: 'device', label: '设备' }, { value: 'license', label: '许可' },
        { value: 'accessory', label: '配件' }, { value: 'consumable', label: '耗材' },
        { value: 'service', label: '服务' },
      ]" />
    </AFormItem>
    <AFormItem label="父级分类" name="parent_id">
      <ASelect v-model:value="form.parent_id" placeholder="请选择父级分类（可选）" allow-clear :options="parentOptions" />
    </AFormItem>
  </AForm>
</template>
