<template>
  <BasicDrawer
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showFooter="true"
  >
    <BasicForm @register="registerForm" layout="vertical" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dataFormSchema } from './data';

  import { sysPosAdd, sysPosEdit, sysPosDetail } from '/@/api/sys/sysPosApi';

  const emit = defineEmits(['success', 'register']);

  const getTitle = computed(() => (!unref(isUpdate) ? '新增岗位管理' : '编辑岗位管理'));
  const width = '45%';
  const isUpdate = ref(false);
  const rowId = ref();

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      const resData = await sysPosDetail(data.record.id);
      rowId.value = resData.id;
      await setFieldsValue({
        ...resData,
      });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      !unref(isUpdate)
        ? await sysPosAdd({ ...values })
        : await sysPosEdit({ ...values, id: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeDrawer();
      emit('success', {
        isUpdate: unref(isUpdate),
        values: { ...values, id: rowId.value },
      });
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
