<template>
  <tf-dialog
    :visible.sync="dialogVisible"
    :width="width"
    :footer="false"
    :gutter="false"
    :title="title"
    max-height="100vh"
    v-bind="$attrs"
    v-on="$listeners"
    @closed="onClosed"
  >
    <div v-loading="loading" element-loading-background="transparent">
      <el-image :src="src" :alt="alt" @click="onZoomIn" class="img" />
    </div>
  </tf-dialog>
</template>

<script lang="ts">
  import { Vue, Component, Prop, PropSync, Watch } from 'vue-property-decorator'
  import TfDialog from './index.vue'
  const DEFAULT_WIDTH = '375px'

  @Component({ name: 'TfImagePreview', components: { TfDialog } })
  export default class TfImagePreview extends Vue {
    @Prop({ type: String }) src!: string
    @Prop({ type: String }) alt!: string
    @Prop({ type: String, default: '图片查看' }) title!: string
    @PropSync('visible', { type: Boolean }) dialogVisible!: boolean
    width: string = DEFAULT_WIDTH
    loading: boolean = false
    onZoomIn() {
      window.open(this.src, this.title, 'toolbar=no,menubar=no,location=no,status=no,scrollbar=no')
    }
    onClosed() {
      this.width = DEFAULT_WIDTH
    }
    @Watch('src')
    onSrcChange(src: string) {
      this.loading = false
      if (src) {
        const image = new Image()
        this.loading = true
        image.src = src
        image.onload = () => {
          this.loading = false
          const {
            naturalWidth
            // naturalHeight
          } = image
          const {
            clientWidth
            //  clientHeight
          } = document.body
          const maxWidth = clientWidth * 0.8
          // const maxHeight = clientHeight * 0.8
          const width = naturalWidth > maxWidth ? maxWidth : naturalWidth
          // const height = naturalHeight > width ? maxHeight : naturalHeight
          this.width = `${width}px`
        }
        image.onerror = () => {
          this.width = DEFAULT_WIDTH
          this.loading = false
        }
      } else {
        this.width = DEFAULT_WIDTH
      }
    }
  }
</script>
<style lang="scss" scoped>
  .img {
    width: 100%;
    min-height: 100px;
    >>> img {
      cursor: zoom-in;
    }
    >>> .el-image__error {
      text-align: center;
      height: 100px;
    }
  }
</style>
