<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    wrapClassName="custom-modal-box"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  export const formSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('表格列名称'),
      component: 'Input',
      required: true,
      colProps: {
        span: 24,
      },
    },
    {
      field: 'code',
      label: t('表格列编码'),
      component: 'Input',
      required: true,
      colProps: {
        span: 24,
      },
    },
  ];

  export default defineComponent({
    name: 'MenuButtonModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');

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

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          rowId.value = data.record.key;

          setFieldsValue({
            ...data.record,
          });
        } else {
          rowId.value = '';
        }
      });

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

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });

          closeModal();
          emit('success', { isUpdate: unref(isUpdate), record: { ...values, key: rowId.value } });
        } catch (error) {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit, t };
    },
  });
</script>
