<template>
  <el-dialog
    title="文件预览"
    :visible.sync="dialogVisible"
    append-to-body
    width="80%"
    destroy-on-close
  >
    <RuoYiIframe
      v-if="fileType === 'pdf'"
      :src="src"
      style="max-height: 70vh"
    />

    <el-image
      v-else-if="imgTypes.includes(fileType)"
      style="width:100%"
      :src="src"
      lazy
    />

    <div v-else class="text-center">暂不支持该类型文件预览</div>
  </el-dialog>
</template>

<script>
import RuoYiIframe from '../RuoYiIframe/index.vue'

export default {
  components: {
    RuoYiIframe
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    src: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imgTypes: ['png', 'jpg'],
      base64Reg: /^\s*data:(?:[a-z]+\/[a-z0-9-+.]+(?:;[a-z-]+=[a-z0-9-]+)?)?(?:;base64)?,([a-z0-9!$&',()*+;=\-._~:@/?%\s]*?)\s*$/i
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(v) {
        this.$emit('input', v)
      }
    },
    fileType() {
      return !this.isBase64(this.src)
        ? this.getExtensionFromUrl(this.src)
        : this.getExtensionFromBase64(this.src)
    }
  },
  methods: {
    // 检测是不是base64
    isBase64(url = '') {
      return this.base64Reg.test(url)
    },
    // 取到base64中的文件格式
    getExtensionFromBase64(base64) {
      const re = new RegExp('data:.*/(?<ext>.*?);base64,.*')
      const res = re.exec(base64)
      if (res) {
        return res.groups.ext
      }
    },
    // 获取src文件格式
    getExtensionFromUrl(url) {
      // 截取?前面的字符
      const lastIndex = url.lastIndexOf('?')
      const endIndex = lastIndex === -1 ? url.length : lastIndex
      const orginUrl = url.slice(0, endIndex)
      const index = orginUrl ? orginUrl.lastIndexOf('.') + 1 : ''
      return orginUrl.slice(index)
    }
  }
}
</script>

  <style>
  </style>

