<template>
  <div>
    <span v-if="fileList.length > 0" v-for="(item, index) in imageList" :key="item.uid" style="padding-right: 8px;"><a @click="handlePreview(item)"><a-icon type="link" />{{item.name}}</a><br v-if="index < (imageList.length - 1)"/></span>
    <span v-if="fileList.length === 0">{{text ? '查看附件' : '无附件'}}</span>
  </div>
</template>

<script>

  import { getFileAccessHttpUrl } from '../../utils/manage'
  import TokenStorageUtil from "../../utils/TokenStorageUtil";

  export default {
    name: 'ViewFileSlot',
    data () {
      return {
        fileList: [],
        text: null,
      }
    },
    props: {
      value: {
        type: String,
      }
    },
    methods: {
      handlePreview(file) {
        // 下载文件
        const x = new XMLHttpRequest();
        x.open("GET", getFileAccessHttpUrl(file.url || file.thumbUrl), true);
        x.responseType = 'blob';

        const token = TokenStorageUtil.get()
        x.setRequestHeader('X-Access-Token', token);

        x.onload = function (e) {
          const url = window.URL.createObjectURL(x.response);
          const a = document.createElement("a");
          a.href = url
          a.download = file.name
          a.click()
        }
        x.send();
      },
    },
    watch: {
      value: {
        handler (val) {
          try {
            if (val && val.length > 0 && val.indexOf("url") !== -1) {
              this.fileList = JSON.parse(val)
              this.text = null
            } else {
              this.fileList = []
              this.text = val
            }
          } catch (e) {
            this.fileList = []
            this.text = val
          }
        },
        immediate: true
      }
    },
    computed: {
      imageList () {
        return this.fileList.map(item => {
          return {
            uid: item.uid,
            name: item.name,
            url: getFileAccessHttpUrl(item.url) || ''
          }
        })
      }
    }
  }
</script>
<style lang="less" scoped>

</style>
