<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';

import { useAppConfig, useTabs } from '@vben/hooks';
import { useAccessStore } from '@vben/stores';

import { useEventListener } from '@vueuse/core';

defineOptions({ name: 'FlowDesigner' });

const route = useRoute();
const definitionId = route.query.definitionId as string;
// const disabled = route.query.disabled === 'true';

const { clientId } = useAppConfig(import.meta.env, import.meta.env.PROD);

const accessStore = useAccessStore();
const params = {
  Authorization: `Bearer ${accessStore.accessToken}`,
  id: definitionId,
  clientid: clientId,
  onlyDesignShow: true,
};

// 将params转换为URL参数格式
const urlParams = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
  // 检查value是否为undefined或null，只有非空值才添加到URL参数中
  if (value !== undefined && value !== null) {
    urlParams.append(key, value.toString());
  }
});

/**
 * iframe设计器的地址   http://192.168.1.15:8086/warm-flow-ui/index.html   http://192.168.1.21:8082/
 */
// const url = `${import.meta.env.VITE_GLOB_API_URL}/warm-flow-ui/index.html?${stringify(params)}`;
// 将空格编码从"+"改为"%20"
const url = `${import.meta.env.VITE_GLOB_FLOW_URL}/index.html?${urlParams.toString().replaceAll('+', '%20')}`;

const { closeCurrentTab } = useTabs();
const router = useRouter();

function messageHandler(event: MessageEvent) {
  switch (event.data.method) {
    case 'close': {
      // 关闭当前tab
      closeCurrentTab();
      // 跳转到流程定义列表
      router.push('/system/workflow/processDefinition');
      break;
    }
  }
}

// iframe监听组件内设计器保存事件
useEventListener('message', messageHandler);
</script>

<template>
  <div class="size-full">
    <iframe :src="url" class="size-full"></iframe>
  </div>
</template>
