<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <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,
        style: {
          paddingTop: '16px',
        },
      },
    },
    {
      field: 'code',
      label: t('编码'),
      component: 'Input',
      required: true,
      colProps: {
        span: 24,
      },
    },

    {
      field: 'url',
      label: t('地址'),
      component: 'Input',
      required: true,
      colProps: {
        span: 24,
      },
    },
    {
      field: 'method',
      label: t('请求方式'),
      component: 'Select',
      defaultValue: 1,
      componentProps: {
        options: [
          { label: 'GET', value: 0 },
          { label: 'POST', value: 1 },
          { label: 'PUT', value: 2 },
          { label: 'DELETE', value: 3 },
        ],
      },
      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',
        rowProps: {
          gutter: 32,
        },
      });

      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>
