<script>
import UploadFileList from "../common/uploadFileList.vue";
import {downloadFileList, getFileContentList, removeFile} from "@/api/test/testInformation";
import {deleteQuotationFile, downLoadQuotationFile} from "@/api/quotation/quotationInformation";

export default {
  name: "profingFile",
  components: {UploadFileList},
  props:{
    testNo:{
      type:String,
    },
    height:{
      type:Number,
      default:300
    },
  },

  data(){
    return{
      uploadDialog:false,
      fileRemark:'',
      token:'',
      fileList:[],
      dataList:[],
      columnList:[
          {
            userId: this.$store.state.user.name,
            functionId: 104001,
            serialNumber: '104001Table4FileName',
            tableId: '104001Table4',
            tableName: '文件信息表',
            columnProp: 'fileName',
            headerAlign: 'center',
            align: 'center',
            columnLabel: '文件名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            userId: this.$store.state.user.name,
            functionId: 104001,
            serialNumber: '104001Table4FileRemark',
            tableId: '104001Table4',
            tableName: '文件信息表',
            columnProp: 'fileRemark',
            headerAlign: 'center',
            align: 'center',
            columnLabel: '备注',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            userId: this.$store.state.user.name,
            functionId: 104001,
            serialNumber: '104001Table4CreateDate',
            tableId: '104001Table4',
            tableName: '文件信息表',
            columnProp: 'createDate',
            headerAlign: 'center',
            align: 'center',
            columnLabel: '上传时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            userId: this.$store.state.user.name,
            functionId: 104001,
            serialNumber: '104001Table4CreatedBy',
            tableId: '104001Table4',
            tableName: '文件信息表',
            columnProp: 'createBy',
            headerAlign: 'center',
            align: 'center',
            columnLabel: '上传人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          }
        ],

    }

  },
  methods:{
    getFileContentList(){
      let params = {
        orderRef1:this.$store.state.user.site,
        orderRef2:this.testNo
      }
      getFileContentList(params).then(({data})=>{
        if (data && data.code === 0){
          this.dataList=data.rows
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    downloadFile (row) {
      downLoadQuotationFile(row).then(({data}) => {
        // 不限制文件下载类型
        const blob = new Blob([data], {type:'application/octet-stream;charset=utf-8'})
        // 下载文件名称
        const fileName = row.fileName
        // a标签下载
        const linkNode = document.createElement('a')
        linkNode.download = fileName // a标签的download属性规定下载文件的名称
        linkNode.style.display = 'none'
        linkNode.href = URL.createObjectURL(blob) // 生成一个Blob URL
        document.body.appendChild(linkNode)
        linkNode.click() // 模拟在按钮上的一次鼠标单击
        URL.revokeObjectURL(linkNode.href) // 释放URL 对象
        document.body.removeChild(linkNode)
      })
    },
    removeFile(row){
      this.$confirm('确定要删除此文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteQuotationFile(row).then(({data}) => {
          if (data && data.code === 0) {
            this.getFileContentList()
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      }).catch(() => {
      })
    },
    previewFile(row){
      // 预览文件
      let image = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
      let type = '';
      if (image.includes(row.fileType.toLowerCase())){
        type = 'image/' + row.fileType;
      }
      let video = ['mp4', 'avi', 'mov', 'wmv', 'flv'];
      if (video.includes(row.fileType.toLowerCase())){
        type = 'video/' + row.fileType;
      }

      let txt = ['txt'];
      if (txt.includes(row.fileType.toLowerCase())){
        type = 'text/plain';
      }
      let office = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'];
      if (office.includes(row.fileType.toLowerCase())){
        // if (row.fileType.toLowerCase() === 'doc' || row.fileType.toLowerCase() === 'docx'){
        //   type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        // } else if (row.fileType.toLowerCase() === 'ppt' || row.fileType.toLowerCase() === 'pptx'){
        //   type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        // } else {
        //   type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        // }
        this.$message.warning(`该文件格式暂不支持预览`)
        return
      }

      let pdf = ['pdf'];
      if (pdf.includes(row.fileType.toLowerCase())){
        type = 'application/pdf';
      }

      if (type === ''){
        this.$message.warning(`该文件格式暂不支持预览`)
        return;
      }
      downLoadQuotationFile(row).then(({data}) => {
        const blob = new Blob([data], { type: type });
        // 创建URL来生成预览
        const fileURL = URL.createObjectURL(blob);
        // 在新标签页中打开文件预览
        const newTab = window.open(fileURL, '_blank');
      });
    },
    downloadBtn(){
      if (this.selectionFile.length < 1){
        this.$message.warning('请选择需要下载的文件')
        return
      }
      for (let i = 0; i < this.selectionFile.length; i++) {
        this.downloadFile(this.selectionFile[i])
      }
    },
    handleSelectionChange(val){
      this.selectionFile = val
    }
  },
  watch:{
    uploadDialog(newValue,oldValue){
      if (newValue === false){
        this.getFileContentList();
      }
    },
    testNo(newValue,oldValue){
      if (newValue){
        this.getFileContentList();
      }
    },
  }
}
</script>

<template>
<div>
  <div style="margin: 5px 0px">
    <el-button type="primary" @click="uploadDialog = true">上传文件</el-button>
    <el-button type="primary" @click="downloadBtn" >下载</el-button>
  </div>
  <el-table
    :height="height"
    :data="dataList"
    border
    @selection-change="handleSelectionChange"
    style="width: 100%">
    <el-table-column type="selection" label="序号" align="center"/>
    <el-table-column
      v-for="(item,index) in columnList" :key="index"
      :sortable="item.columnSortable"
      :prop="item.columnProp"
      :header-align="item.headerAlign"
      :show-overflow-tooltip="item.showOverflowTooltip"
      :align="item.align"
      :fixed="item.fixed===''?false:item.fixed"
      :min-width="item.columnWidth"
      :label="item.columnLabel">
      <template slot-scope="scope">
        <span v-if="!item.columnHidden">{{scope.row[item.columnProp]}}</span>
        <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
      </template>
    </el-table-column>
    <el-table-column
      fixed="right"
      header-align="center"
      align="center"
      width="120"
      label="操作">
      <template slot-scope="{row,$index}">
<!--        <el-link style="cursor:pointer;" @click="downloadFile(row)">下载</el-link>-->
        <el-link style="cursor:pointer;" @click="removeFile(row)">删除</el-link>
        <el-link style="cursor:pointer;" @click="previewFile(row)">预览</el-link>
      </template>
    </el-table-column>
  </el-table>
  <upload-file-list folder="testFile"  :label="'测试单号:'" :file-list.sync="fileList" :no="testNo" :upload-dialog.sync="uploadDialog" path="/upload/test"></upload-file-list>
</div>
</template>

<style scoped>

</style>
