<!--文档预览-->

<template>
  <div class="preview-container" :style="{width: localWidth, height: localHeight}"
       :class="['preview-container', {'full-screen': fullscreen,}]"
  >
    <!--:class="['preview-container', {'full-screen': fullscreen, 'media-container': fileType === 'mp4' || fileType === 'mp3'}]"-->

    <!--<el-empty v-if="!url || !localUrl" description="加载中..."></el-empty>-->
    <div v-if="!url || !localUrl" class="empty-loading">
      <div>
        <i class="el-icon-loading"></i>
        <span>努力加载中...</span>
      </div>
    </div>

    <!-- 图片 -->
    <ImagePreview v-else-if="localUrl && isPic" :src="localUrl" fit="contain" width="100%" height="100%"></ImagePreview>

    <!--style="height: 100%; width: 100%;"-->
    <!-- excel  -->
    <vue-office-excel
      v-else-if="localUrl && (fileFinalType === 'xlsx' || fileFinalType === 'xls')"
      :src="localUrl"
      :key="fullscreen"
      class="excel-box"
      ref="excel"
      :options="options"
      @rendered="renderedHandler"
      @error="errorHandler"
    />

    <!-- docx-->
    <vue-office-docx
      :src="localUrl"
      v-else-if="localUrl && fileFinalType === 'docx'"
      @rendered="renderedHandler"
      @error="errorHandler"
    />

    <!--<vue-office-pdf-->
    <!--  v-else-if="fileType === 'pdf'"-->
    <!--  :src="localUrl"-->
    <!--  @rendered="renderedHandler"-->
    <!--  @error="errorHandler"-->
    <!--/>-->
    <!--pdf-->
    <iframe v-else-if="localUrl && fileFinalType === 'pdf'" :src="localUrl" class="pdf-iframe"/>

    <!-- 视频 -->
    <vue-plyr v-else-if="localUrl && fileFinalType === 'mp4'">
      <video controls crossorigin playsinline data-poster="poster.jpg">
        <source :src="localUrl" type="video/mp4" />
      </video>
    </vue-plyr>

    <!-- 音频 -->
    <vue-plyr v-else-if="localUrl && fileFinalType === 'mp3'">
      <audio controls crossorigin playsinline>
        <source :src="localUrl" type="audio/mp3"/>
        <!--<source src="/path/to/audio.ogg" type="audio/ogg"/>-->
      </audio>
    </vue-plyr>

    <div v-else style="display: flex; flex-direction: column; align-items: center; justify-content: center">
      <el-empty description="暂不支持该格式文件预览，请下载后查看"></el-empty>

      <button class="button" type="button">
        <span class="button__text">Download</span>
        <span @click="downloadFile" class="button__icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 35 35" id="bdd05811-e15d-428c-bb53-8661459f9307" data-name="Layer 2" class="svg"><path d="M17.5,22.131a1.249,1.249,0,0,1-1.25-1.25V2.187a1.25,1.25,0,0,1,2.5,0V20.881A1.25,1.25,0,0,1,17.5,22.131Z"></path><path d="M17.5,22.693a3.189,3.189,0,0,1-2.262-.936L8.487,15.006a1.249,1.249,0,0,1,1.767-1.767l6.751,6.751a.7.7,0,0,0,.99,0l6.751-6.751a1.25,1.25,0,0,1,1.768,1.767l-6.752,6.751A3.191,3.191,0,0,1,17.5,22.693Z"></path><path d="M31.436,34.063H3.564A3.318,3.318,0,0,1,.25,30.749V22.011a1.25,1.25,0,0,1,2.5,0v8.738a.815.815,0,0,0,.814.814H31.436a.815.815,0,0,0,.814-.814V22.011a1.25,1.25,0,1,1,2.5,0v8.738A3.318,3.318,0,0,1,31.436,34.063Z"></path></svg></span>
      </button>

    </div>

    <!-- 切换全屏-->
    <div v-if="showFullScreen" class="full-screen__menu" @click="toggleFullScreen">
      <i class="el-icon-full-screen"></i>
    </div>
  </div>
</template>

<script>

import VueOfficeExcel from '@vue-office/excel'
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'

import VuePlyr from 'vue-plyr'
import 'vue-plyr/dist/vue-plyr.css'
import ImagePreview from '@/components/ImagePreview/index.vue'

// 支持的图片格式 // TODO 这些格式应该放到全局配置中
const SUPPORT_IMAGE_FORMAT = new Set(['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'])
// 支持的视频格式
const SUPPORT_VIDEO_FORMAT = new Set(['mp4', 'avi', 'mov', 'rmvb', 'rm', 'flv', '3gp', 'wmv', 'mkv'])
// 支持的音频格式
const SUPPORT_AUDIO_FORMAT = new Set(['mp3', 'wav', 'wma', 'ogg', 'ape', 'acc', 'flac'])
// 支持的文件格式汇总
const SUPPORT_FILE_FORMAT = new Set(
  [
    // 'pdf', 'docx', 'xlsx', 'xls',
    'pdf',
    ...SUPPORT_IMAGE_FORMAT,
    ...SUPPORT_VIDEO_FORMAT,
    ...SUPPORT_AUDIO_FORMAT
  ])

export default {
  components: { VueOfficeExcel,VueOfficeDocx, VuePlyr, ImagePreview},
  props: {
    url: {
      type: String,
      required: true,
    },
    fileName: {
      type: String,
      default: ''
    },
    fileType: {
      type: String,
    },
    width: {
      type: String,
      default: '750px'
    },
    height: {
      type: String,
      default: '600px'
    }
  },
  data() {
    return {
      loading: true,
      baseApi: process.env.VUE_APP_BASE_API,
      localUrl: null,
      // localUrl: 'http://localhost:8080/train-profile/bb/pexels-photo-2023384_20240617154854A002.png',
      localWidth: this.width,
      localHeight: this.height,

      isPic: false,
      isVideo: false,
      isAudio: false,

      fullscreen: false,
      fileFinalType: '',
      options: {
        xls: true,       //预览xlsx文件设为false；预览xls文件设为true
        minColLength: 0,  // excel最少渲染多少列，如果想实现xlsx文件内容有几列，就渲染几列，可以将此值设置为0.
        minRowLength: 0,  // excel最少渲染多少行，如果想实现根据xlsx实际函数渲染，可以将此值设置为0.
        widthOffset: 10,  //如果渲染出来的结果感觉单元格宽度不够，可以在默认渲染的列表宽度上再加 Npx宽
        heightOffset: 10, //在默认渲染的列表高度上再加 Npx高
        beforeTransformData: (workbookData) => {
          return workbookData
        }, //底层通过exceljs获取excel文件内容，通过该钩子函数，可以对获取的excel文件内容进行修改，比如某个单元格的数据显示不正确，可以在此自行修改每个单元格的value值。
        transformData: (workbookData) => {
          return workbookData
        } //将获取到的excel数据进行处理之后且渲染到页面之前，可通过transformData对即将渲染的数据及样式进行修改，此时每个单元格的text值就是即将渲染到页面上的内容
      },

      // uniKey: 1
    }
  },

  watch: {

    url: {
      handler(newVal, oldVal) {
        // this.loading = true
        if (!newVal) return
        // console.log('url change:', newVal, oldVal)
        this.initPreview()
        if (newVal && !newVal.includes('http') && !this.isPic) {
          this.localUrl = this.baseApi + newVal
        } else {
          this.localUrl = newVal
        }
        // console.log('localUrl:', this.localUrl)
      },
      immediate: true
    }
  },

  created() {

  },

  computed: {
    showFullScreen() {
      return !this.isPic && !this.isVideo && !this.isAudio
    }
  },

  methods: {
    initPreview() {
      this.getFileType()
      // console.log('fileType:', this.fileFinalType)

      if (!SUPPORT_FILE_FORMAT.has(this.fileFinalType)) {
        // throw new Error('文件格式不支持')
        this.$message.error('文件格式不支持')
        return
      }
      this.isPic = SUPPORT_IMAGE_FORMAT.has(this.fileFinalType);
      this.isVideo = SUPPORT_VIDEO_FORMAT.has(this.fileFinalType);
      this.isAudio = SUPPORT_AUDIO_FORMAT.has(this.fileFinalType);

      if (this.fileFinalType === 'xlsx') {
        this.options.xls = false
      } else if (this.fileFinalType === 'xls') {
        this.options.xls = true
      }

    },

    getFileType() {
      // if (!this.localUrl) {
      if (!this.url) {
        return null
      }
      const fileName = this.url.lastIndexOf('.')//取到文件名开始到最后一个点的长度
      const fileNameLength = this.url.length//取到文件名长度
      const fileFormat = this.fileType || this.url.substring(fileName + 1, fileNameLength)//截
      this.fileFinalType = fileFormat.toLowerCase()
      return fileFormat
    },

    renderedHandler() {
      // console.log('渲染完成')
      this.$emit('rendered')
    },
    errorHandler() {
      // console.log('渲染失败')
      this.$emit('error')
    },
    toggleFullScreen() {
      const localUrl = this.localUrl
      if (this.fileFinalType !== 'pdf' && !this.isPic) {
        this.localUrl = ''
      }

      this.fullscreen = !this.fullscreen
      // console.log('this.fullscreen', this.fullscreen)
      if (this.fullscreen) {
        this.localWidth = '100vw'
        this.localHeight = '100vh'
      } else {
        this.localWidth = this.width
        this.localHeight = this.height
      }

      if (this.fileFinalType !== 'pdf' && !this.isPic) {
        setTimeout(() => {
          // this.localUrl = this.url
          this.localUrl = localUrl
        }, 200)
      }

      // this.$refs.excel
      this.$emit('toggle-fullscreen', this.fullscreen)
    },

    downloadFile() {
      // 文件的 HTTP 地址
      const fileUrl = this.localUrl;
      // 创建一个隐藏的链接元素
      const link = document.createElement('a');
      link.href = fileUrl;
      // 设置下载的文件名
      // link.download = 'file.pdf';
      // 将链接元素添加到 DOM 中
      document.body.appendChild(link);
      // 程序化地点击链接
      link.click();
      // 点击后从 DOM 中移除链接元素
      document.body.removeChild(link);
    }
  }
}

</script>

<style scoped lang="scss">
.preview-container {
  position: relative;
  z-index: 1000;
  padding: 10px;
  border-radius: 10px; /* 圆角 */
  background: white;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5); /* 阴影 */
  //overflow: hidden;
  overflow: auto;

  // 宽高过渡动画
  transition: all 0.2s ease; /* 添加过渡动画 */

  .el-image {
    background-color: #D3D3D3 ;
  }


  .pdf-iframe {
    // 定位是为了让 z-index 生效
    position: relative;
    // z-index 是为了避免preview-container::before 遮挡
    z-index: 2000;
    width: 100%;
    height: 100%;
    border: none;
    //border-radius: 10px;
  }

  //.excel-box {
  //  // 定位是为了让 z-index 生效
  //  position: relative;
  //  // z-index 是为了避免preview-container::before 遮挡
  //  z-index: 2000;
  //  width: 100%;
  //  height: 100%;
  //  border: none;
  //}


  .full-screen__menu {
    z-index: 2001;
    position: absolute;
    right: 30px;
    bottom: 15px;
    cursor: pointer;
    color: #fff;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 50%;
    padding: 5px;
    i {
      font-size: 20px;
    }
  }

  .full-screen__menu:hover {
    background: rgba(0, 0, 0, 0.5);
  }
}

//.preview-container::before {
//  content: "";
//  position: absolute;
//  top: 0;
//  left: 0;
//  right: 0;
//  bottom: 0;
//  border-radius: 10px; /* 与容器圆角相同 */
//  padding: 2px; /* 边框宽度 */
//  background: linear-gradient(45deg, #f06, #f90, #0f0, #09f, #06f);
//  -webkit-mask: linear-gradient(#fff 0 0) content-box,
//  linear-gradient(#fff 0 0);
//  mask: linear-gradient(#fff 0 0) content-box,
//  linear-gradient(#fff 0 0);
//  -webkit-mask-composite: destination-out;
//  mask-composite: exclude;
//}

.full-screen {
  position: fixed;
  padding: 0;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 2003;
  background-color: white;
  border: none;
}

.empty-loading {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: lightslategray;
  border-radius: 10px;
  color: red;

  .el-icon-loading {
    font-size: 30px;
  }
  span {
    margin-left: 10px;
  }
}


// button start
.button {
  position: relative;
  width: 150px;
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  border: 1px solid #17795E;
  background-color: #E70618;
  overflow: hidden;
}

.button, .button__icon, .button__text {
  transition: all 0.3s;
}

.button .button__text {
  transform: translateX(22px);
  color: #fff;
  font-weight: 600;
}

.button .button__icon {
  position: absolute;
  transform: translateX(109px);
  height: 100%;
  width: 39px;
  background-color: #B80513;
  display: flex;
  align-items: center;
  justify-content: center;
}

.button .svg {
  width: 20px;
  fill: #fff;
}

.button:hover {
  background: #B80513;
}

.button:hover .button__text {
  color: transparent;
}

.button:hover .button__icon {
  width: 148px;
  transform: translateX(0);
}

.button:active .button__icon {
  background-color: #960410;
}

.button:active {
  border: 1px solid #960410;
}
// button end




</style>
