<template>
  <!-- 横屏提示 -->
  <view 
    v-if="showTip && isPortrait" 
    class="landscape-tip" 
  >
    <view class="tip-content">
      <!-- 关闭按钮 -->
      <view class="close-btn" @tap="handleCloseTip">
        <text class="close-icon">×</text>
      </view>
      
      <view class="tip-icon">🔄</view>
      <text class="tip-text">{{ tipText }}</text>
      <text class="tip-debug" v-if="debug">方向: {{ screenOrientation }}, 窗口: {{ windowSize }}</text>
      
      <!-- 操作按钮区域 -->
    <!--  <view class="action-buttons">
        <button class="action-btn secondary" @tap="handleCloseTip">
          <text>暂不横屏</text>
        </button>
        <button class="action-btn primary" @tap="handleRotate">
          <text>立即横屏</text>
        </button>
      </view> -->
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';

// ========================== Props & Emits ==========================
interface Props {
  autoShow?: boolean;
  showDelay?: number;
  tipText?: string;
  autoHide?: boolean;
  autoHideDelay?: number;
  checkWideContent?: boolean;
  wideContentThreshold?: number;
  debug?: boolean;
  showRotateButton?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  autoShow: true,
  showDelay: 2000,
  tipText: '建议横屏观看以获得更好体验',
  autoHide: true,
  autoHideDelay: 5000,
  checkWideContent: true,
  wideContentThreshold: 1.5,
  debug: false,
  showRotateButton: true
});

const emit = defineEmits<{
  close: [];
  show: [];
  rotate: [];
  orientationChange: [orientation: 'portrait' | 'landscape'];
}>();

// ========================== 响应式数据 ==========================
const showTip = ref(false);
const isPortrait = ref(true);
const hasShownTip = ref(false);
const autoHideTimer = ref<number | null>(null);
const windowSize = ref('');

// ========================== 计算属性 ==========================
const screenOrientation = computed(() => {
  return isPortrait.value ? '竖屏' : '横屏';
});

// ========================== 生命周期 ==========================
onMounted(() => {
  if (props.debug) console.log('AutoLandscapeTip: 组件已挂载');
  initOrientationDetection();
  
  if (props.autoShow) {
    if (props.debug) console.log('AutoLandscapeTip: 开始延迟显示检测');
    setTimeout(() => {
      checkAndShowTip();
    }, props.showDelay);
  }
});

onUnmounted(() => {
  removeOrientationListener();
  clearAutoHideTimer();
});

// ========================== 方向检测方法 ==========================
/**
 * 初始化方向检测
 */
const initOrientationDetection = () => {
  checkScreenOrientation();
  
  if (typeof uni !== 'undefined' && uni.onWindowResize) {
    uni.onWindowResize(handleResize);
  } else if (typeof window !== 'undefined') {
    window.addEventListener('resize', handleResize);
  }
  
  if (typeof window !== 'undefined' && window.screen && window.screen.orientation) {
    window.screen.orientation.addEventListener('change', handleOrientationChange);
  }
};

/**
 * 移除方向监听
 */
const removeOrientationListener = () => {
  if (typeof uni !== 'undefined' && uni.offWindowResize) {
    uni.offWindowResize(handleResize);
  } else if (typeof window !== 'undefined') {
    window.removeEventListener('resize', handleResize);
  }
  
  if (typeof window !== 'undefined' && window.screen && window.screen.orientation) {
    window.screen.orientation.removeEventListener('change', handleOrientationChange);
  }
};

/**
 * 处理系统方向变化
 */
const handleOrientationChange = () => {
  if (props.debug) console.log('AutoLandscapeTip: 系统方向变化');
  checkScreenOrientation();
};

/**
 * 处理窗口大小变化
 */
const handleResize = (res?: any) => {
  const width = res?.size?.windowWidth || window.innerWidth;
  const height = res?.size?.windowHeight || window.innerHeight;
  
  windowSize.value = `${width} × ${height}`;
  
  if (props.debug) console.log('AutoLandscapeTip: 窗口尺寸', width, height);
  
  checkScreenOrientation();
};

/**
 * 检测屏幕方向
 */
const checkScreenOrientation = () => {
  let width = window.innerWidth;
  let height = window.innerHeight;
  
  if (typeof uni !== 'undefined' && uni.getSystemInfoSync) {
    try {
      const systemInfo = uni.getSystemInfoSync();
      width = systemInfo.windowWidth || systemInfo.screenWidth || width;
      height = systemInfo.windowHeight || systemInfo.screenHeight || height;
    } catch (e) {
      if (props.debug) console.log('AutoLandscapeTip: 获取系统信息失败', e);
    }
  }
  
  const newIsPortrait = height > width;
  
  if (props.debug) console.log('AutoLandscapeTip: 方向检测', { 
    width, height, 
    current: isPortrait.value, 
    new: newIsPortrait 
  });
  
  if (isPortrait.value !== newIsPortrait) {
    isPortrait.value = newIsPortrait;
    emit('orientationChange', isPortrait.value ? 'portrait' : 'landscape');
    
    if (props.debug) console.log('AutoLandscapeTip: 方向变化', screenOrientation.value);
    
    if (!newIsPortrait && showTip.value) {
      if (props.debug) console.log('AutoLandscapeTip: 横屏，自动隐藏提示');
      handleCloseTip();
    }
    
    if (newIsPortrait && !hasShownTip.value) {
      if (props.debug) console.log('AutoLandscapeTip: 竖屏，检查是否显示提示');
      setTimeout(() => {
        checkAndShowTip();
      }, 500);
    }
  }
};

/**
 * 检查并显示提示
 */
const checkAndShowTip = async () => {
  if (hasShownTip.value || !isPortrait.value) {
    if (props.debug) console.log('AutoLandscapeTip: 条件不满足，跳过显示');
    return;
  }
  
  if (props.debug) console.log('AutoLandscapeTip: 开始检查显示条件');
  
  let shouldShow = true;
  
  if (props.checkWideContent) {
    shouldShow = await checkWideContent();
    if (props.debug) console.log('AutoLandscapeTip: 宽内容检测结果', shouldShow);
  }
  
  if (shouldShow) {
    showLandscapeTip();
  }
};

/**
 * 检测宽内容
 */
const checkWideContent = (): Promise<boolean> => {
  return new Promise((resolve) => {
    const scrollWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
    const windowWidth = window.innerWidth;
    
    if (scrollWidth > 0 && windowWidth > 0) {
      const isWide = scrollWidth > windowWidth * props.wideContentThreshold;
      if (props.debug) console.log('AutoLandscapeTip: 文档宽度检测', { scrollWidth, windowWidth, isWide });
      resolve(isWide);
      return;
    }
    
    if (typeof uni !== 'undefined' && uni.createSelectorQuery) {
      const query = uni.createSelectorQuery();
      query.selectViewport().scrollOffset().exec((res: any) => {
        if (res && res[0]) {
          const scrollWidth = res[0].scrollWidth || 0;
          const windowWidth = window.innerWidth;
          const isWide = scrollWidth > windowWidth * props.wideContentThreshold;
          resolve(isWide);
        } else {
          resolve(true);
        }
      });
    } else {
      resolve(true);
    }
  });
};

/**
 * 显示横屏提示
 */
const showLandscapeTip = () => {
  if (hasShownTip.value || !isPortrait.value) {
    return;
  }
  
  if (props.debug) console.log('AutoLandscapeTip: 显示横屏提示');
  
  showTip.value = true;
  hasShownTip.value = true;
  emit('show');
  
  if (props.autoHide) {
    clearAutoHideTimer();
    autoHideTimer.value = setTimeout(() => {
      if (props.debug) console.log('AutoLandscapeTip: 自动隐藏提示');
      handleCloseTip();
    }, props.autoHideDelay) as unknown as number;
  }
};

/**
 * 处理关闭提示
 */
const handleCloseTip = () => {
  showTip.value = false;
  clearAutoHideTimer();
  emit('close');
};

/**
 * 处理横屏旋转
 */
const handleRotate = () => {
  if (props.debug) console.log('AutoLandscapeTip: 用户选择横屏');
  emit('rotate');
  
  // 尝试锁定横屏
  if (typeof window !== 'undefined' && window.screen && window.screen.orientation && window.screen.orientation.lock) {
    window.screen.orientation.lock('landscape').catch((error) => {
      console.log('AutoLandscapeTip: 横屏锁定失败', error);
      uni.showToast({
        title: '请手动旋转设备',
        icon: 'none',
        duration: 2000
      });
    });
  } else {
    uni.showToast({
      title: '请手动旋转设备',
      icon: 'none',
      duration: 2000
    });
  }
  
  handleCloseTip();
};

/**
 * 清除自动隐藏计时器
 */
const clearAutoHideTimer = () => {
  if (autoHideTimer.value) {
    clearTimeout(autoHideTimer.value);
    autoHideTimer.value = null;
  }
};

/**
 * 手动显示提示（供父组件调用）
 */
const show = () => {
  showLandscapeTip();
};

/**
 * 手动隐藏提示（供父组件调用）
 */
const hide = () => {
  handleCloseTip();
};

/**
 * 重置提示状态（可以再次自动显示）
 */
const reset = () => {
  hasShownTip.value = false;
  handleCloseTip();
};

// 暴露方法给父组件
defineExpose({
  show,
  hide,
  reset,
  getOrientation: () => isPortrait.value ? 'portrait' : 'landscape',
  isShowing: () => showTip.value
});
</script>

<style scoped lang="scss">
.landscape-tip {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  animation: fadeIn 0.3s ease;
}

.tip-content {
  position: relative;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 60rpx 40rpx 40rpx;
  margin: 40rpx;
  max-width: 500rpx;
  text-align: center;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
  animation: slideUp 0.3s ease;
  
  /* 关闭按钮 */
  .close-btn {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    background: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .close-icon {
      font-size: 36rpx;
      color: #666;
      font-weight: bold;
      line-height: 1;
    }
    
    &:active {
      background: #e0e0e0;
    }
  }
  
  .tip-icon {
    font-size: 80rpx;
    display: block;
    margin-bottom: 30rpx;
  }
  
  .tip-text {
    display: block;
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 20rpx;
    line-height: 1.5;
  }
  
  .tip-debug {
    display: block;
    font-size: 22rpx;
    color: #999;
    margin-bottom: 30rpx;
  }
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  gap: 20rpx;
  justify-content: center;
  
  .action-btn {
    flex: 1;
    padding: 20rpx 30rpx;
    border-radius: 10rpx;
    font-size: 28rpx;
    border: none;
    min-width: 0;
    
    &.secondary {
      background: #f0f0f0;
      color: #666;
    }
    
    &.primary {
      background: #20269B;
      color: white;
    }
    
    &:active {
      opacity: 0.8;
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(50rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .tip-content {
    margin: 20rpx;
    padding: 50rpx 30rpx 30rpx;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 15rpx;
  }
}
</style>