<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';
// 这些库已在 main.ts 中全局注册，这里不需要重复导入
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: any;
    $echarts: any;
    $useEcharts: typeof useEcharts;
    $themeStore: typeof themeStore;
    $WangEditor: any;
  }
}

// axios, echarts, WangEditor 已在 main.ts 中全局注册
// 这里只需要注册组件特有的工具
(window as any).$useEcharts = useEcharts;
(window as any).$themeStore = themeStore;

// 清理函数 - 完全销毁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 && typeof editor.destroy === 'function') {
      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>
