<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">工位号：</span>
        <el-select v-model="stationNumberValue" placeholder="请选择工位号" size="small" style="width: 250px" @change="getImgCheckDirectFileList">
          <el-option
            v-for="item in stationNumber"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <el-button type="primary" plain size="small" icon="el-icon-order" @click="getImgCheckDirectFileList">查询</el-button>
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="uploadShowPDF()">上传</el-button>
      </div>
      <div class="main">
        <el-table
          ref="multipleTable"
          :data="imgCheckDirectFileList"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          :cell-class-name="tableRowClassName"
          element-loading-text="数据加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.2)"
          class="main"
          tooltip-effect="dark"
          height="640px"
          style="width: 70%"
          border
          size="mini"
        >
          <el-table-column
            label="排序"
            type="index"
            align="center"
            width="80"/>
          <el-table-column prop="文件名称" label="文件名称" align="center">
            <template slot-scope="scope2">
              {{ scope2.row.文件名称 }}.{{ scope2.row.文件后缀 }}
            </template>
          </el-table-column>
          <el-table-column prop="操作时间" label="导入时间" align="center" width="150">
            <template slot-scope="scope2">
              {{ scope2.row.操作时间 }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope2">
              <el-button type="text" icon="el-icon-view" size="mini" @click="imgCheckDirectFile(scope2.row)" >查看</el-button>
              <el-button type="text" icon="el-icon-download" size="mini" style="color: #67c23a" @click="downloadPDF(scope2.row)" >下载</el-button>
              <el-button type="text" icon="el-icon-delete" size="mini" style="color: #ff0000" @click="deleteImgCheckDirectFileSubmit(scope2.row)" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!--上传文件-->
    <el-dialog v-el-drag-dialog :visible.sync="imgDialogFormVisible" :close-on-click-modal="!uploading" title="上传指导文件" center style="height: 800px" width="460px">
      <el-upload
        ref="uploadPDF"
        :on-remove="handelLimitStyle"
        :on-change="handelLimit"
        :multiple="true"
        :auto-upload="false"
        :on-success="uploadSuccessPDF"
        :on-progress="handleProgress"
        :on-error="handleUploadError"
        :on-preview="handlePictureCardPreview"
        :before-upload="beforeUploadFile"
        :on-exceed="warningExceedFile"
        :limit="limit"
        :data="DataPDF"
        :action="uploadPDF"
        :disabled="uploading"
        accept=".pdf,.zip"
        style="margin-left: 30px"
        drag>
        <i class="el-icon-upload"/>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">只能上传一个pdf文件，且不超过100mb</div>
      </el-upload>
      <!-- 上传进度条 -->
      <div v-if="uploading" style="margin-top: 20px; padding: 0 30px;">
        <el-progress
          :percentage="uploadPercent"
          :status="uploadPercent === 100 ? 'success' : undefined"
          :stroke-width="18"
          :text-inside="true"
        />
        <div style="text-align: center; margin-top: 10px; color: #909399; font-size: 12px;">
          {{ uploadStatusText }}
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="uploading" @click="imgDialogFormVisible=false">取消</el-button>
        <el-button :loading="uploading" type="primary" style="width: 70px" @click="submitPicturePDF()">确定</el-button>
      </div>
    </el-dialog>
    <!--展示文件列表-->
    <el-dialog v-el-drag-dialog :visible.sync="imgCheckDialogFormVisible" title="查看指导文件" center style="height: 100%;overflow: auto" width="80%">
      <span style="margin-left: 10px">工位号：</span>
      <el-button type="text" size="mini" icon="el-icon-circle-check-outline" @click="getImgCheckDirectFileList">查看</el-button>
      <el-table
        :data="imgCheckDirectFileList"
        size="small"
        max-height="365px"
        style="width: 100%; height: 280px; font-size: 20px; color: #000; border: 1px solid #9e9b9b"
      >
        <el-table-column
          label="排序"
          type="index"
          align="center"
          width="100"/>
        <el-table-column prop="文件名称" label="文件名称" align="center">
          <template slot-scope="scope2">
            {{ scope2.row.文件名称 }}.{{ scope2.row.文件后缀 }}
          </template>
        </el-table-column>
        <el-table-column prop="上传时间" label="导入时间" align="center">
          <template slot-scope="scope2">
            {{ scope2.row.操作时间 }}
          </template>
        </el-table-column>
        <el-table-column label="查看文件" align="center" width="150">
          <template slot-scope="scope2">
            <el-button type="warning" @click="imgCheckDirectFile(scope2.row)" >打开指导文件</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope2">
            <el-button type="success" @click="downloadPDF(scope2.row)" >下载</el-button>
            <el-button type="warning" @click="deleteImgCheckDirectFileSubmit(scope2.row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="imgCheckDialogFormVisible=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { url } from '@/utils/request'
export default {
  data() {
    return {
      imgDialogFormVisible: false,
      imgDialogObj: '', // 点检类型对象
      stationNumberValue: '', // 点检指导文件选择的工位号
      engineType: [], // 点检机型类型
      engineTypeValue: '', // 点检机型类型
      imgCheckDialogFormVisible: false, // 查看点检文件
      stationNumber: [],
      stationName: '',
      limit: 1,
      DataPDF: {},
      uploadPDF: url,
      imgCheckDirectFileList: [],
      dialogFormVisible: false,
      // 上传进度相关
      uploading: false,
      uploadPercent: 0,
      uploadStatusText: '正在上传...'
    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    this.getStationNumber()
  },
  methods: {
    getEngineType() {
      this.engineType = []
      var param = []
      var Data = this.CreateData('11', 'MES_基本变量_机型代码_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) this.engineTypeValue = response.data[0].发动机机型标志
        for (let i = 0; i < response.data.length; i++) {
          this.engineType.push({
            label: response.data[i].发动机型号,
            value: response.data[i].发动机机型标志
          })
        }
        this.searchOrder()
      })
    },
    getStationNumber() {
      this.stationNumber = []
      var param = []
      var Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) this.stationNumberValue = response.data[0].工位号
        for (let i = 0; i < response.data.length; i++) {
          this.stationNumber.push({
            label: `【${response.data[i].工位号}】${response.data[i].工位名称}`,
            value: response.data[i].工位号,
            labelName: response.data[i].工位名称
          })
        }
      })
    },
    // 表格颜色变化
    tableRowClassName({ row, rowIndex }) {
      // console.log(row, rowIndex)
      if (rowIndex % 2 === 0) {
        return 'black'
      } else {
        return 'red'
      }
    },
    // 给样式的
    handelLimitStyle() {
    },
    handelLimit() {
    },
    // 上传成功回调
    uploadSuccessPDF(res) {
      this.uploading = false
      this.uploadPercent = 0
      this.uploadStatusText = '正在上传...'
      this.imgDialogFormVisible = false
      this.$refs.uploadPDF.clearFiles()
      this.$message.success('指导文件上传成功!')
      this.getImgCheckDirectFileList()
    },
    // 上传进度回调
    handleProgress(event, file, fileList) {
      this.uploading = true
      this.uploadPercent = Math.round(event.percent)
      if (this.uploadPercent < 100) {
        this.uploadStatusText = `正在上传: ${this.uploadPercent}%`
      } else {
        this.uploadStatusText = '文件已发送，等待服务器处理...'
      }
    },
    // 上传失败回调
    handleUploadError(err, file, fileList) {
      console.error('上传指导文件失败:', err)
      this.uploading = false
      this.uploadPercent = 0
      this.uploadStatusText = '正在上传...'
      this.$message.error('上传失败，请重试!')
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisiblePictureCard = true
    },
    // 上传前检测
    beforeUploadFile(file) {
      let isAllowFile = this.isAllowFile(file)
      if (!isAllowFile) {
        this.$message.error('只能上传PDF')
      }
      if (!this.stationNumberValue) {
        this.$message.error('请选择工位号')
        isAllowFile = false
      }
      return isAllowFile
    },
    isAllowFile(file) {
      const fileName = file.name ? file.name.toLowerCase() : ''
      return fileName.endsWith('.pdf') || fileName.endsWith('.zip')
    },
    warningExceedFile() {
      this.$message.error('仅可上传一份PDF指导文件')
    },
    // 预览指导文件按钮
    imgCheckDirectFile(row) {
      if (String(row.文件后缀).toLowerCase() === 'zip') {
        this.$message.warning('ZIP文件不支持在线预览，已为您下载')
        this.downloadPDF(row)
        return
      }
      var param = []
      param[0] = ['ID', row.ID]
      var Data = this.CreateData('11', '基础数据_操作指南指导文件_查看文件', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response)
        if (response.data.length > 0) {
          this.pdfSrc = this.solvePdfUr1(response.data[0].指导文件)
          window.open(this.pdfSrc, '_blank')
          // this.imgCheckDialogFormVisible = true // 查看点检文件
        } else {
          this.$message.error('该工位此点检项目无指导文件，请设置后查看')
        }
      })
    },
    // 下载PDF文件
    downloadPDF(row) {
      var param = []
      param[0] = ['ID', row.ID]
      var Data = this.CreateData('11', '基础数据_操作指南指导文件_查看文件', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          const content = response.data[0].指导文件
          const bstr = atob(content)
          let n = bstr.length
          const u8arr = new Uint8Array(n)
          while (n--) { u8arr[n] = bstr.charCodeAt(n) }
          const blob = new Blob([u8arr], { type: this.getFileMimeType(row.文件后缀) })
          // 创建下载链接
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = `${row.文件名称}.${row.文件后缀}`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(link.href)
          this.$message.success('文件下载成功！')
        } else {
          this.$message.error('该文件不存在')
        }
      })
    },
    // 处理pdf 二进制流
    solvePdfUr1(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)
    },
    getFileMimeType(fileSuffix) {
      const suffix = String(fileSuffix).toLowerCase()
      if (suffix === 'zip') {
        return 'application/zip'
      }
      return 'application/pdf'
    },
    callOff() {
      this.dialogFormVisible = false
      this.$refs['form'].resetFields()
    },
    // 删除指导文件
    deleteImgCheckDirectFileSubmit(row) {
      this.$confirm('此操作将永久删除该指导文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['ID', row.ID]
        var Data = this.CreateData('12', '基础数据_操作指南指导文件_删除', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('删除指导文件成功！')
            this.getImgCheckDirectFileList()
          } else {
            this.$message.error('删除指导文件失败！')
          }
        })
      }).catch(() => {
      })
    },
    // 添加指导文件
    uploadShowPDF(row) {
      this.imgDialogFormVisible = true
    },
    // 保存文件
    submitPicturePDF() {
      if (!this.stationNumberValue) {
        this.$message.error('请先选择工位号后提交!')
        return
      }
      // 检查是否选择了文件
      if (!this.$refs.uploadPDF.uploadFiles || this.$refs.uploadPDF.uploadFiles.length === 0) {
        this.$message.error('请先选择要上传的文件!')
        return
      }
      var param = []
      param[0] = ['工位号', this.stationNumberValue]
      param[1] = ['文件名称', '']
      param[2] = ['文件后缀', '']
      param[3] = ['文件内容', null]
      var Data1 = this.CreateData('15', '基础数据_操作指南指导文件_保存文件', param)
      this.DataPDF.param = Data1
      // 开始上传，显示进度条
      this.uploading = true
      this.uploadPercent = 0
      this.$refs.uploadPDF.submit()
      // 注意：不要在这里关闭弹窗！弹窗会在 uploadSuccessPDF 回调中关闭
    },
    // 查询指导文件列表
    getImgCheckDirectFileList() {
      if (!this.stationNumberValue) {
        this.$message.error('请选择工位号')
        return
      }
      var param = []
      this.imgCheckDirectFileList = []
      param[0] = ['工位号', this.stationNumberValue]
      var Data = this.CreateData('11', '基础数据_操作指南指导文件_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          this.imgCheckDirectFileList = response.data
        } else {
          this.$message.error('该工位无此点检指导文件，请添加后查看')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.NewlyAdded{
  background:rgb(253,246,236);
  border-color: #ff9759;
  color: #ff9759;
&:hover{
   background: #ff9759;
   border-color: #ff9759;
   color: white;
 }
&:focus{
   background: #ff9759;
   border-color: #ff9759;
   color: white;
 }
}
#dianjianbiao {
  /*.el-table td, .el-table th.is-leaf,.el-table--border, .el-table--group{*/
  /*border-color: black !important;*/
  /*}*/
  /*.el-table--border::after, .el-table--group::after, .el-table::before{*/
  /*background-color: black !important;*/
  /*}*/
  /*th {*/
  /*background: white !important;*/
  /*color: black !important;*/
  /*}*/
}
.el-upload-dragger{
  width: 210px;
//right: 30px;
}
</style>
