<template>
  <div v-if="visible">
    <component
      :is="componentName"
      v-if="visible"
      ref="SystemFormRef"
      :fromPage="FromPageType.FLOW"
      @loadingCompleted="loadingCompleted"
      @changeUploadComponentIds="changeUploadComponentIds"
    />
  </div>
  <div v-else>
    <SimpleForm
      class="form-box"
      ref="SystemFormRef"
      :formProps="formProps"
      :formModel="workflowConfig.formModel"
      :isWorkFlow="true"
      :isCamelCase="true"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed, defineAsyncComponent, reactive } from 'vue';
  import { FromPageType } from '/@/enums/workflowEnum';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { createFormEvent, loadFormEvent } from '/@/hooks/web/useFormEvent';
  import { changeFormJson } from '/@/hooks/web/useWorkFlowForm';

  const props = defineProps({
    systemComponent: {
      type: Object,
      default: () => {
        return {
          functionalModule: '',
          functionName: '',
          functionFormName: '',
        };
      },
    },
    workflowConfig: {
      //工作流表单配置
      type: Object,
      default: () => {
        return {
          formName: '',
          formProps: {},
          formModel: {},
          formKey: '',
          validate: true,
          workflowPermissions: [],
          opinions: [],
          opinionsComponents: [],
          formJson: [],
        };
      },
    },
    isViewProcess: {
      //是否查看表单
      type: Boolean,
      default: false,
    },
  });
  const SystemFormRef = ref();
  const visible = ref(false);
  const formProps = ref({});
  const flowConfig = reactive({
    draftsFormData: {},
    uploadComponentIds: [], // 所有上传文件的文件夹id    【因为流程需要统计每个节点的附件汇总】
    isOldSystem: false,
  });
  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`
        ),
      onError: async function () {
        flowConfig.isOldSystem = true;
        const {
          formJson: newJson,
          formModel,
          formKey,
          workflowPermissions,
          opinions,
          opinionsComponents,
        } = props.workflowConfig;
        const model = JSON.parse(newJson) as GeneratorConfig;
        const { formJson, formEventConfig } = model;
        if (formEventConfig) {
          let { formId, formName } = getFormInfo();
          //初始化表单
          await createFormEvent(formEventConfig, formModel, formJson.list, true, formName, formId);
          //加载表单
          await loadFormEvent(formEventConfig, formModel, formJson.list, true, formName, formId);

          //TODO 暂不放开 工作流没有获取表单数据这个步骤 获取表单数据
          // getFormDataEvent(formEventConfig, formModels,true);
        }

        let isViewProcess = props.isViewProcess;
        let { buildOptionJson, uploadComponentIds } = changeFormJson(
          {
            formJson,
            formConfigChildren: workflowPermissions,
            formConfigKey: formKey,
            opinions: opinions,
            opinionsComponents: opinionsComponents,
          },
          isViewProcess,
          flowConfig.uploadComponentIds,
        );
        flowConfig.uploadComponentIds = uploadComponentIds;
        if (buildOptionJson.schemas) {
          formProps.value = buildOptionJson;
        }
        visible.value = false;
      },
    });
  });

  onMounted(() => {
    visible.value = true;
  });

  function getFormInfo() {
    let formId = '';
    if (props.workflowConfig.formKey) {
      let tempArr = props.workflowConfig.formKey.split('_');
      if (tempArr.length > 0 && tempArr[1]) {
        formId = tempArr[1];
      }
    }
    return { formId, formName: props.workflowConfig.formName };
  }
  async function loadingCompleted() {
    let { formId, formName } = getFormInfo();
    await SystemFormRef.value.setWorkFlowForm({
      formConfigChildren: props.workflowConfig.workflowPermissions,
      formConfigKey: props.workflowConfig.formKey,
      opinions: props.workflowConfig.opinions,
      opinionsComponents: props.workflowConfig.opinionsComponents,
      isViewProcess: props.isViewProcess,
      uploadIds: flowConfig.uploadComponentIds,
      formModels: props.workflowConfig.formModel,
      formName,
      formId,
    });

    // 草稿箱处理
    if (
      '{}' == JSON.stringify(props.workflowConfig.formModel) &&
      '{}' != JSON.stringify(flowConfig.draftsFormData)
    ) {
      SystemFormRef.value.setFieldsValue(flowConfig.draftsFormData);
    }
  }
  function changeUploadComponentIds(ids) {
    flowConfig.uploadComponentIds = ids;
  }
  function validate() {
    return SystemFormRef.value.validate();
  }
  function getFieldsValue() {
    return SystemFormRef.value.getFieldsValue();
  }
  function getRowKey() {
    return SystemFormRef.value.getRowKey();
  }
  function getUploadComponentIds() {
    return flowConfig.uploadComponentIds;
  }
  function getIsOldSystem() {
    return flowConfig.isOldSystem;
  }
  async function setFieldsValue(record) {
    flowConfig.draftsFormData = record;
  }
  async function workflowSubmit() {
    let values = {};
    try {
      values = await SystemFormRef.value.validate();
      // 提交表单
      if (visible.value) {
        let id = await submit();
        let rowKey = getRowKey();
        values[rowKey] = id;
      }

      return values;
    } catch (error) {}
  }
  async function submit() {
    let saveValId = '';
    let values = await SystemFormRef.value.validate();
    let rowKey = getRowKey();
    if (props.workflowConfig.formModel[rowKey]) {
      values[rowKey] = props.workflowConfig.formModel[rowKey];
    }
    if (values[rowKey]) {
      // 编辑
      await SystemFormRef.value.update({ values, rowId: values[rowKey] });
      saveValId = values[rowKey];
    } else {
      // 新增
      saveValId = await SystemFormRef.value.add(values);
    }
    return saveValId;
  }
  async function sendMessageForAllIframe() {
    try {
      if (SystemFormRef.value && SystemFormRef.value.sendMessageForAllIframe) {
        SystemFormRef.value.sendMessageForAllIframe();
      }
    } catch (error) {}
  }
  defineExpose({
    workflowSubmit,
    getRowKey,
    validate,
    getUploadComponentIds,
    setFieldsValue,
    getFieldsValue,
    getIsOldSystem,
    sendMessageForAllIframe,
  });
</script>

<style scoped></style>
