<template>
  <div>
    <el-card style="height: 867px">
      <el-col :span="6">
        <div style="width: 145px;display: inline-block">
          <el-input v-model="processFileName" placeholder="请输入文件名称" clearable/>
        </div>
        <el-button :disabled="loading" type="success" plain icon="el-icon-search" style="margin-left: 10px" @click="searchTable()">查询文件</el-button>
        <br>
        <el-upload
          ref="uploadStandFile"
          :on-remove="handleRemove"
          :before-upload="beforeAvatarUpload"
          :file-list="fileList"
          :auto-upload="false"
          :action="action"
          :data="Data"
          :limit="1"
          :on-success="stnFileSuccess"
          :on-error="stnFileError"
          accept=".png,.jpg,.jpeg,.pdf,.gif"
          class="upload-demo"
          style="margin-top: 10px">
          <el-button slot="trigger" plain type="primary" icon="el-icon-thumb">选取工艺文件</el-button>
          <el-button style="margin-left: 10px;" plain type="warning" icon="el-icon-upload2" @click="uploadStandFile">上传文件</el-button>
        </el-upload>
        <div style="margin-top: 10px">
          <el-table
            v-loading="loading"
            :data="tableData"
            :header-cell-style="{background:'#F5F5F5'}"
            element-loading-text="数据加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.2)"
            tooltip-effect="dark"
            style="width: 100%"
            height="740"
            border
            highlight-current-row
            stripe
            size="mini">
            <el-table-column
              type="index"
              width="50"/>
            <el-table-column align="left" label="文件名称" min-width="100">
              <template slot-scope="scope">
                {{ scope.row.fileName + '.' + scope.row.fileType }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="编辑" width="100">
              <template slot-scope="scope">
                <el-button type="text" size="mini" icon="el-icon-view" @click="lookFile(scope.row)"/>
                <el-button type="text" size="mini" icon="el-icon-download" style="color: #00893d" @click="downLoadFile(scope.row)"/>
                <el-button type="text" size="mini" icon="el-icon-delete" style="color: red" @click="deleteFile(scope.row)"/>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="18">
        <span v-if="fileName !== ''" style="font-size: 18px;font-weight: bolder">{{ fileName + '.' + fileType }}</span>
        <span v-else style="font-size: 18px;font-weight: bolder">请选择左侧文件进行预览</span>
        <div style="height: 814px;border: 1px solid #a1a1a1">
          <div v-show="fileContent !== ''">
            <el-image v-if="isImageType" :src="fileContentImg" lazy fit="fill"/>
            <div v-else-if="isPdfType">
              <iframe
                :src="fileContentPdf"
                width="100%"
                height="810px"/>
            </div>
            <div v-else class="noView">不支持的预览格式</div>
          </div>
        </div>
      </el-col>
    </el-card>
  </div>
</template>
<script>
import { action } from '@/utils/request'
import $ from 'jquery'

export default {
  // props: ['opname'],
  data() {
    return {
      opname: '',
      imageType: ['bmp', 'jpg', 'png', 'gif'],
      pdfType: ['pdf'],
      currentDownLoadUrl: '',
      fileName: '',
      fileType: '',
      fileContent: '',
      fileContentImg: null,
      fileContentPdf: null,
      isImageType: false,
      isPdfType: false,
      action: action,
      fileList: [],
      processFileName: '',
      opnames: [],
      opnameThis: '',
      opnameThisName: '',
      listOP: [],
      loading: false,
      tableData: [],
      Data: {},
      total: 0, // 总条数
      pageSize: 50, // 每页显示条数
      PageCurrent: 1 // 后台获取页
    }
  },
  computed: {},
  mounted() {
    // this.opnameThis = this.opname
    // this.searchTableOpName()
    // this.searchTable()
  },
  created() {
  },
  methods: {
    // 获取工位号
    searchTableOpName() {
      var param = []
      this.machineInfo_state = {}
      var Data = this.CreateData('11', '[AAA临工看板_主看板_查询数据]', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.opnames.push({
            label: response.data[i].工位号 + '-' + response.data[i].工位名称,
            value: response.data[i].工位号,
            id: response.data[i].id
          })
          if (response.data[i].工位号 === this.opnameThis) {
            this.opnameThisName = response.data[i].工位号 + '-' + response.data[i].工位名称
          }
        }
      })
    },
    // 查询文件列表
    searchTable() {
      this.loading = true
      this.tableData = []
      var param = []
      param[0] = ['opname', this.opnameThis]
      param[1] = ['fileName', this.processFileName]
      var Data = this.CreateData('11', 'LG_临工看板_工艺管理_工艺文件查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.tableData = response.data
        }
        this.loading = false
      })
    },
    searchTable1() {
    },
    // 预览文件
    lookFile(row) {
      this.fileName = row.fileName
      this.fileType = row.fileType.toLowerCase()
      this.fileContent = row.fileContent
      this.fileContentImg = ''
      this.fileContentPdf = ''
      if (this.imageType.indexOf(this.fileType) !== -1) {
        this.isImageType = true
        this.isPdfType = false
        this.fileContentImg = 'data:image/png;base64,' + this.fileContent
      } else if (this.pdfType.indexOf(this.fileType) !== -1) {
        this.isImageType = false
        this.isPdfType = true
        this.fileContentPdf = this.solvePdfUrl(this.fileContent, this.fileType, this.fileName)
      } else {
        this.isImageType = false
        this.isPdfType = false
      }
    },
    // 处理pdf
    solvePdfUrl(content, type, fileName) {
      const bstr = atob(content)
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) { u8arr[n] = bstr.charCodeAt(n) }
      // 确定解析格式，可能可以变成img，没有深入研究
      const blob = new Blob([u8arr], { type: 'application/pdf;chartset=UTF-8' })
      return window.URL.createObjectURL(blob)
    },
    // 下载文件
    downLoadFile(row) {
      let contentUrl = ''
      this.fileName = row.fileName
      this.fileType = row.fileType.toLowerCase()
      this.fileContent = row.fileContent
      this.fileContentImg = ''
      this.fileContentPdf = ''
      if (this.imageType.indexOf(this.fileType) !== -1) {
        this.isImageType = true
        this.isPdfType = false
        this.fileContentImg = 'data:image/png;base64,' + this.fileContent
        contentUrl = 'data:image/png;base64,' + this.fileContent
      } else if (this.pdfType.indexOf(this.fileType) !== -1) {
        this.isImageType = false
        this.isPdfType = true
        this.fileContentPdf = this.solvePdfUrl(this.fileContent, this.fileType, this.fileName)
        contentUrl = this.fileContentPdf
      } else {
        this.isImageType = false
        this.isPdfType = false
        this.$message.warning('不支持的下载格式！')
        return
      }
      var a = document.createElement('a')
      a.download = this.fileName + '.' + this.fileType
      a.href = contentUrl
      $('body').append(a)
      a.click()
      $(a).remove()
    },
    // 删除文件
    deleteFile(row) {
      this.$confirm('是否确认将文件进行删除' + '</div>', '提示', {
        distinguishCancelAndClose: true,
        center: true,
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(() => {
        var param = []
        param[0] = ['ID', row.ID]
        var Data = this.CreateData('11', 'LG_临工看板_工艺管理_工艺文件删除', param)
        this.ExecDatabase(Data).then(response => {
          this.$message.success('删除成功！')
          this.searchTable()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除！'
        })
      })
    },
    /**
       * 移除上传文件
       */
    handleRemove(file, fileList) {
      this.fileList = []
    },
    /**
       * 上传设备文件大小限制
       */
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传工艺文档大小不能超过 10MB!')
      }
      return isLt2M
    },
    /**
       * 上传标准文件
       */
    uploadStandFile() {
      if (this.$refs.uploadStandFile.uploadFiles.length === 0) {
        this.$message.warning('请选择文件进行上传！')
        return
      }
      var param = []
      param[0] = ['opName', this.opnameThis]
      param[1] = ['fileName', '']
      param[2] = ['fileType', '']
      param[3] = ['fileContent', null]
      this.Data.param = this.CreateData('15', 'LG_临工看板_工艺管理_工艺文件上传', param)
      this.$refs.uploadStandFile.submit()
    },
    /**
       * 上传标准设备文件成功后
       */
    stnFileSuccess(res, file) {
      this.$message.success('上传成功！')
      this.fileList = []
      this.searchTable()
    },
    stnFileError(err, file, fileList) {
      this.$message.success('上传失败，请重新上传！' + err.toString())
      this.fileList = []
    }
  }
}
</script>
<style scoped>
    .noView{
        font-size: 20px;
        text-align: center;
        line-height: 800px;
        color: #b8b5b5;
    }
</style>
