<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <SimpleForm ref="formRef" :formProps="formProps" :formModel="state.formModel" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { addTable52930, getTable52930, updateTable52930 } from '/@/api/bi/aaaa';
  import { formProps } from './config';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';

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

  const { notification } = useMessage();

  const formRef = ref();

  const state = reactive({
    formModel: {},
    isUpdate: true,
    rowId: '',
  });

  const { t } = useI18n();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    state.isUpdate = !!data?.isUpdate;
    setModalProps({
      destroyOnClose: true,
      maskClosable: false,
      width: 800,
    });

    if (state.isUpdate) {
      state.rowId = data.id;
      const record = await getTable52930(data.id);
      formRef.value.setFieldsValue(record);
    } else {
      formRef.value.resetFields();
    }
  });

  const getTitle = computed(() => (!state.isUpdate ? t('新增') : t('编辑')));

  async function handleSubmit() {
    try {
      const values = await formRef.value?.validate();
      //添加隐藏组件
      if (formProps.hiddenComponent?.length) {
        formProps.hiddenComponent.forEach((component) => {
          values[component.label] = component.value;
        });
      }
      setModalProps({ confirmLoading: true });

      // TODO custom api
      if (!state.isUpdate) {
        //false 新增
        await addTable52930(values);
        notification.success({
          message: t('提示'),
          description: t('新增成功！'),
        }); //提示消息
      } else {
        values.id = state.rowId;
        await updateTable52930(values);
        notification.success({
          message: t('提示'),
          description: t('修改成功！'),
        }); //提示消息
      }

      closeModal();
      formRef.value.resetFields();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleClose() {
    formRef.value.resetFields();
  }
</script>
