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

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: '',
  url: '',
  support_url: '',
  warranty_url: '',
  support_phone: '',
  support_email: '',
})

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

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

function getInfo() {
  loading.value = true
  apiBaseManufacturer.detail(form.value.id as number).then((res: any) => {
    loading.value = false
    const d = res.data
    Object.assign(form.value, {
      name: d.name, url: d.url, support_url: d.support_url,
      warranty_url: d.warranty_url, support_phone: d.support_phone, support_email: d.support_email,
    })
  }).catch(() => { loading.value = false })
}

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      formRef.value?.validate().then(() => {
        apiBaseManufacturer.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="url">
      <AInput v-model:value="form.url" placeholder="请输入官网地址" />
    </AFormItem>
    <AFormItem label="支持URL" name="support_url">
      <AInput v-model:value="form.support_url" placeholder="请输入支持URL" />
    </AFormItem>
    <AFormItem label="保修查询URL" name="warranty_url">
      <AInput v-model:value="form.warranty_url" placeholder="请输入保修查询URL" />
    </AFormItem>
    <AFormItem label="支持电话" name="support_phone">
      <AInput v-model:value="form.support_phone" placeholder="请输入支持电话" />
    </AFormItem>
    <AFormItem label="支持邮箱" name="support_email">
      <AInput v-model:value="form.support_email" placeholder="请输入支持邮箱" />
    </AFormItem>
  </AForm>
</template>
