<template>
  <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      @ok="handleSubmit"
      width="720px">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, unref } from 'vue';
import {BasicModal, ModalProps, useModalInner} from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './config.data';
import { set } from '/@/api/system/config';

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

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

    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      await resetFields();
      const props: Partial<ModalProps> = { confirmLoading: false };

      isUpdate.value = !!data?.isUpdate;

      if (unref(isUpdate)) {
        await setFieldsValue({
          ...data.record,
        });
        props.title = "编辑参数";
      }else {
        props.title = "新增参数";
      }

      setModalProps(props);
    });

    async function handleSubmit() {
      try {
        const values = await validate();
        setModalProps({ confirmLoading: true });
        await set(values);
        closeModal();
        emit('success');
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

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