<template>
  <div id="view-image" v-show="visible">
    <div class="image-container">
      <img :src="imageUrl" :width="imageWidth" :height="imageHeight" @error="handleImageError" />
      <span class="el-icon-close close-icon" @click="close" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'ViewImage',
  data() {
    return {
      visible: false,
      imageUrl: '',
      imageWidth: 800,
      imageHeight: 800
    }
  },
  methods: {
    open(url) {
      this.imageUrl = url
      this.visible = true
      this.enterFullscreen()
      const img = new Image()
      img.src = url
      img.onload = () => {
        const imgScale = img.width / img.height
        this.imageWidth = 800
        this.imageHeight = 800 / imgScale
      }
    },
    close() {
      this.exitFullscreen()
      this.visible = false
    },
    enterFullscreen() {
      const element = document.getElementById('view-image')
      if (element.requestFullscreen) {
        element.requestFullscreen()
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen()
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen()
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen()
      }
    },
    exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
      }
    },
    handleImageError(e) {
      e.target.src = '/img/noPhoto.jpg'
    }
  }
}
</script>

<style scoped>
#view-image {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-container {
  position: relative;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.close-icon {
  position: absolute;
  right: 20px;
  top: 20px;
  font-size: 20px;
  color: red;
  cursor: pointer;
}
</style>