<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm"> </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue'
  import { BasicForm, useForm } from '/@/components/Form/index'
  import { accountFormSchema } from './city.data'
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer'
  import { addaGriculturalBasic, editGriculturalBasic } from '/@/api/sys/user'
  const emits = defineEmits(['success', 'register'])
  const isUpdate = ref(false)
  const getTitle = computed(() => (!isUpdate.value ? '新增街镇' : '编辑街镇'))
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
  })
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields()
    setDrawerProps({ confirmLoading: false })
    isUpdate.value = data?.isUpdate
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data,
      })
    }
  })
  const handleSubmit = async () => {
    try {
      const values = await validate()
      values.type = 2
      if (values.id) {
        // 修改
        await editGriculturalBasic(values.id, values)
      } else {
        // 新增
        await addaGriculturalBasic(values)
      }
      closeDrawer()
      emits('success')
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
