<template>
<div class="honjo-file-viewer">
  <div class="honjo-file-viewer__content">
    <span class="honjo-file-viewer__prefix">
      <i class="el-icon-paperclip"></i>
    </span>
    <span class="honjo-file-viewer__text" :title="actualTitle">{{actualTitle}}</span>
    <span class="honjo-file-viewer__suffix">
      <el-link :underline="false" @click="onPreview()" v-if="canPreview" style="margin-left: 8px;" class="el-icon-view"></el-link>
      <el-link :underline="false" @click="onDownload()" style="margin-left: 8px;" class="el-icon-download"></el-link>
    </span>
  </div>

  <div style="height: 0;overflow: hidden;"><el-image style="width: 0px; height: 0px" :preview-src-list="imageUrls" ref="image"></el-image></div>
</div>
</template>

<script lang="ts">

import { Vue, Component, Prop, Ref, Emit } from 'vue-property-decorator'
import config from '../../config'
import { getFileType } from '../../utils/file'

@Component
export default class HonjoFileViewer extends Vue {
  @Prop(String) name!: string

  @Prop(String) url!: string

  @Prop(String) title!: string

  @Prop(Function) onView!: any

  @Prop(Function) onDld!: any

  @Ref() image!: any

  imageUrl = ''

  get imageUrls () {
    return this.imageUrl ? [this.imageUrl] : []
  }

  get filename () {
    const urlO = new URL(this.url)
    const url = urlO.origin + urlO.pathname
    const idx = (url || '').lastIndexOf('/')
    if (idx >= 0) return (url || '').slice(idx + 1)
    return 'unkown'
  }

  get actualTitle () {
    const _name = this.title || this.filename
    let n
    try {
      n = decodeURIComponent(_name)
    } catch {
      n = _name
    }
    return n
  }

  get actualName () {
    const _name = this.name || this.filename
    let n
    try {
      n = decodeURIComponent(_name)
    } catch {
      n = _name
    }
    return n
  }

  get canPreview () {
    return ['image', 'pdf', 'word', 'excel', 'ppt'].includes(getFileType(this.url))
  }

  onPreview () {
    if (this.onView) {
      this.onView(this.url)
      return
    }
    // if (getFileType(this.url) === 'pdf') config.previewPdf(this.url)
    // else
    if (['word', 'excel', 'ppt', 'pdf'].includes(getFileType(this.url))) config.previewOffice(this.url)
    else if (getFileType(this.url) === 'image') {
      this.imageUrl = this.url
      this.image.clickHandler()
      this.$nextTick(() => {
        this.image.clickHandler()
      })
    } else {
      this.$message.info('尚不支持预览该类型文件')
    }
  }

  onDownload () {
    this.onDld && this.onDld(this.actualName, this.url)
    config.download(this.actualName, this.url)
  }
}
</script>

<style lang="scss">
@import "./style/index.scss";

</style>
