<template>
  <el-dialog
    :visible.sync="visible"
    fullscreen
    :show-close="false"
    @close="handleClose"
  >
    <div style="position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%);">
      <el-image
        :src="imageUrl"
        :style="imageStyle"
        fit="contain"
      />
      <i
        class="el-icon-close"
        style="position: absolute; right: 20px; top: 20px; font-size: 24px; color: red; cursor: pointer;"
        @click="visible = false"
      />
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'ViewImage',
  data() {
    return {
      visible: false,
      imageUrl: '',
      imageStyle: {
        width: '800px',
        height: '800px'
      }
    }
  },
  methods: {
    open(url) {
      this.imageUrl = url
      this.visible = true
      this.adjustImageSize(url)
    },
    handleClose() {
      this.imageUrl = ''
    },
    adjustImageSize(url) {
      const img = new Image()
      img.src = url
      img.onload = () => {
        const ratio = img.width / img.height
        if (ratio > 1) {
          this.imageStyle.height = `${800 / ratio}px`
          this.imageStyle.width = '800px'
        } else {
          this.imageStyle.width = `${800 * ratio}px`
          this.imageStyle.height = '800px'
        }
      }
    }
  }
}
</script>