<template>
  <div ref="fullscreenContainer">
    <slot :toggle="toggleFullscreen" :isFullscreen="isFullscreen"></slot> <!-- 这里放你的图表或其他内容 -->
  </div>
</template>

<script>
export default {
  name: 'FullscreenToggle',
  data () {
    return {
      isFullscreen: false
    }
  },
  mounted () {
    this.initFullscreenListeners()
  },
  beforeDestroy () {
    this.removeFullscreenListeners()
  },
  methods: {
    // 检查是否全屏
    checkFullscreen () {
      return (
        document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.msFullscreenElement
      )
    },

    // 进入全屏
    enterFullscreen () {
      const container = this.$refs.fullscreenContainer
      if (!container) return

      if (container.requestFullscreen) {
        container.requestFullscreen().catch((err) => console.error(err))
      } else if (container.webkitRequestFullscreen) {
        container.webkitRequestFullscreen()
      } else if (container.msRequestFullscreen) {
        container.msRequestFullscreen()
      }
    },

    // 退出全屏
    exitFullscreen () {
      if (document.exitFullscreen) {
        document.exitFullscreen().catch((err) => console.error(err))
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
      }
    },

    // 切换全屏
    toggleFullscreen () {
      if (this.checkFullscreen()) {
        this.exitFullscreen()
      } else {
        this.enterFullscreen()
      }
    },

    // 监听全屏变化
    handleFullscreenChange () {
      this.isFullscreen = this.checkFullscreen()
    },

    // 监听 ESC 键
    handleKeyDown (e) {
      if (e.key === 'Escape' && this.isFullscreen) {
        this.exitFullscreen()
      }
    },

    // 初始化监听
    initFullscreenListeners () {
      document.addEventListener('fullscreenchange', this.handleFullscreenChange)
      document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange)
      document.addEventListener('msfullscreenchange', this.handleFullscreenChange)
      document.addEventListener('keydown', this.handleKeyDown)
    },

    // 移除监听
    removeFullscreenListeners () {
      document.removeEventListener('fullscreenchange', this.handleFullscreenChange)
      document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange)
      document.removeEventListener('msfullscreenchange', this.handleFullscreenChange)
      document.removeEventListener('keydown', this.handleKeyDown)
    }
  }
}
</script>

<style scoped>

</style>
