<template>
  <div class="app-container">
    <h3 class="toolbar">
      <div class="tool">
        <el-button type="primary" plain icon="el-icon-upload2" size="mini" @click="handleUpload" v-if="userType == 'ENT_TECH' || userType == 'ENT_ADMIN_TECH'" v-hasRole="['ENT_ADMIN_TECH','ENT_TECH']">一键上传</el-button>
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleDownloadBatch">批量下载</el-button>
        <el-button type="primary" plain icon="el-icon-delete" size="mini" @click="handleBatchDelte" v-if="userType == 'ENT_TECH' || userType == 'ENT_ADMIN_TECH'">批量删除</el-button>
      </div>
    </h3>
    <el-table v-loading="loading" :data="list" border @selection-change="handleSelectionChange" style="width: 100%" @select-all="selectAll">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
      <el-table-column label="文件名称" prop="fileName" align="center"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" @click="handleDownload(scope.row)">下载</el-button>
          <el-button type="text" @click="handleDelete(scope.row)" v-if="userType == 'ENT_TECH' || userType == 'ENT_ADMIN_TECH'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>
    <upload-enclosure ref="uploadEnclosure" v-if="enclosureVisible" @refreshData="getList()" :dataId="dataId" :attachType="'PROJECT'"></upload-enclosure>
    <div class="container" style="margin-top: 20px;">
      <div v-show="loading" class="well loading">正在加载中，请耐心等待...</div>
      <div v-show="!loading" class="well" ref="output"></div>
    </div>
  </div>
</template>

<script>
  import {getEnclosureApi,deleteEnclosureApi,getProjectInfoApi} from '@/api/enterprise/project/project'
  import UploadEnclosure from './UploadEnclosure'
  import { getExtend, readBuffer, render } from '@/utils/util';
  import { parse } from 'qs';
  import axios from 'axios'
  export default {
    components: {
      UploadEnclosure
    },
    data() {
      return {
        total: 0,
        enclosureVisible: false,
        list: [],
        id: this.$route.query.id,
        dataId: undefined,
        attachType: 'PROJECT',
        loading: false,
        selectionList: [],
        ids: '',
        queryParams: {
          pageNum: 1,
          pageSize: 10
        }
      };
    },
    computed: {
      userType() {
        return this.$store.state.user.userType
      }
    },
    created() {
      this.id = this.$route.query.id || undefined;
      this.getData()
    },
    methods: {
      getData() {
        getProjectInfoApi(this.id).then(res => {
          let obj = res.data.techProject || {}
          this.dataId = obj.id //技术资料id
          this.getList()
        })
      },
      getList() {
        getEnclosureApi(this.attachType,this.dataId).then(res => {
          if(res.code == 200) {
            this.list = res.data.records
            this.total = res.data.total
          }
        })
      },
      handleUpload() {
        this.enclosureVisible = true
        this.$nextTick(() => {
          this.$refs.uploadEnclosure.init()
        })
      },
      handleDownload(row) {
        window.open("http://124.232.146.72:7015/api/common/attach/"+row.id)
      },
      handleDownloadBatch() {
        if(this.selectionList.length <=0) {
          this.$message.error('请选择要下载的数据');
          return
        }
        window.open("http://124.232.146.72:7015/api/common/attach/"+this.ids)
        this.getList();
      },
      handleBatchDelte() {
        if(this.selectionList.length <=0) {
          this.$message.error('请选择要删除的数据');
          return
        }
        this.$confirm('请确认是否删除所选择的数据！', '提示').then(() => {
        	deleteEnclosureApi(this.ids).then(res => {
            if(res.code == 200) {
              this.queryParams.pageNum = 1;
              this.getList();
              this.$modal.msgSuccess("删除成功");
            }
        	})
        })
      },
      // 从url加载
      handleView(row) {
		  let routeUrl = this.$router.resolve({
		    path: '/enclosurePreview',
		    query: {url: row.url,fileName: row.fileName,id: row.id}
		  });
		  window.open(routeUrl.href, "_blank");
        // this.loading = true;
        // // 要预览的文件地址
        // const { url } = row.url;
        // const filename = row.fileName
        // // const filename = url.substr(url.lastIndexOf('/') + 1);
        // // 拼接iframe请求url
        // axios({
        //   url: "http://124.232.146.72:7015/api/common/attach/"+row.id,
        //   method: 'get',
        //   responseType: 'blob',
        // }).then(({ data }) => {
        //   if (!data) {
        //     console.error('文件下载失败');
        //   }
        //   const file = new File([ data ], filename, {});
        //   this.handleChange({ target: { files: [ file ] } });
        // }).finally(() => {
        //   this.loading = false;
        // })
      },
      async handleChange(e) {
        this.loading = true;
        try {
          const [ file ] = e.target.files;
          this.filename = file.name && decodeURIComponent(file.name) || '';
          const arrayBuffer = await readBuffer(file);
          this.loading = false
          this.last = await this.displayResult(arrayBuffer, file)
          console.log("last")
          console.log(this.last)
        } catch (e) {
          console.error(e)
        } finally {
          this.loading = false
        }
      },
      displayResult(buffer, file) {
        // 取得文件名
        const { name } = file;
        // 取得扩展名
        const extend = getExtend(name);
        // 输出目的地
        const { output } = this.$refs;
        // 生成新的dom
        const node = document.createElement('div');
        // 添加孩子，防止vue实例替换dom元素
        if (this.last) {
          output.removeChild(this.last.$el);
          this.last.$destroy();
        }
        const child = output.appendChild(node);
        // 调用渲染方法进行渲染
        return new Promise((resolve, reject) => render(buffer, extend, child)
            .then(resolve).catch(reject));
      },
      handleDelete(row) {
        const id = row.id;
        this.$confirm('是否确认删除该数据?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            return deleteEnclosureApi(id);
          }).then(() => {
            this.queryParams.pageNum = 1;
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
      },
      // 取消全选
      selectAll(selection) {
        if (selection.length == 0) {
          let list = this.selectedList.filter(item => !this.list.some(ele => ele.id === item.id));
          this.selectionList = list;
        }
      },
      handleSelectionChange(val) {
        this.selectionList = val;
        if(this.selectionList.length > 0) {
          let selectionIds = []
          for (let i = 0, len = this.selectionList.length; i < len; i++) {
          	selectionIds.push(this.selectionList[i].id)
          }
          this.ids = selectionIds.join(',')
        }else {
          this.ids = ''
        }
      }
    }
  };
  </script>

</script>

<style>
</style>
