<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-order" @click="searchTable()">查询</el-button>
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="uploadShowPDF">上传</el-button>
      </div>
      <div>
        <el-col :span="8">
          <el-table
            ref="multipleTable"
            :data="tableData"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
            height="680px"
            class="main"
            tooltip-effect="dark"
            style="width: 100%"
            border
            size="mini">
            <el-table-column label="序号" type="index" align="center" />
            <el-table-column label="产品编号" align="center">
              <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="100">
              <template slot-scope="scope">
                <el-button type="text" @click="lookFile(scope.row)"><i class="el-icon-view"/></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="16">
          <span style="margin-left: 5px">产品编号：{{ fileName1 }}</span>
          <div style="margin-left: 5px">
            <iframe
              :src="fileContentPdf"
              width="98%"
              height="660px"/>
          </div>
        </el-col>
      </div>
    </el-card>
    <!--上传文件-->
    <el-dialog v-el-drag-dialog :visible.sync="imgDialogFormVisible" title="上传指导文件" center style="height: 800px" 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"
        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 slot="footer" class="dialog-footer">
        <el-button @click="imgDialogFormVisible=false">取消</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,
      imgDialogObj: '', // 点检类型对象
      imgDialogOpName: '', // 点检指导文件选择的工位号
      engineTypes: [], // 点检机型类型
      imgCheckDialogFormVisible: false, // 查看点检文件
      limit: 1,
      DataPDF: {},
      uploadPDF: url,
      imgCheckDirectFileList: [],
      tableData: [], // 总数据数组
      tableData1: [], // 总数据数组
      stationNumber: [],
      stationNumberValue: '',
      stationNumberValue1: '',
      opname: '',
      imageType: ['bmp', 'jpg', 'png', 'gif'],
      pdfType: ['pdf'],
      currentDownLoadUrl: '',
      fileName: '',
      fileName1: '',
      fileType: '',
      fileContent: '',
      fileContentImg: null,
      fileContentPdf: null,
      isImageType: false,
      isPdfType: false,
      fileList: [],
      stationName: '',
      moduleDescription: [],
      moduleDescriptionValue: '',
      engineTypeValue: '',
      engineTypeValue1: '',
      engineTypeName: '',
      engineType: [],

      isDisableValue: 0,
      labelText: '',
      labelNumber: '',
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible4: false,
      title: '',
      form: {
        stationNumber: '',
        ID: 0,
        类别: '',
        测试方法: '',
        检测要求: '',
        实测值: ''
      },
      rules: {
        stationNumber: [{ required: true, message: '请选择工位号', trigger: 'change' }],
        类别: [{ required: true, message: '请输入类别', trigger: 'blur' }],
        测试方法: [{ required: true, message: '请输入测试方法', trigger: 'blur' }],
        检测要求: [{ required: true, message: '请输入检测要求', trigger: 'blur' }],
        实测值: [{ required: true, message: '请输入实测值', trigger: 'blur' }]
      },
      form1: {
        number: '',
        text: '',
        work: '',
        fun: ''
      },
      rules1: {
        number: [{ required: true, message: '请输入序号', trigger: 'blur' }],
        text: [{ required: true, message: '请输入操作内容', trigger: 'blur' }]
      },
      form4: {
        engineTypeValue: '',
        stationNumberValue: ''
      },
      rules4: { // 订单下发验证
        engineTypeValue: [{ required: true, message: '请选择机型', trigger: 'blur' }],
        stationNumberValue: [{ required: true, message: '请选择工位号', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token',
      'departmentName'
    ])
  },
  watch: {
    // stationNumberValue() {
    //   for (let i = 0; i < this.stationNumber.length; i++) {
    //     if (this.stationNumber[i].value === this.stationNumberValue) {
    //       console.log(this.stationNumber[i].label, 'this.stationNumber[i].label')
    //       this.stationName = this.stationNumber[i].labelName
    //     }
    //   }
    //   if (!this.stationNumberValue) {
    //     this.stationName = ''
    //   }
    // },
    engineTypeValue1() {
      console.log(1234)
      for (let i = 0; i < this.engineType.length; i++) {
        if (this.engineType[i].value === this.engineTypeValue1) {
          this.engineTypeName = this.engineType[i].labelName
          console.log(this.engineTypeName, 'this.engineTypeName')
        }
      }
    }
  },
  created() {
    this.getStationNumber()
    this.getEndStation()
  },
  mounted() {
    this.searchTable()
  },
  methods: {
    getStationNumber() {
      this.stationNumber = []
      var param = []
      var Data = this.CreateData('11', 'CATL_随车卡_PDF_查询_初始化', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.stationNumber.push({
            label: response.data[i].产品编号,
            value: response.data[i].产品编号
          })
        }
      })
    },
    // 初始化获取产品型号
    getEndStation() {
      this.engineType = []
      var param = []
      var Data = this.CreateData('11', 'CATL_基础信息_机型信息_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) this.engineTypeValue = response.data[0].机型ID
        for (let i = 0; i < response.data.length; i++) {
          this.engineType.push({
            label: response.data[i].机型号,
            value: response.data[i].机型ID,
            labelName: response.data[i].机型号
          })
        }
      })
    },
    // 表格颜色变化
    tableRowClassName({ row, rowIndex }) {
      // console.log(row, rowIndex)
      if (rowIndex % 2 === 0) {
        return 'black'
      } else {
        return 'red'
      }
    },
    // 查询MES消息
    searchTable() {
      this.tableData = []
      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
        }
      })
    },
    // 添加指导文件
    uploadShowPDF() {
      this.imgDialogFormVisible = true
    },
    // 上传成功回调
    uploadSuccessPDF(res) {
      this.dialogFormVisible = false
      this.$refs.uploadPDF.clearFiles()
      this.$message.success('指导文件上传成功!')
      this.searchTable()
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisiblePictureCard = true
    },
    // 上传前检测
    beforeUploadPdf(file) {
      let isJPG = /(\.|\/)(pdf)$/.test(file.type)
      if (!isJPG) {
        this.$message.error('只能上传PDF')
      }
      if (this.stationNumberValue1 === '') {
        this.$message.error('请选择工位号')
        isJPG = false
      }
      return isJPG
    },
    warningExceedPdf() {
      this.$message.error('仅可上传一份PDF指导文件')
    },
    // 保存文件
    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
    },
    // 预览指导文件按钮
    imgCheckDirectFile(row) {
      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 二进制流
    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)
    },
    searchTable1() {
      this.tableData1 = []
      var param = []
      var Data = this.CreateData('11', 'CATL_出厂报告_基础_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.tableData1 = response.data
          this.tableData1.push({
            数据名称: '',
            数据值: 'button'
          })
        }
      })
    },
    addTo() {
      this.title = '添加'
      this.dialogFormVisible = true
    },
    submitAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['工位号', this.form.stationNumber]
          param[1] = ['类别', this.form.类别]
          param[2] = ['测试方法', this.form.测试方法]
          param[3] = ['检测要求', this.form.检测要求]
          param[4] = ['实测值', this.form.实测值]
          var Data = this.CreateData('12', 'CATL_出厂报告_基础项目_增加', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              this.$message({
                message: '增加成功',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.searchTable()
            } else {
              this.$message.error('增加失败！')
            }
          })
        } else {
          return false
        }
      })
    },
    callOff() {
      this.dialogFormVisible = false
      this.$refs['form'].resetFields()
      this.form.stationNumber = ''
      this.form.moduleDescription = ''
      this.form.number = ''
      this.form.text = ''
      this.engineTypeName = ''
      this.title = ''
    },
    callOff1() {
      this.dialogFormVisible1 = false
      this.$refs['form1'].resetFields()
      this.form.stationNumber = ''
      this.form.moduleDescription = ''
      this.form.number = ''
      this.form.text = ''
      this.engineTypeName = ''
      this.title = ''
    },
    editInformation(row) {

    },
    // 编辑消息
    submitUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['类别', this.form.类别]
          param[1] = ['测试方法', this.form.测试方法]
          param[2] = ['检测要求', this.form.检测要求]
          param[3] = ['实测值', this.form.实测值]
          param[4] = ['ID', this.form.ID]
          var Data = this.CreateData('12', 'CATL_出厂报告_基础项目_编辑', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.searchTable()
            } else {
              this.$message.error('修改失败！')
            }
          })
        } else {
          return false
        }
      })
    },
    deleteInformation(row) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['ID', row.ID]
        var Data = this.CreateData('12', 'CATL_出厂报告_基础项目_删除', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.searchTable()
          } else {
            this.$message.error('删除失败！')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitUpdate1() {
      const value1 = this.tableData1[0].数据值
      const value2 = this.tableData1[1].数据值
      const value3 = this.tableData1[2].数据值
      const value4 = this.tableData1[3].数据值
      var param = []
      param[0] = ['数据值1', value1]
      param[1] = ['数据值2', value2]
      param[2] = ['数据值3', value3]
      param[3] = ['数据值4', value4]
      var Data = this.CreateData('12', 'CATL_出厂报告_基础_编辑', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.searchTable1()
        } else {
          this.$message.error('修改失败！')
        }
      })
    },
    // 预览文件
    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/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()
    }
  }
}
</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>

