<script setup lang="ts">
import type { Router, RouteRecordRaw } from 'vue-router';

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

import WujieVue from 'wujie-vue3';

import { version } from '/package.json';

const props = withDefaults(
  defineProps<{
    [key: string]: any;
    accessToken?: string;
    applicationId: number;
    degrade?: boolean;
    fileId: number | string;
    getRouter: () => Router;
    name: string;
    // 传递给子应用的参数 payload
    payload?: Record<string, any>;
    projectId: number;
    route: RouteRecordRaw;
    router: Router;
    sync: boolean;
    url: string;
  }>(),
  {
    // 默认 wujie 降级
    degrade: true,
  },
);

const { bus } = WujieVue;

const isDegrade = computed(() => props.degrade ?? true);
// 生命周期钩子
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 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>
  <div style="width: 100%; height: 100%">
    <WujieVue
      :name="name"
      :url="url"
      :sync="sync"
      width="100%"
      height="100%"
      :degrade="isDegrade"
      :props="subAppProps"
      :before-load="beforeLoad"
      :after-mount="afterMount"
    />
  </div>
</template>
