<template>
  <div>
    <van-image-preview v-if="fileType==='image'" v-model="showPopup" :images="images" @close="onCancel" />
    <van-popup
      v-else
      v-model="showPopup"
      class="ibps-fullscreen-popup"
    >
      <van-nav-bar
        :title="title"
        left-arrow
        @click-left="onCancel"
      >
        <template #left>
          <van-icon name="cross" class="ibps-nav-bar__close-icon" />
        </template>
      </van-nav-bar>
      <pdf-viewer
        v-if="fileType==='pdf'"
        ref="viewer"
      />
      <audio-player
        v-else-if="fileType==='audio'"
        ref="viewer"
        :title="title"
        :url="url"
      />

      <video-player
        v-else-if="fileType==='video'"
        ref="viewer"
        :ext="fileExt"
        :url="url"
      />

      <div v-else class="ibps-fixed-navbar">
        不支持预览的类型
      </div>
    </van-popup>
  </div>
</template>
<script>

/**
 * 文件预览
 * 1、'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'  类型支持
 * 2、图片支持缩放
 * 3、音频，语音支持
 * 下一版本支持
 * 1、pdf支持缩放
 * 2、音频，语音多格式支持
 *
 */
import PdfViewer from './pdf'
import AudioPlayer from './audio'
import VideoPlayer from './video'
import { previewFile } from '@/api/platform/file/attachment'
const OFFICE_TYPE = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']
const PDF_TYPE = ['pdf']
const IMAGE_TYPE = ['jpg', 'jpeg', 'bmp', 'png', 'gif']
const AUDIO_TYPE = ['mp3']
const VIDEO_TYPE = ['mp4']
import { ImagePreview } from 'vant'
export default {
  components: {
    PdfViewer,
    AudioPlayer,
    VideoPlayer,
    [ImagePreview.Component.name]: ImagePreview.Component
  },
  props: {
    value: Boolean,
    file: {
      type: Object
    }
  },
  data() {
    return {
      showPopup: false,
      title: '',
      fileId: '',
      fileExt: '',
      fileType: '',
      url: '',
      images: []
    }
  },
  watch: {
    value() {
      if (this.value) {
        this.title = this.file.fileName
        this.fileId = this.file.id
        this.fileExt = this.file.ext
        this.loadViewer()
      }
      this.showPopup = this.value
    }
  },
  methods: {
    loadViewer() {
      const url = previewFile(this.fileId)
      if (IMAGE_TYPE.includes(this.fileExt)) {
        this.fileType = 'image'
        this.url = url + '&type=' + this.fileType
        this.images = [this.url]
      } else if (PDF_TYPE.includes(this.fileExt) || OFFICE_TYPE.includes(this.fileExt)) {
        this.fileType = 'pdf'
        this.$nextTick(() => {
          this.$refs.viewer.load(url + '&type=' + this.fileType)
        })
      } else if (AUDIO_TYPE.includes(this.fileExt)) {
        this.fileType = 'audio'
        this.url = url + '&type=' + this.fileType
      } else if (VIDEO_TYPE.includes(this.fileExt)) {
        this.fileType = 'video'
        this.url = url + '&type=' + this.fileType
      }
    },
    onCancel() {
      this.$emit('input', false)
    }
  }

}
</script>
