<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="600px" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="UserDrawer">
  import { defineEmits, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './schema';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import * as UserApi from '/@/api/system/userApi';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const entityId = ref(0);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    entityId.value = data?.record?.id;

    if (unref(isUpdate)) {
      await setFieldsValue({
        ...data.record,
        distributorId: { label: data.record.distributorName, value: data.record.distributorId },
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      const {
        distributorId,
        ...rest
      } = values;
      const action = !unref(isUpdate) ? UserApi.add : UserApi.update;
      const data = !unref(isUpdate)
        ? {
            ...rest,
            distributorId: distributorId.value,
            distributorName: distributorId.label,
          }
        : Object.assign({},
          {
            ...rest,
            id: unref(entityId),
            distributorId: distributorId.value,
            distributorName: distributorId.label,
          },
        );
      await action(data);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
