<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">物料编码:</span>
        <!-- 查询用的多选 -->
        <el-select 
          v-model="stationNumberValues" 
          filterable
          clearable
          remote
          :remote-method="getStationNumber"
          size="small" 
          style="width: 400px" 
          collapse-tags
        >
          <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('part')" style="width: 100px;">零件图</el-button>
        
        <!-- 选零件上传零件图按钮 - 改为多选上传 -->
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="uploadShowPDF('multi')" style="width: 155px;">选零件上传零件图</el-button>
        
        <el-button type="warning" icon="el-icon-document-delete" size="small" @click="showDeleteRecords" style="width: 140px;">查看删除记录</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)" v-if="uesrname == scope.row.worker">查看</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="partDialogVisible" title="上传零件图" center style="height: 800px" width="700px">
      <el-upload
        ref="partUpload"
        :multiple="true"
        :auto-upload="false"
        :on-success="uploadSuccessPDF"
        :before-upload="beforeUploadPdf"
        :on-exceed="warningExceedPdf"
        :limit="limit"
        :data="partDataPDF"
        :on-change="handlePartChange"
        :action="uploadPDF"
        accept=".pdf"
        style="margin-left: 130px"
        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="partDialogVisible=false">取消</el-button>
        <el-button type="primary" style="width: 70px" @click="submitPartPDF()">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- 选零件上传零件图弹窗 - 支持多选 -->
    <el-dialog :visible.sync="multiDialogVisible" title="选零件上传零件图" center style="height: 800px" width="700px">
      <div style="margin-bottom: 20px; padding: 0 20px;">
        <span style="margin-left: 10px">物料编码:</span>
        <el-select 
          v-model="selectedMaterials" 
          multiple
          filterable 
          clearable 
          remote 
          :remote-method="getStationNumber" 
          size="small" 
          style="width: 500px" 
          placeholder="请选择物料(可多选)"
          collapse-tags
        >
          <el-option
            v-for="item in materialOptions"
            :key="item.物料编码"
            :label="item.物料编码"
            :value="item.物料编码"
            size="mini"/>
        </el-select>
      </div>

      <el-upload
        ref="multiUpload"
        :multiple="true"
        :auto-upload="false"
        :on-success="uploadSuccessPDF"
        :before-upload="beforeUploadPdf"
        :on-exceed="warningExceedPdf"
        :limit="limit"
        :data="multiDataPDF"
        :on-change="handleMultiChange"
        :action="uploadPDF"
        accept=".pdf"
        style="margin-left: 130px"
        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="uploadingProgress.show" style="margin-top: 20px; padding: 0 20px;">
        <el-progress :percentage="uploadingProgress.percentage" :status="uploadingProgress.status"></el-progress>
        <p style="text-align: center; margin-top: 10px;">{{ uploadingProgress.message }}</p>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelMultiUpload">取消</el-button>
        <el-button type="primary" style="width: 70px" @click="submitMultiPDF()" :loading="uploading">确定</el-button>
      </div>
    </el-dialog>
    
    <el-dialog :visible.sync="deleteRecordsVisible" title="删除记录" center width="1200px">
      <div class="topDiv">
        <span style="margin-left: 10px">物料编码:</span>
        <el-select v-model="itemnum" placeholder="请选择物料" filterable clearable remote :remote-method="getStationNumber" size="small" style="width: 250px" >
          <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="getDeleteRecords">查询</el-button>
      </div>
      <el-table
        :data="deleteRecordsList"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        element-loading-text="数据加载中"
        border
        size="mini"
        height="500px"
      >
        <el-table-column label="序号" type="index" align="center" width="80"/>
        <el-table-column prop="物料编号" label="物料编号" align="center" width="200"/>
        <el-table-column prop="文件名称" label="文件名称" align="center" width="250"/>
        <el-table-column prop="操作人" label="操作人" align="center" width="150"/>
        <el-table-column prop="删除时间" label="删除时间" align="center" width="200"/>
        <el-table-column prop="备注" label="备注" align="center" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteRecordsVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    
    <!-- 冲突提示对话框 -->
    <el-dialog :visible.sync="conflictDialog.visible" title="上传冲突提示" width="600px">
      <div style="padding: 20px;">
        <el-alert
          title="以下物料已有图纸，无法上传"
          type="warning"
          :closable="false"
          show-icon>
        </el-alert>
        <el-table :data="conflictDialog.items" border size="mini" style="margin-top: 20px;">
          <el-table-column prop="物料编码" label="物料编码" width="180"></el-table-column>
          <el-table-column prop="导入人" label="现有图纸导入人" width="150"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="showContactInfo(scope.row)">查看信息</el-button>
            </template>
          </el-table-column>
        </el-table>
        <p style="margin-top: 20px; color: #666;">请联系以上导入人删除图纸后，再重新上传</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="conflictDialog.visible = false">关 闭</el-button>
      </div>
    </el-dialog>
    
    <el-dialog :visible.sync="seeVisible" title="图纸" center width="1200px" overflow="scroll" >
      <div id="el-dialog__body" style="min-height: 500px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="seeVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { MESUploadFile } from '@/utils/request'
import { MESDownFile } from '@/utils/request'
import { seepdf, initPDFKeyboardShortcuts, setZoom } from '@/utils/pdf';
export default {
  data() {
    return {
      // 原零件图相关 - 保持原功能
      partDialogVisible: false,
      partDataPDF: {},
      
      // 多选上传相关
      multiDialogVisible: false,
      selectedMaterials: [], // 选择的物料列表
      materialOptions: [], // 物料选项
      multiDataPDF: {},
      
      // 原变量 - 保持兼容
      imgDialogFormVisible: false,
      imgDialogObj: '', // 点检类型对象
      stationNumberValue: '', // 单选用（保留原变量）
      stationNumberValues: [], // 查询用多选
      itemnum:'',
      engineType: [], // 点检机型类型
      engineTypeValue: '', // 点检机型类型
      imgCheckDialogFormVisible: false, // 查看点检文件
      stationNumber: [],
      stationName: '',
      limit: 1,
      DataPDF: {},
      uploadPDF: MESUploadFile,
      downPDF:MESDownFile,
      imgCheckDirectFileList: [],
      dialogFormVisible: false,
      selectedRow:{},
      itemupload:false,
      tabledata2:[],
      tabledata3:[],
      uploadValue:'', // 单选用
      uploadValues: [], // 改为数组，支持多选
      currentTime:'',
      Uploaddirectly:false,
      filename:'',
      deleteRecordsVisible: false, // 删除记录弹窗显示状态
      deleteRecordsList: [], // 删除记录列表
      toolbarConfig:{
        // 隐藏下载按钮
        download: false,
        
        // 或完全移除下载按钮
        toolbar: {
          toolbarViewer: {
            download: false,  // 隐藏下载按钮
            openFile: false,  // 隐藏打开文件按钮（可选）
            print: false,     // 隐藏打印按钮（可选）
          }
        }
      },
      seeVisible:false,
      uesrname:'',
      // 上传进度相关
      uploading: false,
      uploadingProgress: {
        show: false,
        percentage: 0,
        status: '',
        message: ''
      },
      // 冲突对话框
      conflictDialog: {
        visible: false,
        items: []
      },
      // 成功上传的物料列表
      successItems: [],
      // 失败物料列表
      failItems: []
    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    this.searchTable()
    this.getStationNumber()
    this.getCurrentTime()
    this.getImgCheckDirectFileList()
    this.uesrname = this.$store.state.user.name
    setInterval(this.getCurrentTime, 1000);
  }, 
  // mounted(){
  //   initPDFKeyboardShortcuts()
  // },
  methods: {
    
    showDeleteRecords() {
      this.deleteRecordsVisible = true
      this.getDeleteRecords()
    },
    
    // 获取删除记录
    getDeleteRecords() {
      var params = []
      params.push (['物料编码',this.itemnum])
      var Data = this.CreateData('11', '工艺管理_图纸维护_查询删除记录', params)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.deleteRecordsList = response.data
        } else {
          this.deleteRecordsList = []
          this.$message.info('暂无删除记录')
        }
      }).catch(error => {
        console.error('获取删除记录失败:', error)
        this.$message.error('获取删除记录失败')
      })
    },
    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] = ['零件图号','']
      param[2] = ['导入人',this.$store.state.user.name]
      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
          this.materialOptions = response.data // 多选用
      })
    },
    // 表格颜色变化
    tableRowClassName({ row, rowIndex }) {
      // console.log(row, rowIndex)
      if (rowIndex % 2 === 0) {
        return 'black'
      } else {
        return 'red'
      }
    },
    // 上传成功回调
    uploadSuccessPDF(res) {
      // 这个回调会在每个文件上传成功后触发
      // 我们使用批量处理，所以这里不做处理
    },
    
    // 零件图按钮的文件变化处理 - 保持原功能
    handlePartChange(file) {
      const filename = file.name
      const lastIndex = filename.lastIndexOf('.');
      const name = filename.substring(0, lastIndex);
      
      // 验证文件名对应的物料是否存在
      var param = []
      param[0] = ['零件图号', name]
      var Data = this.CreateData('11', '工艺管理_图纸维护_验证名称', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length == 0) {
          this.partDialogVisible = false
          this.$message.error(`不存在物料编号'${name}'`)
          this.$refs.partUpload.clearFiles()
        }
      })
      
      // 检查是否重复上传
      const exists = this.imgCheckDirectFileList.some(item => item["num"] === name);
      if (exists) {
        this.partDialogVisible = false
        this.$message.error(`图纸上传重复，请先删除'${name}'`)
        this.$refs.partUpload.clearFiles()
      }
    },
    
    // 多选上传的文件变化处理
    handleMultiChange(file) {
      // 只做基本的文件类型检查，不验证物料对应关系
      // 因为物料是手动选择的，与文件名无关
    },
    
    // 上传前检测
    beforeUploadPdf(file) {
      let isPDF = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf')
      if (!isPDF) {
        this.$message.error('只能上传PDF文件')
      }
      return isPDF
    },
    warningExceedPdf() {
      this.$message.error('仅可上传一份PDF指导文件')
    },
    // 预览指导文件按钮
    imgCheckDirectFile(row) {
      var param = []
      console.log(row)
      param[0] = ['物料编号',row.num]
      var updatepp = row.worker
      var uesrname = this.$store.state.user.name
      console.log(updatepp,uesrname)
      if(updatepp == uesrname){
        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"
            this.seeVisible = true
            this.$nextTick(() => {
                seepdf(pdfSrc,'see')
                    
            })
            // window.open(pdfSrc,'_blank')
          }
        })
      }else{
        return this.$message.error('只能查看自己上传的图纸')
      }
      
    },
    // 删除指导文件
    deleteImgCheckDirectFileSubmit(row) {
      this.$confirm('此操作将永久删除该指导文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['物料编号', row.num]
        param[1] = ['文件名称', row.name || '']
        param[2] = ['操作人', this.$store.state.user.name]
        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(mode) {
      if (mode === 'part') {
        // 零件图按钮 - 原功能
        this.partDialogVisible = true
        this.Uploaddirectly = true
        this.$nextTick(() => {
          if (this.$refs.partUpload) {
            this.$refs.partUpload.clearFiles()
          }
        })
      } else if (mode === 'multi') {
        // 选零件上传零件图 - 多选功能
        this.multiDialogVisible = true
        this.selectedMaterials = []
        this.uploadingProgress.show = false
        this.uploadingProgress.percentage = 0
        this.successItems = []
        this.failItems = []
        this.$nextTick(() => {
          if (this.$refs.multiUpload) {
            this.$refs.multiUpload.clearFiles()
          }
        })
      }
    },
    
    // 提交零件图上传 - 原功能
    submitPartPDF() {
      const files = this.$refs.partUpload.uploadFiles
      if (files.length === 0) {
        return this.$message.error('请先选择文件')
      }
      
      const filename = files[0].name
      const lastIndex = filename.lastIndexOf('.');
      const name = filename.substring(0, lastIndex);
      
      this.partDataPDF.params = JSON.stringify({
        num: name,
        tableName: '物料基础数据_零件图纸',
        worker: this.$store.state.user.name,
        uploadTime: this.currentTime,
        department: this.$store.state.user.name
      })
      console.log('上传参数:', JSON.stringify(this.partDataPDF))
      this.$refs.partUpload.submit()
      this.partDialogVisible = false
      setTimeout(() => {
        this.searchTable()
      }, 1000)
    },
    
    // 取消多选上传
    cancelMultiUpload() {
      this.multiDialogVisible = false
      if (this.$refs.multiUpload) {
        this.$refs.multiUpload.clearFiles()
      }
      this.resetUploadState()
    },
    
    // 批量检查物料是否存在图纸
    async checkMaterialsBatch(materials) {
      const results = {
        canUpload: [], // 可以上传的物料
        conflicts: []  // 冲突的物料
      }
      
      for (const material of materials) {
        try {
          var param = []
          param[0] = ['物料编号', material]
          var Data = this.CreateData('11', '工艺管理_图纸维护_查看图纸', param)
          const response = await this.ExecDatabase(Data)
          
          if (response.data.length > 0) {
            // 已有图纸，记录冲突信息
            results.conflicts.push({
              物料编码: material,
              导入人: response.data[0].worker || '未知',
              导入时间: response.data[0].uploadTime || ''
            })
          } else {
            // 可以上传
            results.canUpload.push(material)
          }
        } catch (error) {
          console.error(`检查物料${material}失败:`, error)
          // 如果检查失败，暂时认为可以上传
          results.canUpload.push(material)
        }
      }
      
      return results
    },
    
    // 批量上传图纸
    // async uploadMaterialsBatch(materials) {
    //   if (materials.length === 0) return { success: [], fail: [] }
      
    //   const success = []
    //   const fail = []
    //   const total = materials.length
    //   const currentUser = this.$store.state.user.name
      
    //   // 获取上传的文件
    //   const files = this.$refs.multiUpload.uploadFiles
    //   if (files.length === 0) {
    //     this.$message.error('请选择要上传的文件')
    //     return { success: [], fail: [] }
    //   }
      
    //   // 使用同一个文件为所有选中的物料上传
    //   // 假设上传的文件名格式为"图纸.pdf"，与物料编号无关
    //   const file = files[0] // 取第一个文件
      
    //   for (let i = 0; i < materials.length; i++) {
    //     const material = materials[i]
        
    //     try {
    //       // 更新进度
    //       this.uploadingProgress.percentage = Math.round(((i + 1) / total) * 100)
    //       this.uploadingProgress.message = `正在为物料 ${material} 上传图纸 (${i + 1}/${total})`
          
    //       // 准备上传参数
    //       this.multiDataPDF.params = JSON.stringify({
    //         num: material,  // 取消注释，使用实际值
    //         tableName: '物料基础数据_零件图纸',
    //         worker: this.$store.state.user.name,  // 取消注释
    //         uploadTime: this.currentTime, // 取消注释
    //         department:this.$store.state.user.name,
    //       })
    //       console.log(this.multiDataPDF)
    //       // 模拟上传延迟
    //       await new Promise(resolve => setTimeout(resolve, 800))
          
    //       // 这里应该是实际的上传请求
       
    //       this.$refs.multiUpload.submit()
    //       this.getImgCheckDirectFileList()
          
          
    //       // 模拟成功
    //       success.push(material)
          
    //     } catch (error) {
    //       console.error(`为物料${material}上传失败:`, error)
    //       fail.push(material)
    //     }
    //   }
      
    //   return { success, fail }
    // },
    // 使用项目中已有的请求方法
async uploadMaterialsBatch(materials) {
  if (materials.length === 0) return { success: [], fail: [] }
  
  const success = []
  const fail = []
  const total = materials.length
  const currentUser = this.$store.state.user.name
  
  // 获取上传的文件
  const files = this.$refs.multiUpload.uploadFiles
  if (files.length === 0) {
    this.$message.error('请选择要上传的文件')
    return { success: [], fail: [] }
  }
  
  const file = files[0].raw
  
  for (let i = 0; i < materials.length; i++) {
    const material = materials[i]
    
    try {
      this.uploadingProgress.percentage = Math.round(((i + 1) / total) * 100)
      this.uploadingProgress.message = `正在为物料 ${material} 上传图纸 (${i + 1}/${total})`
      
      const formData = new FormData()
      const uploadParams = {
        num: material,
        tableName: '物料基础数据_零件图纸',
        worker: currentUser,
        uploadTime: this.currentTime,
        department: currentUser
      }
      
      formData.append('file', file)
      formData.append('params', JSON.stringify(uploadParams))
      
      // 使用 Fetch API（原生支持，不需要引入）
      const response = await fetch(this.uploadPDF, {
        method: 'POST',
        body: formData
      })
      
      const result = await response.json()
      console.log(result)
      if (result[0].result ==='1') {
        success.push(material)
        this.$message.success(`物料 ${material} 上传成功`)
      } else {
        fail.push(material)
      }
      
    } catch (error) {
      console.error(`为物料${material}上传失败:`, error)
      fail.push(material)
    }
  }
  
  if (success.length > 0) {
    this.getImgCheckDirectFileList()
    this.$message.success(`成功上传 ${success.length} 个物料图纸`)
  }
  
  if (fail.length > 0) {
    this.$message.warning(`${fail.length} 个物料上传失败: ${fail.join(', ')}`)
  }
  
  return { success, fail }
},
    // 提交多选上传
    async submitMultiPDF() {
      // 验证
      if (this.selectedMaterials.length === 0) {
        return this.$message.error('请先选择物料')
      }
      
      const files = this.$refs.multiUpload.uploadFiles
      if (files.length === 0) {
        return this.$message.error('请先选择文件')
      }
      
      // 开始上传
      this.uploading = true
      // 确保 uploadingProgress 对象存在且有所有必要属性
      if (!this.uploadingProgress) {
        this.uploadingProgress = {}
      }
      this.uploadingProgress.show = true
      this.uploadingProgress.percentage = 0
      this.uploadingProgress.status = 'success'
      this.uploadingProgress.message = '开始检查物料...'
      
      try {
        // 第一步：批量检查哪些物料已有图纸
        const checkResult = await this.checkMaterialsBatch(this.selectedMaterials)
        
        // 如果有冲突，显示冲突对话框
        if (checkResult.conflicts.length > 0) {
          this.conflictDialog.items = checkResult.conflicts
          this.conflictDialog.visible = true
          
          // 如果全部冲突，直接返回
          if (checkResult.canUpload.length === 0) {
            this.$message.warning('所有选中的物料都已存在图纸，无法上传')
            this.uploading = false
            this.uploadingProgress.show = false
            this.$refs.multiUpload.clearFiles()
            return
          }
          
          // 部分冲突，询问用户是否继续上传可用的物料
          this.$confirm(`其中 ${checkResult.conflicts.length} 个物料已有图纸，是否继续上传剩余的 ${checkResult.canUpload.length} 个物料？`, '提示', {
            confirmButtonText: '继续上传',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            // 用户确认继续，上传可用的物料
            await this.uploadAvailableMaterials(checkResult.canUpload)
          }).catch(() => {
            // 用户取消
            this.resetUploadState()
            this.$refs.multiUpload.clearFiles()
          })
        } else {
          // 没有冲突，直接上传所有物料
          await this.uploadAvailableMaterials(checkResult.canUpload)
        }
      } catch (error) {
        console.error('上传过程出错:', error)
        this.$message.error('上传失败: ' + error.message)
        this.resetUploadState()
      }
    },
    
    // 上传可用的物料
    async uploadAvailableMaterials(materials) {
      if (materials.length === 0) {
        this.resetUploadState()
        return
      }
      // 确保状态对象存在
      if (!this.uploadingProgress) {
        this.uploadingProgress = {}
      }
      this.uploadingProgress.message = '开始上传图纸...'
      
      const result = await this.uploadMaterialsBatch(materials)
      
      this.uploadingProgress.percentage = 100
      
      if (result.success.length > 0) {
        this.uploadingProgress.message = `上传完成，成功：${result.success.length} 个，失败：${result.fail.length} 个`
        this.$message.success(`成功上传 ${result.success.length} 个物料图纸`)
        
        // 刷新列表
        this.searchTable()
        
        // 如果有失败，显示失败信息
        if (result.fail.length > 0) {
          this.$message.warning(`${result.fail.length} 个物料上传失败: ${result.fail.join(', ')}`)
        }
        
        // 关闭弹窗
        setTimeout(() => {
          this.multiDialogVisible = false
          this.resetUploadState()
          this.$refs.multiUpload.clearFiles()
        }, 2000)
      } else {
        this.uploadingProgress.message = '上传失败'
        this.uploadingProgress.status = 'exception'
        this.$message.error('所有物料上传失败')
        this.resetUploadState()
      }
    },
    resetUploadState() {
      this.uploading = false
      if (this.uploadingProgress) {
        this.uploadingProgress.show = false
        this.uploadingProgress.percentage = 0
        this.uploadingProgress.status = ''
        this.uploadingProgress.message = ''
      }
    },
    // 显示联系导入人信息
    showContactInfo(row) {
      this.$message({
        message: `请联系导入人 ${row.导入人} 删除物料 ${row.物料编码} 的图纸`,
        type: 'info',
        duration: 5000
      })
    },
    
    // 查询指导文件列表
    getImgCheckDirectFileList() {
      var param = []
      this.imgCheckDirectFileList = []
      if (!this.stationNumberValues || this.stationNumberValues.length === 0) {
        param[0] = ['零件图号_check', 0]
        param[1] = ['零件图号','']
        param[2] = ['导入人',this.$store.state.user.name]
        var Data = this.CreateData('11', '工艺管理_图纸维护_零件图查询', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data.length > 0) {
            this.imgCheckDirectFileList = response.data
          } else {
            this.$message.info('暂无图纸记录')
          }
        })
      } else {
        // 多选查询
        param[0] = ['零件图号_check', 1]
        param[1] = ['零件图号', this.stationNumberValues]
        param[2] = ['导入人',this.$store.state.user.name]
        var Data = this.CreateData('11', '工艺管理_图纸维护_零件图查询', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data.length > 0) {
            this.imgCheckDirectFileList = response.data
          } else {
            this.$message.info('所选物料暂无图纸记录')
          }
        })
      }
    }
  }
}
</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;
}
.pdf-viewer-container {
    position: relative;
    width: 100%;
    height: 500px;
    overflow: auto;
    border: 1px solid #ddd;
    margin-bottom: 20px;
    
    canvas {
        display: block;
        margin: 0 auto;
        background: #f5f5f5;
    }
}

// 确保弹窗有足够的空间
.el-dialog__body {
    padding: 20px !important;
}
</style>