<template>
  <div class="dataDiv">
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <div>{{ loadingMessage }}</div>
    </div>
    <el-button type="primary" @click="download" style="position: absolute;left: 92%;top: -7%">下载</el-button>
    <iframe :src="file" frameborder="0" width="100%" height="720px" @load="onIframeLoad"></iframe>
  </div>
</template>

<script>
import { filePreview, lookFaceFile, lookFile, lookMioIoFile } from '@/utils/bonus' // Assuming Base64 is saved as a separate module
import useBase64 from '@/api/base64Utils'
import { encryptCBC, encryptCBCTime } from '@/utils/aescbc'
import { downloadFile } from '@/api/tool/select'

export default {
  name: 'FileHandler',
  props: {
    items: {
      type: Object,
      default: () => {
        return {
          filePreviewUrl: ''
        }
      }
    },
    fileType: {
      type: String,
      default: '' // docx: word
    },
    lookType: {
      type: String,
      default: 'normal'
    }
  },
  data() {
    return {
      // lookFile: 'http://218.21.27.6:1999/nxnyback/statics',
      // filePreviewPath: 'http://218.21.27.6:8012/onlinePreview?url=',
      // lookFile: 'http://112.29.103.165:14413/file/statics',
      lookFile: '',
      filePreviewPath: '',
      file: '',
      loading: true,
      loadingMessage: 'Loading...'
    }
  },
  created() {
    console.log('this.lookType', this.lookType)
    if (this.lookType === 'normal') {
      this.lookFile = lookFile()
    } else {
      this.lookFile = lookMioIoFile()
    }
    this.filePreviewPath = filePreview()
  },
  methods: {
    setParam() {
      this.filePreviewPath = filePreview()
      if (this.lookType === 'normal') {
        this.lookFile = lookFile()
      } else {
        this.lookFile = lookMioIoFile()
      }
      console.log(`${this.lookFile}/${this.items.filePreviewUrl}`)
      this.file = ''
      this.loading = true
      this.loadingMessage = 'Loading...'
      this.updateLoadingMessage()
      let filePath = this.items.filePreviewUrl
      let fileNames = this.items.fileName
      let suffix = ''
      if (fileNames && fileNames !== 'null' && fileNames !== 'undefined') {
        suffix = fileNames.substring(fileNames.lastIndexOf('.') + 1)
      }

      let fileUploadPath = filePath
      let filePreviewPath
      let time = encryptCBCTime(Math.floor(Date.now()).toString())
      if (suffix.toLowerCase() === 'pdf') {
        filePreviewPath = filePath.includes('http') ? filePath : `${this.lookFile}/${filePath}`
        this.showDownloadButton = false
        console.log('filePreviewPath', filePreviewPath)
      } else {
        const encodedPath = filePath.includes('http')
          ? encodeURIComponent(useBase64.encode64(`${filePath}`))
          : encodeURIComponent(useBase64.encode64(`${this.lookFile}/${filePath}`))
        filePreviewPath = `${this.filePreviewPath}${encodedPath}&token=${time}`
        console.log('filePreviewPath', filePreviewPath)
        if (fileNames.length > 50) {
          this.fileName = `${fileNames.substring(0, 50)}...`
        } else {
          this.fileName = fileNames
        }

        this.showDownloadButton = !['jpg', 'png', 'JPG', 'PNG'].includes(suffix)
        console.log('encodedPath', encodedPath)
      }
      console.log('filePreviewPath', filePreviewPath)
      const isEdgeOrOther = /Edg|Chrome|Firefox|Safari/.test(navigator.userAgent)
      if (isEdgeOrOther) {
        const url = new URL(filePreviewPath)
        url.searchParams.append('preventDownload', 'true')
        filePreviewPath = url.toString()
      }
      console.log('filePreviewPath', filePreviewPath)
      this.file = filePreviewPath
      this.fileUploadPath = fileUploadPath
    },
    onIframeLoad() {
      this.loading = false
      this.loadingMessage = ''
    },
    updateLoadingMessage() {
      let dots = 0
      const interval = setInterval(() => {
        if (!this.loading) {
          clearInterval(interval)
          return
        }
        dots = (dots + 1) % 4
        this.loadingMessage = 'Loading' + '.'.repeat(dots)
      }, 500)
    },
    fillInComments() {
      this.$prompt('请填写意见', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.$message({
          type: 'success',
          message: '填写成功'
        })
        this.$emit('fillInComments', value)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    download() {
      if (this.fileType === 'docx') {
        // 将路径 .pdf的 替换为 .doc, 下载docx文件
        this.fileUploadPath = this.fileUploadPath.replace('.pdf', '.docx')
        console.log('🚀 ~ download ~ this.fileUploadPath:', this.fileUploadPath)
      }
      downloadFile(this.fileUploadPath, this.$props.items.fileName)
    }
  },
  watch: {
    items: {
      handler: 'setParam',
      immediate: true
    }
  }
}
</script>
<style scoped>
.dataDiv {
  width: 100%;
  height: 600px;
  float: left;
  position: relative;
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  color: #000;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #000;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
  margin-left: 15px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
