<template>
  <div id="workflowChart" v-loading="state.loading"/>
</template>
<script lang="ts" setup>
  import { reactive, onDeactivated } from 'vue';
  import { loadMicroApp, MicroApp } from 'qiankun';
  import { getSubDefineProps } from '/@/qiankun/state';
  import { GlStateEnum, WORKFLOW_DESIGN_APP_COMPONENTS } from '/@/enums/microAppEnum';
  import { useMicroAppStore } from '/@/store/modules/microApp';
  import { apps } from '/@/qiankun/apps';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getFlowChart as getProcessDefFlowChart } from '/@/api/platform/workflow/controller/process';
  import { getFlowChart as getProcessInsFlowChart } from '/@/api/platform/workflow/controller/task';

  interface WindowState {
    workflowDesignApp: MicroApp;
    loading: boolean;
    bpmnData: Recordable;
  }

  const state = reactive<WindowState>({
    workflowDesignApp: undefined!,
    loading: false,
    bpmnData: {}
  });
  const workflowDesignProps = {
    style: { 'min-height': '100vh' },
  };
  const microAppStore = useMicroAppStore();
  const { createMessage } = useMessage();

  async function init(processInsId: string, processDefId: string) {
    if (processInsId || processDefId) {
      state.loading = true;
      // 处理流程图xml数据
      try {
        if (processInsId) {
          state.bpmnData = await getProcessInsFlowChart(processInsId);
        } else {
          const bpmnXml = await getProcessDefFlowChart(processDefId);
          state.bpmnData = { bpmnXml };
        }
        state.workflowDesignApp?.unmount();
        state.workflowDesignApp = loadMicroApp(Object.assign({} , apps.find(item => item.name == 'workflow-design'), {
          container: '#workflowChart',
          props: {
            ...getSubDefineProps(),
            mountApp: WORKFLOW_DESIGN_APP_COMPONENTS.CHART,
            [GlStateEnum.WORKFLOW_DESIGN_APP_PROPS_KEY]: workflowDesignProps
          }
        }), { sandbox: { experimentalStyleIsolation: true }});
        state.workflowDesignApp.mountPromise.then(() => {
          const workflowChartApp: Recordable = microAppStore.getWorkflowDesignApp(WORKFLOW_DESIGN_APP_COMPONENTS.CHART),
                workflowRef: Recordable = workflowChartApp.getRef().$refs['workflow-chart'];
          workflowRef.setHighlightImportDiagram(state.bpmnData);
          state.loading = false;
        });
      } catch(e: any) {
        createMessage.error(e);
        state.loading = false;
      }
    } else createMessage.error('无法打开流程图,没有关联流程图ID!');
  }

  onDeactivated(() => {
    state.workflowDesignApp?.unmount();
  });

  defineExpose({
    init
  });

</script>
