<script setup lang="ts">
import type { AxiosInterceptorManager } from 'axios';

import type { Router, RouteRecordRaw } from 'vue-router';

import { computed, onBeforeUnmount, onMounted } from 'vue';

import WujieVue from 'wujie-vue3';

// @ts-ignore ignore the type error
import { version } from '/package.json';

const props = withDefaults(
  defineProps<{
    [key: string]: any;
    applicationId: number;
    degrade?: boolean;
    fileId: number | string;
    interceptors?: {
      request?: AxiosInterceptorManager<any>;
      response?: AxiosInterceptorManager<any>;
    };
    name?: string;
    // 传递给子应用的参数 payload
    payload?: Record<string, any>;
    projectId: number;
    route?: RouteRecordRaw;
    router?: Router;
    sync?: boolean;
    url?: string;
  }>(),
  {
    degrade: false,
    // 默认不使用拦截器
    interceptors: () => ({}),
    // 默认不使用 name
    name: undefined,
    // 默认不使用 payload
    payload: () => ({}),
    // 默认不使用 route
    route: undefined,
    // 默认不使用 router
    router: undefined,
    sync: true,
    url: 'https://y-code-renderer.shiyue.com',
  },
);

const { bus } = WujieVue;

// // 定义无界插件
// const wujiePlugins = [
//   {
//     patchElementHook(element: Element, iframeWindow: Window) {
//       if (element.nodeName === 'STYLE') {
//         element.insertAdjacentElement = function (_position, ele) {
//           iframeWindow.document.head.append(ele);
//         };
//       }
//     },
//   },
//   // InstanceofPlugin(),
// ];

// 生命周期钩子
const beforeLoad = (appWindow: Window) => {
  console.log(`${props.name} 开始加载`, appWindow);
};

const afterMount = (appWindow: Window) => {
  console.log(`${props.name} 加载完成`, appWindow);
};

// 事件处理
const handleMessage = (data: any) => {
  console.log(`${props.name} 收到子应用消息:`, data);
};

// 准备传递给子应用的数据
const subAppProps = {
  ...props,
  adapterInfo: {
    version,
  },
};

const finalUrl = computed(() => {
  return `${props.url}?fileId=${props.fileId}&projectId=${props.projectId}&applicationId=${props.applicationId}`;
});

// 监听子应用的事件
const handleReady = (data: any) => {
  console.log(`${props.name} 子应用就绪:`, data);
  // 可以在这里执行一些操作
};

const handleRenderSuccess = () => {
  console.log(`${props.name} 子应用渲染成功`);
  // 通知父应用
};

const handleRenderFail = (error: any) => {
  console.error(`${props.name} 子应用渲染失败:`, error);
  // 处理错误情况
};

onMounted(() => {
  // 注册事件监听
  bus.$on('message', handleMessage);
  bus.$on('ready', handleReady);
  bus.$on('render-success', handleRenderSuccess);
  bus.$on('render-fail', handleRenderFail);
});

onBeforeUnmount(() => {
  // 移除所有事件监听
  bus.$off('message', handleMessage);
  bus.$off('ready', handleReady);
  bus.$off('render-success', handleRenderSuccess);
  bus.$off('render-fail', handleRenderFail);
});
</script>

<template>
  <WujieVue
    :name="name || fileId"
    :url="finalUrl"
    :sync="sync"
    :degrade="degrade"
    :props="subAppProps"
    :before-load="beforeLoad"
    :after-mount="afterMount"
    :interceptors="interceptors"
  />
</template>
