<template>
  <div>
    <component
      :is="componentName"
      ref="SystemFormRef"
      :fromPage="FromPageType.DESKTOP"
      @loadingCompleted="loadingCompleted"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, defineAsyncComponent, reactive } from 'vue';
  import { FromPageType } from '/@/enums/workflowEnum';
  import { notification } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const props = defineProps({
    systemComponent: {
      type: Object,
      default: () => {
        return {
          functionalModule: '',
          functionName: '',
          functionFormName: '',
        };
      },
    },
    formModel: {
      type: Object,
    },
  });
  const SystemFormRef = ref();
  const dataConfig = reactive({
    PkKey: '',
    PKValue: '',
    formModel: {},
  });
  const componentName = computed(() => {
    if (!props.systemComponent.functionName) {
      return defineAsyncComponent({
        loader: () => import('./Empty.vue'),
      });
    }
    return defineAsyncComponent({
      loader: () =>
        import(
          `./../../../views/${props.systemComponent.functionalModule}/${props.systemComponent.functionName}/components/Form.vue`
        ),
    });
  });
  function loadingCompleted() {
    dataConfig.PkKey = SystemFormRef.value.getRowKey();
    if (props.formModel) dataConfig.PKValue = props.formModel[dataConfig.PkKey];
    if (dataConfig.PKValue) {
      SystemFormRef.value.setFormDataFromId(dataConfig.PKValue);
    }
  }
  async function submit() {
    let saveValId = '';
    let values = await SystemFormRef.value.validate();
    let rowKey = SystemFormRef.value.getRowKey();
    if (dataConfig.PKValue) {
      let rowId = dataConfig.PKValue;
      // 编辑
      await SystemFormRef.value.update({ values, rowId });
      saveValId = values[rowKey];
      notification.success({
        message: t('提示'),
        description: t('编辑成功！'),
      }); //提示消息
    } else {
      // 新增
      saveValId = await SystemFormRef.value.add(values);
      notification.success({
        message: t('提示'),
        description: t('新增成功！'),
      }); //提示消息
    }
    return saveValId;
  }
  function resetFields() {
    SystemFormRef.value.resetFields();
  }
  defineExpose({
    submit,
    resetFields,
  });
</script>

<style scoped></style>
