<template>
  <div class="app-container">
    <el-card style="height: 850px">
      <div style="margin-top: 7px; margin-bottom: 7px">
        <el-input v-model="MaterialCode" style="width: 160px " size="small" clearable placeholder="物料编码"/><!-- 备注：修改人:Ld 修改时间:2026-06-29 14:24:00 -->
        <el-input v-model="MaterialName" style="width: 200px " size="small" clearable placeholder="物料名称/规格"/>
        <el-input v-model="DrawingNo" style="width: 200px " size="small" clearable placeholder="图号/型号"/>
        <el-input v-model="locationWarehouseValue" style="width:200px" placeholder="库位" size="small" clearable/>
        <el-button style="margin-left: 7px;width: 80px" type="primary" plain size="small" @click="searchTable()">查询</el-button>
        <!-- 修改人:Ld 修改时间:2026-07-22 10:17:30; 新增按Excel批量修改物料库位入口。 -->
        <el-button type="primary" icon="el-icon-upload2" style="margin-left: 7px" plain size="small" @click="openImportLocationDialog">导入修改库位</el-button>
        <el-button type="primary" icon="el-icon-printer" style="margin-left: 7px" plain size="small" @click="printReceiptDoc1()">打印</el-button>
      </div>
      <div>
        <!-- 修改人:Ld 修改时间:2026-07-22 09:59:17; 扩展表格宽度容纳修改库位操作列。 -->
        <el-table
          v-loading="loading"
          ref="table"
          :data="tableData"
          highlight-current-row
          show-summary
          border
          stripe
          size="small"
          style="width: 880px"
          height="740px"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50px"/>
          <el-table-column :width="setColumnWidth('序号')" type="index" label="序号" align="center"/>
          <el-table-column label="物料编码" align="center" show-overflow-tooltip><!-- 备注：修改人:Ld 修改时间:2026-06-29 14:24:00 -->
            <template slot-scope="scope">
              {{ scope.row.物料编号 }}
            </template>
          </el-table-column>
          <el-table-column label="物料名称" width="170px" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.物料名称 }}
            </template>
          </el-table-column>
          <el-table-column label="图号或型号" width="170px" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.图号或型号 }}
            </template>
          </el-table-column>
          <el-table-column label="库位" width="160px" align="center">
            <template slot-scope="scope">
              <!-- 修改人:Ld 修改时间:2026-07-22 09:59:17; 物料库位维护支持行内选择新库位。 -->
              <el-select
                v-if="scope.row.edit"
                v-model="scope.row.货位流水号"
                size="mini"
                style="width: 100%"
                clearable
                filterable
                placeholder="请选择库位"
                @change="handleLocationChange(scope.row)">
                <el-option
                  v-for="item in storageLocation"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <span v-else>{{ scope.row.货位名称 }}</span>
            </template>
          </el-table-column>
          <!-- 修改人:Ld 修改时间:2026-07-22 09:59:17; 物料库位维护新增修改库位操作按钮。 -->
          <el-table-column label="操作" width="130px" align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.edit" type="text" size="mini" @click="confirmEdit(scope.row)">确定</el-button>
              <el-button v-if="scope.row.edit" type="text" size="mini" @click="cancelEdit(scope.row)">取消</el-button>
              <el-button v-else type="text" size="mini" @click="openEdit(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="block" style="margin-top: 10px;">
        <el-pagination
          :current-page="pageCurrent"
          :page-sizes="[10, 20, 30, 40, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChanges"
          @current-change="handleCurrentChanges"/>
      </div>
    </el-card>
    <!-- 修改人:Ld 修改时间:2026-07-22 10:17:30; 导入物料库位修改预校验与提交弹窗。 -->
    <el-dialog
      v-el-drag-dialog
      :visible.sync="dialogFormVisibleImportLocation"
      title="导入修改库位"
      center
      width="1050px">
      <upload-excel-component @on-selected-file="selectedImportLocation"/>
      <div style="margin: 10px 0 0 45px">
        <span v-show="importWorksheet.length > 1" style="cursor: pointer;width: 50px;" @click="removeAllImportLocation"><i class="el-icon-close"/></span>
        <el-upload :on-remove="handleRemoveImportLocation" :file-list="importItemFile" style="width: 260px" action=""/>
      </div>
      <div style="margin: 12px 0">
        <el-button type="primary" size="small" icon="el-icon-search" @click="previewImportLocation">预校验</el-button>
        <el-button
          :loading="importLocationSubmitting"
          :disabled="importLocationData.length === 0"
          type="success"
          size="small"
          icon="el-icon-check"
          @click="submitImportLocation">确认修改</el-button>
        <span style="margin-left: 12px;font-size: 13px;color: #606266">{{ importLocationSummary }}</span>
      </div>
      <el-table :data="importLocationData" border stripe size="mini" height="430px">
        <el-table-column prop="导入序号" label="行号" width="70px" align="center"/>
        <el-table-column prop="物料编码" label="物料编号" width="130px" align="center" show-overflow-tooltip/>
        <el-table-column prop="物料名称" label="物料名称" width="160px" align="center" show-overflow-tooltip/>
        <el-table-column prop="图号或型号" label="图号或型号" width="150px" align="center" show-overflow-tooltip/>
        <el-table-column prop="原货位名称" label="原库位" width="100px" align="center" show-overflow-tooltip/>
        <el-table-column prop="调整后库位" label="调整后库位" width="120px" align="center" show-overflow-tooltip/>
        <el-table-column prop="处理状态" label="状态" width="100px" align="center"/>
        <el-table-column prop="说明" label="说明" align="center" show-overflow-tooltip/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisibleImportLocation=false">关闭</el-button>
      </div>
    </el-dialog>
    <el-card v-show="false">
      <div style="width:900px;margin-left: 350px">
        <el-card>
          <div id="WGBLD" style="width: 840px;margin: 0 auto">
            <div style="width: 260px;margin: 0 auto 20px">
              <h3>浙江景耀数控物料库位清单</h3>
            </div>
            <div style="margin: 0 0 20px">
              <span style="float: right; font-size: 14px;margin-right: 10px">日期：{{ NowTime }}</span>
            </div>
            <table align="center" border="1 solid black" cellspacing="0px" width="100%">
              <tr id="tablehead12" style="height: 35px">
                <td colspan="3" style="text-align: center;width: 25%;font-size: 14px">物料编码</td>
                <td colspan="5" style="text-align: center;width: 30%;font-size: 14px">物料名称</td>
                <td colspan="4" style="text-align: center;width: 22%;font-size: 14px">图号或型号</td>
                <td colspan="6" style="text-align: center;width: 23%;font-size: 14px">库位</td>
              </tr>
              <tr v-for="(list, index) in returns" :key="index" style="height: 35px">
                <td colspan="3" style="text-align: center;width: 25%;font-size: 14px">{{ list.物料编码 }}</td>
                <td colspan="5" style="text-align: center;width: 30%;font-size: 14px">{{ list.物料名称 }}</td>
                <td colspan="4" style="text-align: center;width: 22%;font-size: 14px">{{ list.规格型号 }}</td>
                <td colspan="6" style="text-align: center;width: 23%;font-size: 14px">{{ list.库位 }}</td>
              </tr>
              <tr style="height: 35px">
                <td colspan="12" style="text-align: center;font-size: 14px">合计</td>
                <td colspan="6" style="text-align: center;">
                  <div>
                    <span style="float: right;margin-right: 24%;font-size: 14px">{{ returns.length }} 条</span>
                  </div>
                </td>
              </tr>
            </table>
            <div style="margin-top: 15px"><span style="margin-left: 10px;font-size: 14px">制单：</span></div>
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ExecDatabase } from '@/main'
import { mapGetters } from 'vuex'
import $ from 'jquery'
import { getNowDAY } from '@/utils'
import UploadExcelComponent from '@/views/TechnologyCenter/ImportBOM/UploadExcel/index.vue'
export default {
  components: { UploadExcelComponent },
  data() {
    return {
      NowTime: getNowDAY(),
      returns: [],
      multipleSelection: [],
      locationWarehouseValue: '', // 库位
      MaterialCode: '',
      MaterialName: '',
      DrawingNo: '',
      dialogFormVisibleImportLocation: false, // 修改人:Ld 修改时间:2026-07-22 10:17:30; 导入修改库位弹窗。
      importItemFile: [],
      importWorksheet: [],
      importLocationData: [],
      importLocationDetailText: '',
      importLocationDetailChunks: [],
      importLocationSubmitting: false,
      LocationName: '',
      materialName1: '',
      productName: [],
      editorialStaff: [],
      loading: false, // 数据加载
      total: 0, // 分页总数
      tableData: [], // 合同信息表
      tableData10: [], // 合同信息表
      storageLocation: [], // 修改人:Ld 修改时间:2026-07-22 09:59:17; 库位下拉数据用于修改物料库位。
      pageCurrent: 1, // 分页当前页
      pageSize: 20, // 分页每页显示条数
      orderName: '', // 排序列名
      order: '' // 排序方式
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token'
    ]),
    importLocationSummary() {
      // 修改人:Ld 修改时间:2026-07-22 10:17:30; 汇总导入修改库位预校验和执行结果。
      if (this.importLocationData.length === 0) {
        return ''
      }
      var map = {}
      for (let i = 0; i < this.importLocationData.length; i++) {
        var status = this.importLocationData[i].处理状态 || '未知'
        map[status] = (map[status] || 0) + 1
      }
      var text = []
      for (var key in map) {
        text.push(key + '：' + map[key])
      }
      return '共' + this.importLocationData.length + '行，' + text.join('，')
    }
  },
  created() {
    // 修改人:Ld 修改时间:2026-07-22 09:59:17; 页面初始化时加载库位列表，供修改按钮使用。
    this.getLocateName()
    this.searchTable()
  },
  methods: {
    openImportLocationDialog() {
      // 修改人:Ld 修改时间:2026-07-22 10:17:30; 打开导入修改库位弹窗并清空上次预览。
      this.dialogFormVisibleImportLocation = true
      this.importLocationData = []
      this.importLocationDetailText = ''
      this.importLocationDetailChunks = []
    },
    selectedImportLocation(data) {
      // 修改人:Ld 修改时间:2026-07-22 10:17:30; 接收Excel上传组件解析出的工作表。
      this.importWorksheet = data.worksheet
      this.importItemFile = data.itemFile
      this.importLocationData = []
      this.importLocationDetailText = ''
      this.importLocationDetailChunks = []
    },
    handleRemoveImportLocation(file) {
      // 修改人:Ld 修改时间:2026-07-22 10:17:30; 移除导入文件时同步移除工作表数据。
      for (let i = 0; i < this.importItemFile.length; i++) {
        if (this.importItemFile[i].name === file.name) {
          this.importWorksheet.splice(i, 1)
          this.importItemFile.splice(i, 1)
          this.importLocationData = []
          this.importLocationDetailText = ''
          this.importLocationDetailChunks = []
        }
      }
    },
    removeAllImportLocation() {
      // 修改人:Ld 修改时间:2026-07-22 10:17:30; 清空所有待导入文件。
      this.importWorksheet = []
      this.importItemFile = []
      this.importLocationData = []
      this.importLocationDetailText = ''
      this.importLocationDetailChunks = []
    },
    getExcelCellValue(sheet, col, row) {
      var cell = sheet[col + row]
      if (!cell || cell.v === undefined || cell.v === null) {
        return ''
      }
      return String(cell.v).trim()
    },
    getImportLocationColumns(sheet) {
      // 修改人:Ld 修改时间:2026-07-23 08:24:55; 自动识别物料编号、物料名称、图号型号、调整后库位和库存列。
      var cols = [
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
        'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
      ]
      var result = {
        headerRow: 1,
        materialCodeCol: 'A',
        materialNameCol: 'B',
        drawingCol: 'C',
        locationCol: 'E',
        inventoryCol: 'F'
      }
      for (let row = 1; row <= 10; row++) {
        let materialCodeCol = ''
        let materialNameCol = ''
        let drawingCol = ''
        let locationCol = ''
        let inventoryCol = ''
        for (let i = 0; i < cols.length; i++) {
          var title = this.getExcelCellValue(sheet, cols[i], row).replace(/\s/g, '')
          if (title === '物料编号' || title === '物料编码') {
            materialCodeCol = cols[i]
          }
          if (title === '物料名称' || title === '名称' || title === '零件名称') {
            materialNameCol = cols[i]
          }
          if (title === '图号型号' || title === '图号' || title === '图号或型号' || title === '图号/型号' || title === '规格型号') {
            drawingCol = cols[i]
          }
          if (title === '调整后库位' || title === '库位') {
            locationCol = cols[i]
          }
          if (title === '库存' || title === '库存数') {
            inventoryCol = cols[i]
          }
        }
        if (materialCodeCol || materialNameCol || drawingCol || locationCol || inventoryCol) {
          result.headerRow = row
          result.materialCodeCol = materialCodeCol || result.materialCodeCol
          result.materialNameCol = materialNameCol || result.materialNameCol
          result.drawingCol = drawingCol || result.drawingCol
          result.locationCol = locationCol || result.locationCol
          result.inventoryCol = inventoryCol || result.inventoryCol
          return result
        }
      }
      return result
    },
    getImportLocationDetail() {
      // 修改人:Ld 修改时间:2026-07-23 08:24:55; 提取Excel中的物料编号、物料名称、图号型号、调整后库位和库存。
      var detail = []
      for (let j = 0; j < this.importWorksheet.length; j++) {
        var sheet = this.importWorksheet[j]
        var columns = this.getImportLocationColumns(sheet)
        var emptyCount = 0
        for (let row = columns.headerRow + 1; row <= 6000; row++) {
          var materialCode = this.getExcelCellValue(sheet, columns.materialCodeCol, row)
          var materialName = this.getExcelCellValue(sheet, columns.materialNameCol, row)
          var drawing = this.getExcelCellValue(sheet, columns.drawingCol, row)
          var locationName = this.getExcelCellValue(sheet, columns.locationCol, row)
          var inventory = this.getExcelCellValue(sheet, columns.inventoryCol, row)
          if (!materialCode && !materialName && !drawing && !locationName && !inventory) {
            emptyCount++
            if (emptyCount >= 20) {
              break
            }
            continue
          }
          emptyCount = 0
          detail.push({
            行号: row,
            物料编码: materialCode,
            物料名称: materialName,
            图号或型号: drawing,
            调整后库位: locationName,
            库存: inventory
          })
        }
      }
      return detail
    },
    getImportLocationInventoryValue(value) {
      // 修改人:Ld 修改时间:2026-07-23 08:24:55; 多库位时按Excel库存数比较大小。
      var num = Number(value)
      if (isNaN(num)) {
        return 0
      }
      return num
    },
    getImportLocationBestDetail(detail) {
      // 修改人:Ld 修改时间:2026-07-23 08:24:55; 同一物料多库位时保留库存数最大的库位行。
      var map = {}
      var list = []
      for (let i = 0; i < detail.length; i++) {
        var materialCode = String(detail[i].物料编码 || '').trim()
        var materialName = String(detail[i].物料名称 || '').trim()
        var drawing = String(detail[i].图号或型号 || '').trim()
        var key = materialCode || (materialName + '^' + drawing)
        if (!key) {
          key = 'ROW-' + detail[i].行号
        }
        if (!map[key]) {
          map[key] = detail[i]
          list.push(detail[i])
        } else if (this.getImportLocationInventoryValue(detail[i].库存) > this.getImportLocationInventoryValue(map[key].库存)) {
          var index = list.indexOf(map[key])
          map[key] = detail[i]
          if (index >= 0) {
            list.splice(index, 1, detail[i])
          }
        }
      }
      return list
    },
    buildImportLocationDetailText(detail) {
      // 修改人:Ld 修改时间:2026-07-23 08:24:55; 将导入明细转为后端批量过程可解析的字符串。
      var list = []
      var usedMap = {}
      for (let i = 0; i < detail.length; i++) {
        var materialCode = String(detail[i].物料编码 || '').replace(/\^|\|\|/g, '').trim()
        var materialName = String(detail[i].物料名称 || '').replace(/\^|\|\|/g, '').trim()
        var drawing = String(detail[i].图号或型号 || '').replace(/\^|\|\|/g, '').trim()
        var locationName = String(detail[i].调整后库位 || '').replace(/\^|\|\|/g, '').trim()
        var inventory = String(detail[i].库存 || '').replace(/\^|\|\|/g, '').trim()
        var key = materialCode + '^' + materialName + '^' + drawing + '^' + locationName + '^' + inventory
        if (!usedMap[key]) {
          usedMap[key] = true
          list.push(detail[i].行号 + '^' + materialCode + '^' + materialName + '^' + drawing + '^' + locationName + '^' + inventory)
        }
      }
      return list.join('||')
    },
    buildImportLocationDetailChunks(detail) {
      // 修改人:Ld 修改时间:2026-07-23 08:24:55; 大表分批提交，避免单次参数过长。
      var chunks = []
      var chunk = []
      var usedMap = {}
      for (let i = 0; i < detail.length; i++) {
        var materialCode = String(detail[i].物料编码 || '').replace(/\^|\|\|/g, '').trim()
        var materialName = String(detail[i].物料名称 || '').replace(/\^|\|\|/g, '').trim()
        var drawing = String(detail[i].图号或型号 || '').replace(/\^|\|\|/g, '').trim()
        var locationName = String(detail[i].调整后库位 || '').replace(/\^|\|\|/g, '').trim()
        var inventory = String(detail[i].库存 || '').replace(/\^|\|\|/g, '').trim()
        var key = materialCode + '^' + materialName + '^' + drawing + '^' + locationName + '^' + inventory
        if (!usedMap[key]) {
          usedMap[key] = true
          chunk.push(detail[i].行号 + '^' + materialCode + '^' + materialName + '^' + drawing + '^' + locationName + '^' + inventory)
          if (chunk.length >= 500) {
            chunks.push(chunk.join('||'))
            chunk = []
          }
        }
      }
      if (chunk.length > 0) {
        chunks.push(chunk.join('||'))
      }
      return chunks
    },
    requestImportLocationPreview(index, rows) {
      // 修改人:Ld 修改时间:2026-07-22 10:17:30; 分批调用预校验过程并合并展示。
      if (index >= this.importLocationDetailChunks.length) {
        this.importLocationData = rows
        this.loading = false
        this.$message.success('预校验完成')
        return
      }
      var param = []
      param[0] = ['导入明细', this.importLocationDetailChunks[index]]
      var Data = this.CreateData('11', '仓储管理_物料库位_导入修改库位_预校验', param)
      ExecDatabase(Data).then(response => {
        var data = response.data.rows || response.data || []
        this.requestImportLocationPreview(index + 1, rows.concat(data))
      }).catch(() => {
        this.loading = false
      })
    },
    previewImportLocation() {
      // 修改人:Ld 修改时间:2026-07-22 10:17:30; 上传后先预校验物料和库位变化。
      var detail = this.getImportLocationDetail()
      if (detail.length === 0) {
        this.$message.warning('请导入包含物料编号和调整后库位的表格')
        return
      }
      var validDetail = this.getImportLocationBestDetail(detail)
      this.importLocationDetailText = this.buildImportLocationDetailText(validDetail)
      this.importLocationDetailChunks = this.buildImportLocationDetailChunks(validDetail)
      this.loading = true
      if (this.importLocationDetailChunks.length === 0) {
        this.importLocationData = []
        this.loading = false
        this.$message.warning('导入表中没有可提交的数据')
        return
      }
      this.requestImportLocationPreview(0, [])
    },
    requestImportLocationSubmit(index, rows) {
      // 修改人:Ld 修改时间:2026-07-22 10:17:30; 分批执行物料库位修改并合并返回结果。
      if (index >= this.importLocationDetailChunks.length) {
        this.importLocationData = rows
        this.importLocationSubmitting = false
        this.$message.success('导入修改完成')
        this.getLocateName()
        this.searchTable()
        return
      }
      var param = []
      param[0] = ['导入明细', this.importLocationDetailChunks[index]]
      param[1] = ['修改人', this.id]
      var Data = this.CreateData('12', '仓储管理_物料库位_导入修改库位_批量执行', param)
      ExecDatabase(Data).then(response => {
        var data = response.data.rows || response.data || []
        this.requestImportLocationSubmit(index + 1, rows.concat(data))
      }).catch(() => {
        this.importLocationSubmitting = false
      })
    },
    submitImportLocation() {
      // 修改人:Ld 修改时间:2026-07-22 10:17:30; 确认后批量新建缺失库位并修改物料库位。
      if (this.importLocationDetailChunks.length === 0) {
        this.$message.warning('请先预校验')
        return
      }
      this.$confirm('确认按导入表修改物料库位吗？缺失库位将自动新建。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.importLocationSubmitting = true
        this.requestImportLocationSubmit(0, [])
      }).catch(() => {})
    },
    getLocateName() {
      // 修改人:Ld 修改时间:2026-07-22 09:59:17; 复用库位管理查询接口加载可选库位。
      this.storageLocation = []
      var param = []
      var Data = this.CreateData('11', '仓储管理_库位_查询', param)
      ExecDatabase(Data).then(response => {
        var rows = response.data.rows || response.data || []
        for (let i = 0; i < rows.length; i++) {
          this.storageLocation.push({
            label: rows[i].货位名称,
            value: Number(rows[i].货位流水号)
          })
        }
      })
    },
    searchTable() {
      this.loading = true
      this.tableData10 = []
      let MaterialCode_check, MaterialName_check, DrawingNo_check, locationWarehouseValue_check
      this.MaterialCode ? MaterialCode_check = 1 : MaterialCode_check = 0
      this.MaterialName ? MaterialName_check = 1 : MaterialName_check = 0
      this.DrawingNo ? DrawingNo_check = 1 : DrawingNo_check = 0
      this.locationWarehouseValue ? locationWarehouseValue_check = 1 : locationWarehouseValue_check = 0
      var param = []
      param[0] = ['物料名称_check', MaterialName_check]
      param[1] = ['物料名称', this.MaterialName]
      param[2] = ['图号或型号_check', DrawingNo_check]
      param[3] = ['图号或型号', this.DrawingNo]
      param[4] = ['库位_check', locationWarehouseValue_check]
      param[5] = ['库位', this.locationWarehouseValue]
      param[6] = ['物料编码_check', MaterialCode_check]
      param[7] = ['物料编码', this.MaterialCode]
      var Data = this.CreateData('11', '仓储管理_物料库位_查询数据', param, this.pageSize, this.pageCurrent)
      ExecDatabase(Data).then(response => {
        // console.log(response.data)
        if (response.data.rows.length !== 0) {
          for (let i = 0; i < response.data.rows.length; i++) {
            this.tableData10.push({
              // 表示将从数据库中查询到的数据，分别对应填充到表格中
              货位流水号: Number(response.data.rows[i].货位流水号),
              货位名称: response.data.rows[i].货位名称,
              物料流水号: response.data.rows[i].物料流水号,
              物料名称: response.data.rows[i].名称,
              图号或型号: response.data.rows[i].代号,
              物料编号: response.data.rows[i].物料编码,
              货位流水号_before: Number(response.data.rows[i].货位流水号), // 修改人:Ld 修改时间:2026-07-22 09:59:17; 保存修改前库位流水号用于取消和日志。
              货位名称_before: response.data.rows[i].货位名称,
              edit: false
            })
          }
        }
        this.total = response.data.total
        this.loading = false
      }).then(() => {
        this.tableData = this.tableData10
      })
    },
    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.searchTable()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    openEdit(row) {
      // 修改人:Ld 修改时间:2026-07-22 09:59:17; 进入行内库位修改状态并备份原值。
      row.货位流水号_before = row.货位流水号
      row.货位名称_before = row.货位名称
      row.edit = true
      if (this.storageLocation.length === 0) {
        this.getLocateName()
      }
    },
    handleLocationChange(row) {
      // 修改人:Ld 修改时间:2026-07-22 09:59:17; 下拉切换时同步展示库位名称。
      row.货位名称 = ''
      for (let i = 0; i < this.storageLocation.length; i++) {
        if (Number(this.storageLocation[i].value) === Number(row.货位流水号)) {
          row.货位名称 = this.storageLocation[i].label
          return
        }
      }
    },
    confirmEdit(row) {
      // 修改人:Ld 修改时间:2026-07-22 09:59:17; 保存物料库位修改并同步后端物料库位关系。
      if (!row.货位流水号) {
        this.$message.warning('请选择库位')
        return
      }
      if (Number(row.货位流水号) === Number(row.货位流水号_before)) {
        this.$message.warning('库位未变化')
        row.edit = false
        return
      }
      var param = []
      param[0] = ['物料流水号', row.物料流水号]
      param[1] = ['货位流水号', row.货位流水号]
      param[2] = ['原货位流水号', row.货位流水号_before]
      param[3] = ['修改人', this.id]
      var Data = this.CreateData('12', '仓储管理_物料库位_编辑数据', param)
      ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.$message.success('修改成功')
          this.searchTable()
        } else {
          this.$message.error(response.data[0].msg || '修改失败')
        }
      })
    },
    cancelEdit(row) {
      // 修改人:Ld 修改时间:2026-07-22 09:59:17; 取消修改时恢复原库位。
      row.货位流水号 = row.货位流水号_before
      row.货位名称 = row.货位名称_before
      row.edit = false
    },
    async printReceiptDoc1() {
      const aa = this.printReceiptDoc()
      if (aa === 2) {
        await this.sleep(500)
        await this.exportTable()
      } else if (aa === 1) {
        this.$message.warning('请勾选要打印的物料！！')
      }
    },
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms))
    },
    exportTable() {
      const htmlNode = $('#WGBLD').html()
      const body = $('body')
      body.children().hide()
      const printNode = $(htmlNode)
      body.append(printNode)
      window.print()
      body.children().not('script').show()
      body.children().not('#app').hide()
      printNode.remove()
    },
    printReceiptDoc() {
      this.returns = []
      if (this.multipleSelection.length !== 0) {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.returns.push({
            物料编码: this.multipleSelection[i].物料编号,
            物料名称: this.multipleSelection[i].物料名称,
            规格型号: this.multipleSelection[i].图号或型号,
            库位: this.multipleSelection[i].货位名称
          })
        }
        return 2
      } else {
        this.$message.warning('未勾选物料！！')
        return 1
      }
    }
  }
}
</script>
