<template>
  <wd-config-provider :theme-vars="themeVars">
    <slot />
    <MessageBox ref="messageBox" />
    <wd-toast :z-index="1200" loading-color="#FFA007" loading-type="ring"/>
    <AuthDialog ref="authDialog" />
  </wd-config-provider>

</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { onShow, onHide } from '@dcloudio/uni-app';
import AuthDialog from './AuthDialog.vue';
import MessageBox from './MessageBox.vue';
import { useToast } from 'wot-design-uni';
import { eventBus, EventNames } from '@/utils/eventBus';

const authDialog = ref<InstanceType<typeof AuthDialog>>();
const messageBox = ref<InstanceType<typeof MessageBox>>();
const themeVars = reactive({
  buttonPrimaryBgColor: '#FFA007',
  buttonPrimaryColor: '#000',
  colorTheme: '#FFA007',
});

// 获取真实实例
const toast = useToast();

// 事件处理函数
const handleShowToast = (data: any) => {
  const { type, options } = data;
  if (type === 'close') {
    toast.close();
  } else if ((toast as any)[type]) {
    (toast as any)[type](options);
  }
};

const handleShowMessage = (data: any) => {
  const { type, options, resolve, reject } = data;
  if (type === 'close') {
    messageBox.value?.close();
    return;
  }
  
  if (!messageBox.value) {
    setTimeout(() => {
      eventBus.emit(EventNames.SHOW_MESSAGE, data);
    }, 500);
    return;
  }
  
  if ((messageBox.value as any)[type]) {
    (messageBox.value as any)[type](options)
      .then((res: any) => {
        if (resolve) resolve(res);
      })
      .catch((err: any) => {
        if (reject) reject(err);
      });
  }
};

const handleAuth = (data: any) => {
  const { resolve, reject } = data;
  if (!authDialog.value) {
    setTimeout(() => {
      eventBus.emit(EventNames.AUTH, data);
    }, 500);
    return;
  }
  authDialog.value?.auth()
    .then((res: any) => {
      if (resolve) resolve(res);
    })
    .catch((err: any) => {
      if (reject) reject(err);
    });
};


const startListen = () => {
  console.log('start listen')
  // 页面显示时监听全局事件
  eventBus.on(EventNames.SHOW_TOAST, handleShowToast);
  eventBus.on(EventNames.SHOW_MESSAGE, handleShowMessage);
  eventBus.on(EventNames.AUTH, handleAuth);
}

const stopListen = () => {
  console.log('stop listen')
  // 页面隐藏时取消监听
  eventBus.off(EventNames.SHOW_TOAST);
  eventBus.off(EventNames.SHOW_MESSAGE);
  eventBus.off(EventNames.AUTH);
}


onShow(() => {
  startListen()
});

onHide(() => {
  stopListen()
});
</script>

<style scoped lang="scss">

</style>
