<template>
  <view class="ie-page theme-ie"
    :class="[{ 'is-fixed': fixHeight }]"
    :style="{ backgroundColor: bgColor }">
    <view class="ie-page-content">
      <slot></slot>
      <view v-if="safeAreaInsetBottom" class="safe-area-inset-bottom" :style="{ backgroundColor: safeAreaColor }"></view>
    </view>
    <view class="ie-page-popup">
      <vip-popup ref="vipPopupRef" />
    </view>
    <view v-if="$slots.tabbar" class="ie-page-tabbar">
      <slot name="tabbar"></slot>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { CLOSE_VIP_POPUP, OPEN_VIP_POPUP } from '@/types/injectionSymbols';
import VipPopup from './components/vip-popup.vue';
import { EnumEvent } from '@/common/enum';
defineOptions({
  name: 'ie-page',
  options: {
    virtualHost: true
  }
});
type PageProps = {
  safeAreaInsetBottom?: boolean;
  bgColor?: string;
  fixHeight?: boolean;
  safeAreaInsetBottomColor?: string;
}
const props = withDefaults(defineProps<PageProps>(), {
  safeAreaInsetBottom: true,
  bgColor: '',
  fixHeight: false,
  safeAreaInsetBottomColor: ''
});

const safeAreaColor = computed(() => {
  return props.safeAreaInsetBottom ? props.safeAreaInsetBottomColor : (props.bgColor ? props.bgColor
    : '#FFFFFF');
});
// 为 ref 添加类型定义
const vipPopupRef = ref<InstanceType<typeof VipPopup>>();

// 添加安全检查
const showVipPopup = () => {
  console.log('showVipPopup called, vipPopupRef.value:', vipPopupRef.value);
  if (vipPopupRef.value) {
    vipPopupRef.value.open();
  } else {
    console.error('vipPopupRef is not initialized');
  }
}

const closeVipPopup = () => {
  console.log('closeVipPopup called');
  if (vipPopupRef.value) {
    vipPopupRef.value.close();
  } else {
    console.error('vipPopupRef is not initialized');
  }
}

// provide 给 ie-page 内部的子组件（slot 内容）使用
// console.log('ie-page setup: providing OPEN_VIP_POPUP and CLOSE_VIP_POPUP');
provide(OPEN_VIP_POPUP, showVipPopup);
provide(CLOSE_VIP_POPUP, closeVipPopup);
// console.log('ie-page setup: provided successfully');

// 暴露方法给父组件通过 ref 调用
defineExpose({
  showVipPopup,
  closeVipPopup
});
const addListener = () => {
  uni.$on(EnumEvent.OPEN_VIP_POPUP, showVipPopup);
}
const removeListener = () => {
  uni.$off(EnumEvent.OPEN_VIP_POPUP);
}
onMounted(() => {
  addListener();
});
onBeforeUnmount(() => {
  removeListener();
});

onHide(() => {
  removeListener();
});
onUnload(() => {
  removeListener();
});
</script>

<style lang="scss" scoped>
.ie-page {
  min-height: 100vh;
  box-sizing: border-box;
}

.ie-page-content {
  @apply min-h-full relative flex flex-col z-99;
}

.ie-page-tabbar {
  @apply relative z-100 h-[50px];
}

.is-fixed {
  height: 100vh;
  .ie-page-content {
    height: 100%;
  }
}

.ie-fixed-bottom {
  box-shadow: 0 -2px 8px 0 rgba(0, 0, 0, 0.05);
}
</style>