<template>
  <div class="screenfull-container" @click="click">
    <el-tooltip
      effect="dark"
      :content="isFullscreen ? '退出全屏' : '全屏'"
      placement="bottom"
    >
      <i
        :class="isFullscreen ? 'el-icon-close' : 'el-icon-full-screen'"
        class="screenfull-icon"
      />
    </el-tooltip>
  </div>
</template>

<script>
export default {
  name: "Screenfull",
  data() {
    return {
      isFullscreen: false
    };
  },
  mounted() {
    document.addEventListener("fullscreenchange", this.fullscreenChange);
    document.addEventListener("webkitfullscreenchange", this.fullscreenChange);
    document.addEventListener("mozfullscreenchange", this.fullscreenChange);
    document.addEventListener("MSFullscreenChange", this.fullscreenChange);
  },
  beforeDestroy() {
    document.removeEventListener("fullscreenchange", this.fullscreenChange);
    document.removeEventListener(
      "webkitfullscreenchange",
      this.fullscreenChange
    );
    document.removeEventListener("mozfullscreenchange", this.fullscreenChange);
    document.removeEventListener("MSFullscreenChange", this.fullscreenChange);
  },
  methods: {
    fullscreenChange() {
      this.isFullscreen = !!(
        document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.mozFullScreenElement ||
        document.msFullscreenElement
      );
    },
    click() {
      const element = document.documentElement;
      try {
        if (!this.isFullscreen) {
          if (element.requestFullscreen) {
            element.requestFullscreen();
          } else if (element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen();
          } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
          } else if (element.msRequestFullscreen) {
            element.msRequestFullscreen();
          }
        } else {
          if (document.exitFullscreen) {
            document.exitFullscreen();
          } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
          } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
          } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
          }
        }
        this.isFullscreen = !this.isFullscreen;
      } catch (err) {
        this.$message.error("浏览器不支持全屏");
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.screenfull-container {
  cursor: pointer;
  display: flex;
  align-items: center;
  .screenfull-icon {
    font-size: 20px;
    color: #000;
  }
}
</style>
