<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">物料编号:</span>
        <el-select v-model="stationNumberValue" placeholder="请选择物料" filterable clearable remote :remote-method="getStationNumber" size="small" style="width: 250px" @change="queryitem" >
          <el-option
            v-for="item in stationNumber"
            :key="item.物料编码"
            :label="item.物料编码"
            :value="item.物料编码"
            size="mini">
          </el-option>
        </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(val = 2)" style="width: 100px;">工艺图</el-button>
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="uploadShowPDF(val = 0)" style="width: 155px;">选零件上传工艺图</el-button>
        <!-- <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="uploadShowPDF(val = 0)" style="width: 155px;">选订单上传工艺图</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: 90%"
          border
          size="mini"
          @row-click="handleRowClick"
        >
          <el-table-column label="序号" type="index" align="center" width="80"/>
          <el-table-column prop="num" label="物料编号" align="center" width="200"/>
          <el-table-column prop="物料描述" label="物料名称" align="center" width="250"/>
          <el-table-column prop="name" label="文件名称" align="center" width="100"/>
          <el-table-column prop="worker" label="导入人" align="center" width="100"/>
          <el-table-column prop="uploadTime" label="导入时间" align="center" width="150"/>
          <el-table-column label="操作" align="center" width="250">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-view" size="mini" @click="imgCheckDirectFile(scope.row)" >查看</el-button>
              <el-button type="text" icon="el-icon-delete" size="mini" style="color: #ff0000" @click="deleteImgCheckDirectFileSubmit(scope.row)" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!--上传文件-->
    <el-dialog  :visible.sync="imgDialogFormVisible" title="上传指导文件" center style="height: 800px" width="460px">
      <span v-if="itemupload"  style="margin-left: 10px">物料编号:</span>
      <span v-if="orderupload" style="margin-left: 10px">生产订单:</span>
      <el-select v-if="itemupload" v-model="uploadValue" placeholder="请选择" filterable clearable remote :remote-method="getStationNumber"  size="small" style="width: 250px; margin-bottom: 20px;" >
        <el-option
          v-for="item in tabledata2"
          :key="item.物料编码"
          :label="item.物料编码"
          :value="item.物料编码"
          size="mini"/>
      </el-select>
      <el-select v-if="orderupload" v-model="uploadValue" placeholder="请选择" filterable clearable remote :remote-method="getStationNumber"  size="small" style="width: 250px; margin-bottom: 20px;" >
        <el-option
          v-for="item in tabledata3"
          :key="item.物料编码"
          :label="item.物料编码"
          :value="item.物料编码"
          size="mini">
          <b style="float: left">{{ item.订单编号 }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.物料描述 }}</b>
        </el-option>
      </el-select>
      <el-upload
        ref="uploadPDF"
        :multiple="true"
        :auto-upload="false"
        :on-success="uploadSuccessPDF"
        :before-upload="beforeUploadPdf"
        :on-exceed="warningExceedPdf"
        :limit="limit"
        :data="DataPDF"
        :on-change="handleChange"
        :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 { MESUploadFile } from '@/utils/request'
import { MESDownFile } from '@/utils/request'
export default {
  data() {
    return {
      imgDialogFormVisible: false,
      imgDialogObj: '', // 点检类型对象
      stationNumberValue: '', // 点检指导文件选择的工位号
      engineType: [], // 点检机型类型
      engineTypeValue: '', // 点检机型类型
      imgCheckDialogFormVisible: false, // 查看点检文件
      stationNumber: [],
      stationName: '',
      limit: 1,
      DataPDF: {},
      uploadPDF: MESUploadFile,
      downPDF:MESDownFile,
      imgCheckDirectFileList: [],
      dialogFormVisible: false,
      selectedRow:{},
      itemupload:false,
      orderupload:false,
      tabledata2:[],
      tabledata3:[],
      uploadValue:'',
      currentTime:'',
      Uploaddirectly:false,
      filename:'',
    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    // this.searchTable()
    this.getStationNumber()
    this.getCurrentTime()
    this.getStationNumber()
    this.getImgCheckDirectFileList()
  },
  methods: {
    queryitem(){
      console.log(this.stationNumberValue)
    },
    getCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleRowClick(row) {
      this.selectedRow = row
    },
    searchTable(){
      var param = []
      this.imgCheckDirectFileList = []
      param[0] = ['零件图号_check', 0]
      param[1] = ['零件图号','']
      var Data = this.CreateData('11', '工艺管理_工艺维护_工艺图查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          this.imgCheckDirectFileList = response.data
        }
      })
    },
    getStationNumber(query='') {
      this.stationNumber = []
      var param = []
      param.push(["过滤",query])
      var Data = this.CreateData('11', '工艺管理_图纸维护_物料查询',param)
      this.ExecDatabase(Data).then(response => {
          this.stationNumber = response.data
          this.tabledata2 = response.data
          this.tabledata3 = response.data
      })
    },
    // 表格颜色变化
    tableRowClassName({ row, rowIndex }) {
      // console.log(row, rowIndex)
      if (rowIndex % 2 === 0) {
        return 'black'
      } else {
        return 'red'
      }
    },
    // 上传成功回调
    uploadSuccessPDF(res) {
      this.dialogFormVisible = false
      this.$refs.uploadPDF.clearFiles()
      this.$message.success('指导文件上传成功!')
      this.searchTable()
    },
    handleChange(file){
      const filename = file.name
      const lastIndex = filename.lastIndexOf('.');
      const name = filename.substring(0, lastIndex); // 结果: "1.2.3"
      const target = name
      this.filename = target
      if(this.Uploaddirectly){
        var param = []
        param[0] = ['零件图号',target]
        var Data = this.CreateData('11', '工艺管理_工艺维护_验证名称', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data.length == 0 ) {
            this.imgDialogFormVisible = false
            this.$message.error(`不存在物料编号'${target}'`)
            this.$refs.uploadPDF.clearFiles()
          }
        })
      }
      const exists2 = this.imgCheckDirectFileList.some(item => item["num"] === target);
      if(exists2){
        this.imgDialogFormVisible = false
        this.$message.error(`图纸上传重复，请先删除'${target}'`)
        this.$refs.uploadPDF.clearFiles()
      }
      const exists3 = this.imgCheckDirectFileList.some(item => item["name"] === target);
      if(exists3){
        this.imgDialogFormVisible = false
        this.$message.error(`图纸上传重复，请先删除'${target}'`)
        this.$refs.uploadPDF.clearFiles()
      }
    },
    // 上传前检测
    beforeUploadPdf(file) {
      let isJPG = /(\.|\/)(pdf)$/.test(file.type)
      if (!isJPG) {
        this.$message.error('只能上传PDF')
      }
      // if(!this.stationNumberValue){
      //   this.$message.error('请选择物料编号')
      //   isJPG = false
      // }
      return isJPG
    },
    warningExceedPdf() {
      this.$message.error('仅可上传一份PDF指导文件')
    },
    // 预览指导文件按钮
    imgCheckDirectFile(row) {
      var param = []
      console.log(row)
      param[0] = ['物料编号',row.num]
      var Data = this.CreateData('11', '工艺管理_工艺维护_查看图纸', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response)
        if (response.data.length > 0) {
          var pdfSrc =""+this.downPDF+""+ response.data[0].uid+".pdf"
          console.log(this.downPDF)
          console.log(response.data[0].uid)
          console.log(pdfSrc)
          window.open(pdfSrc,'_blank')
        }
      })
    },
    // 删除指导文件
    deleteImgCheckDirectFileSubmit(row) {
      this.$confirm('此操作将永久删除该指导文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['物料编号', row.num]
        var Data = this.CreateData('12', '工艺管理_工艺维护_删除图纸', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('删除指导文件成功！')
            this.searchTable()
          } else {
            this.$message.error('删除指导文件失败！')
          }
        })
      }).catch(() => {
      })
    },
    // 添加指导文件
    uploadShowPDF(val) {
      if(val==1){
        this.itemupload = false
        this.Uploaddirectly = false
      }else if(val==0){
        this.itemupload = true
        this.Uploaddirectly = false
      }else if(val==2){
        this.Uploaddirectly = true
        this.itemupload = false
      }
      this.imgDialogFormVisible = true
    },
    // 保存文件
    // submitPicturePDF() {
    //   if(!this.uploadValue & this.Uploaddirectly == false){
    //     return this.$message.error('请先选择物料')
    //   }
    //   if(this.Uploaddirectly == true){
    //     this.uploadValue = this.filename
    //   }
    //   var param = []
    //   param[0] = ['物料编号',this.uploadValue]
    //   var Data = this.CreateData('11', '工艺管理_图纸维护_查看图纸', param)
    //   this.ExecDatabase(Data).then(response => {
    //     if(response.data.length == 0){
    //       this.DataPDF = {
    //         num: this.uploadValue,
    //         // num:'a123',
    //         tableName: "物料基础数据_零件图纸",
    //         worker:this.$store.state.user.name,
    //         uploadTime:this.currentTime
    //       }
    //       console.log(JSON.stringify(this.DataPDF))
    //       this.$refs.uploadPDF.submit()
    //       this.imgDialogFormVisible = false
    //     }else{
    //       this.$refs.uploadPDF.clearFiles()
    //       this.imgDialogFormVisible = false
    //       this.$message.error('图纸上传重复，请先删除')
    //     }

    //   })

    // },
    // 保存文件
    submitPicturePDF() {
      if(!this.uploadValue & this.Uploaddirectly == false){
        return this.$message.error('请先选择物料')
      }
      if(this.Uploaddirectly == true){
        this.uploadValue = this.filename
      }

      var param = []
      param[0] = ['物料编号',this.uploadValue]
      var Data = this.CreateData('11', '工艺管理_工艺维护_查看图纸', param)
      this.ExecDatabase(Data).then(response => {
        if(response.data.length == 0){
          // 修改这里：确保参数名与后台一致
          this.DataPDF.params = JSON.stringify({
            num: this.uploadValue,  // 取消注释，使用实际值
            tableName: '物料基础数据_工艺图纸',
            worker: this.$store.state.user.name,  // 取消注释
            uploadTime: this.currentTime, // 取消注释
            department:this.$store.state.user.name,
          })
          console.log('上传参数:', JSON.stringify(this.DataPDF))
          this.$refs.uploadPDF.submit()
          this.imgDialogFormVisible = false
        }else{
          this.$refs.uploadPDF.clearFiles()
          this.imgDialogFormVisible = false
          this.$message.error('图纸上传重复，请先删除')
        }
      })
    },
    // 查询指导文件列表
    getImgCheckDirectFileList() {
      var param = []
      this.imgCheckDirectFileList = []
      if (!this.stationNumberValue) {
        param[0] = ['零件图号_check', 0]
        param[1] = ['零件图号','']
        var Data = this.CreateData('11', '工艺管理_工艺维护_工艺图查询', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data.length > 0) {
            this.imgCheckDirectFileList = response.data
          } else {
            this.$message.error('该工位无此点检指导文件，请添加后查看')
          }
        })
      }else{
        param[0] = ['零件图号_check', 1]
        param[1] = ['零件图号',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;
 }
}

.el-upload-dragger{
  width: 210px;
//right: 30px;
}
</style>

