<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 {
    sysConstantConfigAdd,
    sysConstantConfigEdit,
    sysConstantConfigDetail,
  } from '/@/api/sys/sysConstantConfigApi';

  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 sysConstantConfigDetail(data.record.id);
      rowId.value = resData.id;
      await setFieldsValue({
        ...resData,
      });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      !unref(isUpdate)
        ? await sysConstantConfigAdd({ ...values })
        : await sysConstantConfigEdit({ ...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>
