<script setup lang="ts">
import {
  computed,
  getCurrentInstance,
  onActivated,
  onBeforeUnmount,
  onDeactivated,
  onMounted,
  ref,
  shallowRef
} from 'vue';
import { NConfigProvider, darkTheme } from 'naive-ui';
import * as naive from 'naive-ui';
import axios from 'axios';
import * as echarts from 'echarts/core';
import WangEditor from 'wangeditor';
import { useThemeStore } from '@/store/modules/theme';
// 引入echarts相关
import { useEcharts } from '@/hooks/common/echarts';

defineOptions({ name: 'VueComponent' });

const props = defineProps<{
  url: string;
}>();

const asyncComponent = shallowRef<any>(null);
const loading = ref(true);
const error = ref(false);
const isActive = ref(true);
const containerId = `vueCom-${Math.random().toString(36).substr(2, 9)}`;

const themeStore = useThemeStore();
const naiveDarkTheme = computed(() => (themeStore.darkMode ? darkTheme : undefined));

// 全局注册Naive UI组件
const app = getCurrentInstance()?.appContext.app;
Object.keys(naive).forEach(key => {
  if (key.startsWith('N')) {
    app?.component(key, (naive as any)[key]);
  }
});

// 添加类型声明
declare global {
  interface Window {
    $axios: typeof axios;
    $echarts: typeof echarts;
    $useEcharts: typeof useEcharts;
    $themeStore: typeof themeStore;
    $WangEditor: typeof WangEditor;
  }
}

// 全局注入axios
(window as any).$axios = axios;
// 全局注入echarts和useEcharts
(window as any).$echarts = echarts;
(window as any).$useEcharts = useEcharts;
// 全局注入主题存储
(window as any).$themeStore = themeStore;
// 全局注入WangEditor
(window as any).$WangEditor = WangEditor;

// 清理函数 - 完全销毁Vue组件
function cleanup() {
  try {
    // 清空组件引用
    asyncComponent.value = null;

    // 清空容器
    const container = document.getElementById(containerId);
    if (container) {
      container.innerHTML = '';
    }

    // 清理编辑器实例
    const editor = (window as any).$WangEditor?.getInstance();
    if (editor) {
      editor.destroy();
    }
  } catch (e) {
    // console.error('清理Vue组件时出错:', e);
  }
}

// 暴露清理方法给父组件
defineExpose({
  cleanup
});

onMounted(async () => {
  try {
    asyncComponent.value = props.url;
    isActive.value = true;
  } catch (err) {
    // console.error('组件加载错误:', err);
    error.value = true;
  } finally {
    loading.value = false;
  }
});

onActivated(() => {
  isActive.value = true;
});

onDeactivated(() => {
  isActive.value = false;
});

onBeforeUnmount(() => {
  // 组件卸载前清理
  cleanup();
});
</script>

<template>
  <Teleport to="#extjs-root">
    <div v-show="isActive" :id="containerId" class="containers">
      <NConfigProvider :theme="naiveDarkTheme" :theme-overrides="themeStore.naiveTheme">
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="error" class="error">组件加载失败</div>
        <component :is="asyncComponent" v-else class="containers" />
      </NConfigProvider>
    </div>
  </Teleport>
</template>

<style scoped>
.containers {
  width: 100%;
  height: 100%;
}

.loading,
.error {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 16px;
}

.error {
  color: #ff4d4f;
}
</style>
