<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">产品编号：</span>
        <el-input v-model="stationNumberValue" clearable size="mini" style="width: 200px" placeholder="请输入产品编号" />
        <el-button type="primary" plain size="small" icon="el-icon-search" @click="searchTable()">查询</el-button>
        <el-button type="distribution" icon="el-icon-circle-plus-outline" size="small" @click="uploadShowPDF">上传</el-button>
      </div>
      <div>
        <!-- 左侧产品列表 -->
        <el-col :span="6">
          <el-table
            ref="multipleTable"
            :data="tableData"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
            height="680px"
            highlight-current-row
            @current-change="handleCurrentChange"
            class="main"
            tooltip-effect="dark"
            style="width: 100%"
            border
            size="mini">
            <el-table-column label="序号" type="index" align="center" width="50" />
            <el-table-column label="产品编号" align="center" prop="产品编号" />
            <el-table-column label="附件数量" align="center" width="80" prop="附件数量" />
          </el-table>
        </el-col>
        
        <!-- 中间附件列表 -->
        <el-col :span="7">
          <div style="margin-left: 10px; margin-bottom: 5px; font-weight: bold;">
            附件列表 <span v-if="currentProduct">（{{ currentProduct }}）</span>
          </div>
          <el-table
            :data="attachmentList"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
            height="655px"
            class="main"
            tooltip-effect="dark"
            style="width: 95%; margin-left: 10px;"
            border
            size="mini">
            <el-table-column label="附件名称" align="center">
              <template slot-scope="scope">
                {{ scope.row.附件名称 }}
              </template>
            </el-table-column>
            <el-table-column label="类型" align="center" width="60">
              <template slot-scope="scope">
                {{ scope.row.附件类型 }}
              </template>
            </el-table-column>
            <el-table-column label="上传时间" align="center" width="150">
              <template slot-scope="scope">
                {{ scope.row.操作时间 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="120">
              <template slot-scope="scope">
                <el-button type="text" @click="lookFile(scope.row)"><i class="el-icon-view"/></el-button>
                <el-button type="text" @click="downLoadFile(scope.row)"><i class="el-icon-download"/></el-button>
                <el-button type="text" style="color: #f56c6c;" @click="deleteFile(scope.row)"><i class="el-icon-delete"/></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        
        <!-- 右侧预览区域 -->
        <el-col :span="11">
          <div style="margin-left: 10px; margin-bottom: 5px;">
            <span style="font-weight: bold;">文件预览</span>
            <span v-if="fileName1"> - {{ fileName1 }}</span>
          </div>
          <div style="margin-left: 10px; border: 1px solid #ebeef5; height: 655px; overflow: auto;">
            <!-- PDF预览 -->
            <iframe
              v-if="isPdfType"
              :src="fileContentPdf"
              width="100%"
              height="100%"/>
            <!-- 图片预览 -->
            <div v-else-if="isImageType" style="text-align: center; padding: 20px;">
              <img :src="fileContentImg" style="max-width: 100%; max-height: 600px;" />
            </div>
            <!-- 无预览内容 -->
            <div v-else style="text-align: center; padding-top: 300px; color: #909399;">
              <i class="el-icon-document" style="font-size: 48px;"></i>
              <p>请选择文件进行预览</p>
            </div>
          </div>
        </el-col>
      </div>
    </el-card>
    
    <!--上传文件对话框-->
    <el-dialog v-el-drag-dialog :visible.sync="imgDialogFormVisible" title="上传文件" center width="460px">
      <div style="margin-bottom: 5px;margin-left: 30px">
        <span>产品编号：</span>
        <el-input v-model="stationNumberValue1" size="mini" style="width: 200px" placeholder="请输入产品编号" />
      </div>
      <el-upload
        id="invoiceScan"
        ref="uploadPDF"
        :multiple="true"
        :auto-upload="false"
        :on-success="uploadSuccessPDF"
        :on-preview="handlePictureCardPreview"
        :before-upload="beforeUploadPdf"
        :on-exceed="warningExceedPdf"
        :limit="limit"
        :data="DataPDF"
        :action="uploadPDF"
        accept=".pdf,.jpg,.jpeg,.png,.gif,.bmp"
        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、jpg、png、gif、bmp等格式文件，单个文件不超过100MB</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUpload">取消</el-button>
        <el-button type="primary" style="width: 70px" @click="submitPicturePDF()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { url } from '@/utils/request'
import { mapGetters } from 'vuex'
import $ from 'jquery'
export default {
  data() {
    return {
      imgDialogFormVisible: false,
      limit: 5, // 支持多个文件
      DataPDF: {},
      uploadPDF: url,
      tableData: [], // 产品列表数据
      attachmentList: [], // 附件列表数组
      currentProduct: '', // 当前选中的产品编号
      stationNumberValue: '',
      stationNumberValue1: '',
      imageType: ['bmp', 'jpg', 'png', 'gif', 'jpeg'],
      pdfType: ['pdf'],
      fileName: '',
      fileName1: '',
      fileType: '',
      fileContent: '',
      fileContentImg: null,
      fileContentPdf: null,
      isImageType: false,
      isPdfType: false
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token',
      'departmentName'
    ])
  },
  created() {
  },
  mounted() {
    this.searchTable()
  },
  methods: {
    // 查询MES消息
    searchTable() {
      this.tableData = []
      this.attachmentList = []
      this.currentProduct = ''
      this.clearPreview()
      var param = []
      param[0] = ['产品编号', this.stationNumberValue]
      var Data = this.CreateData('11', 'CATL_随车卡_PDF_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.tableData = response.data
        }
      })
    },
    // 处理产品选择
    handleCurrentChange(currentRow) {
      if (currentRow) {
        this.currentProduct = currentRow.产品编号
        this.getAttachmentList(currentRow.产品编号)
      }
    },
    // 查询附件列表
    getAttachmentList(productNo) {
      this.attachmentList = []
      this.clearPreview()
      var param = []
      param[0] = ['产品编号', productNo]
      var Data = this.CreateData('11', 'CATL_随车卡_PDF_附件列表查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.attachmentList = response.data
        }
      })
    },
    // 清空预览
    clearPreview() {
      this.fileName = ''
      this.fileName1 = ''
      this.fileType = ''
      this.fileContent = ''
      this.fileContentImg = null
      this.fileContentPdf = null
      this.isImageType = false
      this.isPdfType = false
    },
    // 添加指导文件
    uploadShowPDF() {
      this.imgDialogFormVisible = true
    },
    // 上传成功回调
    uploadSuccessPDF(res) {
      this.imgDialogFormVisible = false
      this.$refs.uploadPDF.clearFiles()
      this.$message.success('文件上传成功!')
      this.searchTable()
      // 如果有选中的产品，刷新附件列表
      if (this.currentProduct) {
        this.getAttachmentList(this.currentProduct)
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisiblePictureCard = true
    },
    // 上传前检测
    beforeUploadPdf(file) {
      const fileName = file.name.toLowerCase()
      const fileExt = fileName.substring(fileName.lastIndexOf('.') + 1)
      const allowedTypes = ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp']
      
      if (!allowedTypes.includes(fileExt)) {
        this.$message.error('只能上传PDF或图片文件（jpg、png、gif、bmp）')
        return false
      }
      
      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isLt100M) {
        this.$message.error('文件大小不能超过 100MB!')
        return false
      }
      
      if (this.stationNumberValue1 === '') {
        this.$message.error('请输入产品编号')
        return false
      }
      
      return true
    },
    warningExceedPdf() {
      this.$message.error('最多可上传5个文件')
    },
    // 保存文件
    submitPicturePDF() {
      if (this.stationNumberValue1 === '') {
        this.$message.error('请输入产品编号!')
        return
      }
      var param = []
      param[0] = ['产品编号', this.stationNumberValue1]
      param[1] = ['说明', '']
      param[2] = ['文件名称', '']
      param[3] = ['文件后缀', '']
      param[4] = ['文件内容', null]
      var Data1 = this.CreateData('15', 'CATL_随车卡_PDF_增加', param)
      this.DataPDF.param = Data1
      this.$refs.uploadPDF.submit()
      this.imgDialogFormVisible = false
    },

    // 预览文件
    lookFile(row) {
      this.fileName1 = row.附件名称
      this.fileName = row.附件名称
      this.fileType = row.附件类型.toLowerCase()
      this.fileContent = row.附件内容
      this.fileContentImg = ''
      this.fileContentPdf = ''
      if (this.imageType.indexOf(this.fileType) !== -1) {
        this.isImageType = true
        this.isPdfType = false
        this.fileContentImg = 'data:image/' + this.fileType + ';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
        this.$message.warning('不支持的文件格式！')
      }
    },
    // 处理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.附件名称
      this.fileType = row.附件类型.toLowerCase()
      this.fileContent = row.附件内容
      if (this.imageType.indexOf(this.fileType) !== -1) {
        contentUrl = 'data:image/' + this.fileType + ';base64,' + this.fileContent
      } else if (this.pdfType.indexOf(this.fileType) !== -1) {
        contentUrl = this.solvePdfUrl(this.fileContent, this.fileType, this.fileName)
      } else {
        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()
    },
    // 取消上传
    cancelUpload() {
      this.imgDialogFormVisible = false
      this.$refs.uploadPDF.clearFiles()
      this.stationNumberValue1 = ''
    },
    // 删除文件
    deleteFile(row) {
      this.$confirm('此操作将永久删除该附件，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['id', row.id]
        var Data = this.CreateData('12', 'CATL_随车卡_PDF_删除', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            // 刷新附件列表
            if (this.currentProduct) {
              this.getAttachmentList(this.currentProduct)
            }
            // 刷新产品列表
            this.searchTable()
            // 清空预览
            this.clearPreview()
          } else {
            this.$message.error('删除失败！')
          }
        }).catch(error => {
          this.$message.error('删除失败！')
          console.error(error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped>
.topCard {
  margin: 5px;
}

.topDiv {
  margin-bottom: 10px;
}

.el-select {
  width: 200px
}

.el-input {
  width: 200px
}

.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  position: absolute;
  right: 6px;
  top: 80px;
  width: 300px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

::v-deep.el-input.is-disabled .el-input__inner {
  color: #606266 !important;
}

::v-deep textarea {
  height: 100px;
}
</style>

