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

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: '',
  building: '',
  room: '',
  address: '',
  city: '',
  state: '',
  country: '',
})

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

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

function getInfo() {
  loading.value = true
  apiBaseLocation.detail(form.value.id as number).then((res: any) => {
    loading.value = false
    const d = res.data
    Object.assign(form.value, {
      name: d.name, building: d.building, room: d.room,
      address: d.address, city: d.city, state: d.state, country: d.country,
    })
  }).catch(() => { loading.value = false })
}

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      formRef.value?.validate().then(() => {
        apiBaseLocation.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="building">
      <AInput v-model:value="form.building" placeholder="请输入建筑物" />
    </AFormItem>
    <AFormItem label="房间号" name="room">
      <AInput v-model:value="form.room" placeholder="请输入房间号" />
    </AFormItem>
    <AFormItem label="详细地址" name="address">
      <ATextarea v-model:value="form.address" placeholder="请输入详细地址" :rows="2" />
    </AFormItem>
    <AFormItem label="城市" name="city">
      <AInput v-model:value="form.city" placeholder="请输入城市" />
    </AFormItem>
    <AFormItem label="省/州" name="state">
      <AInput v-model:value="form.state" placeholder="请输入省/州" />
    </AFormItem>
    <AFormItem label="国家" name="country">
      <AInput v-model:value="form.country" placeholder="请输入国家" />
    </AFormItem>
  </AForm>
</template>
