<script setup lang="ts">
import type { FormInstance } from 'antdv-next'
import apiBaseSupplier from '@/api/modules/baseSupplier'

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: '',
  contact_name: '',
  phone: '',
  remark: '',
})

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

onMounted(() => {
  if (form.value.id !== '') getInfo()
})

function getInfo() {
  loading.value = true
  apiBaseSupplier.detail(form.value.id as number).then((res: any) => {
    loading.value = false
    const d = res.data
    Object.assign(form.value, {
      name: d.name, contact_name: d.contact_name, phone: d.phone, remark: d.remark,
    })
  }).catch(() => { loading.value = false })
}

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      formRef.value?.validate().then(() => {
        apiBaseSupplier.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="contact_name">
      <AInput v-model:value="form.contact_name" placeholder="请输入联系人" />
    </AFormItem>
    <AFormItem label="联系电话" name="phone">
      <AInput v-model:value="form.phone" placeholder="请输入联系电话" />
    </AFormItem>
    <AFormItem label="备注" name="remark">
      <ATextarea v-model:value="form.remark" placeholder="请输入备注" :rows="3" />
    </AFormItem>
  </AForm>
</template>
