<!-- eslint-disable -->
<script lang="ts">
import { defineComponent } from 'vue';

import WujieVue from 'wujie-vue2';

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

export default defineComponent({
  name: 'WujieAdapter',
  computed: {
    finalUrl() {
      return `${this.url}?fileId=${this.fileId}&projectId=${this.projectId}&applicationId=${this.applicationId}`;
    },
    subAppProps() {
      return {
        ...this.$props,
        adapterInfo: {
          version,
        },
      };
    },
  },
  beforeUnmount() {
    const { bus } = WujieVue;
    bus.$off('message', this.handleMessage);
    bus.$off('ready', this.handleReady);
    bus.$off('render-success', this.handleRenderSuccess);
    bus.$off('render-fail', this.handleRenderFail);
  },
  methods: {
    afterMount(appWindow: any) {
      console.log(`${this.name || this.fileId} 加载完成`, appWindow);
    },
    beforeLoad(appWindow: any) {
      console.log(`${this.name || this.fileId} 开始加载`, appWindow);
    },
    handleMessage(data: any) {
      console.log(`${this.name || this.fileId} 收到子应用消息:`, data);
    },
    handleReady(data: any) {
      console.log(`${this.name || this.fileId} 子应用就绪:`, data);
    },
    handleRenderFail(error: any) {
      console.error(`${this.name || this.fileId} 子应用渲染失败:`, error);
    },
    handleRenderSuccess() {
      console.log(`${this.name || this.fileId} 子应用渲染成功`);
    },
  },
  mounted() {
    const { bus } = WujieVue;
    bus.$on('message', this.handleMessage);
    bus.$on('ready', this.handleReady);
    bus.$on('render-success', this.handleRenderSuccess);
    bus.$on('render-fail', this.handleRenderFail);
  },
  props: {
    applicationId: {
      required: true,
      type: Number,
    },
    degrade: {
      default: false,
      type: Boolean,
    },
    fileId: {
      required: true,
      type: [Number, String],
    },
    interceptors: {
      default: () => ({}),
      type: Object,
    },
    name: {
      type: String,
    },
    payload: {
      default: () => ({}),
      type: Object,
    },
    projectId: {
      required: true,
      type: Number,
    },
    route: {
      type: Object,
    },
    router: {
      type: Object,
    },
    sync: {
      default: true,
      type: Boolean,
    },
    url: {
      default: 'https://y-code-renderer.shiyue.com',
      type: String,
    },
  },
});
</script>

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