<template>
  <el-dialog
    title="历史版本"
    :visible.sync="dialogVisible"
    width="50%"
    :before-close="handleClose"
  >
    <template>
      <el-table
        :data="tableData"
        style="width: 100%"
        stripe
        :header-cell-style="{ background: '#F7F7F7' }"
      >
        <el-table-column
          prop="name"
          align="center"
          show-overflow-tooltip
          label="文件名称"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="docUrl"
          align="center"
          show-overflow-tooltip
          label="链接地址"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="createUser"
          align="center"
          show-overflow-tooltip
          label="创建人"
        >
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          show-overflow-tooltip
          label="创建时间"
        >
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="download(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="dialogVisible = false">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import * as api from '@/api/api'
export default {
  data() {
    return {
      dialogVisible: false,
      tableData: []
    }
  },
  methods: {
    handleClose() {
      this.dialogVisible = false
    },
    openClose(val) {
      this.dialogVisible = true
      this.listDataInit(val)
    },
    /**
     * @method 历史版本信息
     * **/
    listDataInit(val) {
      let code = {
        id: val.id
      }
      api.GET('/doc/getDocHistoryList', code).then(data => {
        if (data.code == 0) {
          this.tableData = data.data
        }
      })
    },
    /**
     * @method 下载
     * **/
    download(val) {
      fetch(val.docUrl, {
        method: 'get',
        responseType: 'arraybuffer'
      })
        .then(function (res) {
          if (res.status !== 200) {
            return res.json()
          }
          return res.arrayBuffer()
        })
        .then(blobRes => {
          // 生成 Blob 对象，设置 type 等信息
          const e = new Blob([blobRes], {
            type: 'application/octet-stream',
            'Content-Disposition': 'attachment'
          })
          // 将 Blob 对象转为 url
          let formName = val.name + '.pdf'
          const link = window.URL.createObjectURL(e)
          this.handleFileDownload(link, formName)
        })
        .catch(err => {
          console.error(err)
        })
    },
    handleFileDownload(url, filename) {
      // 创建 a 标签
      let a = document.createElement('a')
      a.href = url
      a.download = filename
      a.click()
    }
  }
}
</script>