<template>
    <div class="wrap" v-loading="loading">
      <div class="inner">
      <el-page-header @back="$router.back()" content="我的数据"></el-page-header>
        <div class="tool">
          <el-input style="width: 250px" placeholder="请输入文件名称" v-model="keyword" suffix-icon="el-icon-search" clearable size="small"></el-input>
          <div class="action">
            <el-upload :headers="{token}" :action="api.fileUpload" name="file" :limit="1000" :show-file-list="false" :before-upload="beforeImport" :on-success="successImport">
              <el-button type="primary" size="small">导入数据</el-button>
            </el-upload>
            <el-button style="margin-left: 10px;" type="danger" size="small" @click="delAll">批量删除</el-button>
          </div>
        </div>

        <el-table :data="list" class="cus-table" ref="table" stripe header-align="center" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="80" align="center"></el-table-column>
            <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
            <el-table-column prop="fileName" label="文件名称" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTime" label="导入时间" align="center"></el-table-column>
            <el-table-column prop="fileSize" label="文件大小" width="120" align="center">
              <template slot-scope="scope">
                {{ (scope.row.fileSize / 1024 / 1024).toFixed(2) }}MB
              </template>
            </el-table-column>
            <el-table-column prop="fileFormat" label="格式" width="100" align="center"></el-table-column>
            <el-table-column label="文件路径" align="center">
              <template slot-scope="scope">
                {{ scope.row.ossFileName }}
                <i class="el-icon-document-copy copy" @click="copy($event, scope.row)"></i>
              </template>
            </el-table-column>
            <el-table-column width="300" label="操作" align="center">
                <template slot-scope="scope">
                    <el-button type="text" @click="show(scope.row)">查看</el-button>
                    <el-button type="text" @click="download(scope.row)">下载</el-button>
                    <el-button type="text" @click="del(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination background layout="total,prev, pager, next" :current-page="page" @current-change="handleCurrentChange" :total="total"></el-pagination>
        </div>
      </div>
    </div>
</template>
<script>
import util from '@/util'
import clipboard from '@/util/clipboard'
export default {
    data() {
        return {
          token: util.getCookie('token'),
          loading: false,
          list: [],
          multipleSelection: [],
          keyword: '',
          page: 1,
          pageSize: 10,
          total: 0
        };
    },
    watch: {
        keyword: function(val) {
          clearTimeout(this.searchTimer)
          this.searchTimer = setTimeout(() => {
            this.initData()
          },500)
        }
    },
    created() {
      this.loading = true
    },
    mounted(){
      this.getData()
    },
    methods: {
      // 获取列表
      getData() {
        this.$post(`${this.api.myData}?fileName=${this.keyword}&pageNum=${this.page}&pageSize=${this.pageSize}`).then(res => {
          const { data } = res
          this.list = data.records
          this.total = data.total
          this.loading = false
        }).catch(res => {
          this.loading = false
        })
      },
      // 初始化列表
      initData() {
        this.page = 1
        this.getData()
      },
      // 导入前的钩子
      beforeImport(file) {
        const { size, name } = file
        if (util.isVideo(name.substring(name.lastIndexOf('.') + 1))) {
          this.$message.error('不支持上传视频，请选择其他文件！')
          return false
        }
        if (size / 1024 / 1024 > 10) {
          this.$message.error('请上传10M以内的文件！')
          return false
        }
      },
      // 导入数据成功
      successImport(res) {
        const file = res.filesResult
        const name = file.originalFileName
        this.$post(this.api.importData, {
          fileFormat: file.fileType,
          fileName: name.substring(0, name.lastIndexOf('.')),
          filePath: file.fileUrl,
          fileSize: file.fileSize,
          ossFileName: file.ossFileName
        }).then(res => {
          this.$message.success('导入成功')
          this.getData()
        }).catch(res => {})
      },
      // 批量删除
      delAll() {
        if(this.multipleSelection.length){
          const newArr = this.multipleSelection
          const delList = newArr.map(item => {
            return `ids=${item.id}`
          })
          this.$confirm(`此批量删除操作不可逆，是否确认删除？`, '提示', {
            type: 'warning'
          }).then(() => {
            this.$post(`${this.api.batchDeletion}?${delList.join('&')}`).then(res => {
              this.$refs.table.clearSelection()
              this.$message.success('删除成功')
              this.getData()
            }).catch(res => {})
          }).catch(() => {})
        }else{
          this.$message.error('请先选择数据 ！')
        }
      },
      // 复制
      copy(e, row) {
        clipboard(row.filePath, e, '文件路径已复制！')
      },
      // 查看
      show(row) {
        // 如果是word,pdf,excel，就用预览插件打开，图片等就直接打开
        const format = row.fileFormat
        if ('xls,xlsx'.includes(format)) {
          this.$router.push(`/preview?path=${row.filePath}`)
        } else {
          window.open((util.isDoc(format) ? 'https://view.officeapps.live.com/op/view.aspx?src=' : '') + row.filePath)
        }
      },
      // 下载
      download(row) {
        util.downloadFile(row.fileName + '.' + row.fileFormat, row.filePath)
      },
      // 删除
      del(row) {
        this.$confirm('此删除操作不可逆，是否确认删除选中项？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$post(`${this.api.batchDeletion}?ids=${row.id}`).then(res => {
            this.$message.success('删除成功')
            this.getData()
          }).catch(res => {})
        }).catch(() => {})
      },
      handleCurrentChange(val) {
        this.page = val
        this.getData()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      }
    }
};
</script>
<style lang="scss" scoped>
.wrap {
  padding: 20px;
  background-color: #f3f6fa;
  .inner {
    padding: 15px;
    background-color: #fff;
    border-radius: 4px;
  }
  .tool {
    display: flex;
    justify-content: space-between;
    margin: 20px 0;
  }
  .action {
    display: inline-flex;
  }
  .copy {
    margin-left: 5px;
    cursor: pointer;
  }
}
</style>