<template>
  <div class="ele-body">
    <el-card shadow="never">
      <header-title title="基本信息">
        <div class="right_control">
          <el-upload ref="fileUploadBtn" action="#" :auto-upload="false" :on-change="onChange" :limit="1"
            :show-file-list="false" accept=".xls,.xlsx">
            <el-button type="primary">备品备件导入excel</el-button>
          </el-upload>
          <el-button type="primary" @click="back">返回</el-button>
        </div>
      </header-title>
      <el-form :model="formData" ref="formName" label-width="110px" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="物品类型" prop="extInfo.assetType">
              <el-select style="width: 100%" multiple v-model="formData.extInfo.assetType" placeholder="请选择">
                <el-option v-for="item in goodsLists" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库类型" prop="bizType">
              <el-select style="width: 100%" filterable placeholder="请选择" v-model="formData.bizType" clearable>
                <el-option v-for="item in sceneState" :key="item.code" :value="item.code + ''"
                  :label="item.label"></el-option>
              </el-select> </el-form-item></el-col>
          <el-col :span="6">
            <el-form-item label="单据来源" prop="sourceBizNo">
              <el-input placeholder="请选择" v-model="formData.sourceBizNo" @focus="openDocumentSourceDialog">
                <template #append>
                  <el-button @click.stop="clearSourceBizNo" slot="append" icon="el-icon-circle-close"></el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="权属部门" prop="deptName">
              <el-input
                placeholder="权属部门"
                disabled
                v-model="formData.extInfo.deptName"
                clearable
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="入库时间">
              <el-date-picker v-model="formData.storageTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间">
              </el-date-picker></el-form-item></el-col>
          <el-col :span="6">
            <el-form-item label="入库登记人">
              <el-input placeholder="登记人" disabled v-model="formData.extInfo.createUserName"
                clearable /></el-form-item></el-col>
          <el-col :span="6" v-if="formData.bizType == 2">
            <el-form-item label="供应商" prop="supplierName">
              <el-input placeholder="请输入" clearable v-model="formData.extInfo.supplierName" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="送货人" prop="fromUser">
              <el-input placeholder="请输入" v-model="formData.fromUser" clearable /> </el-form-item></el-col>
          <el-col :span="6">
            <el-form-item label="送货人联系方式" prop="deliveryPhone">
              <el-input placeholder="请输入" v-model="formData.extInfo.deliveryPhone" clearable /></el-form-item></el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请详细说明"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="inbound_details">
        <header-title title="产品信息">
          <el-button type="primary" @click="addProduct">添加</el-button>
        </header-title>
        <div class="form_table">
          <el-form ref="productListRef" :model="{ productList: productList }" :show-message="false">
            <!-- <el-button v-if="productList.length != 0" type="success" plain
              style="margin-bottom: 20px; float: right; margin-right: 20px" size="mini"
              @click="batchSave">批量保存</el-button> -->
            <el-button v-if="productList.length != 0" type="success" plain
              style="margin-bottom: 20px; float: right; margin-right: 20px" size="mini"
              @click="handleWareHouse(productList, '', 'batch')">批量选择仓库</el-button>
            <el-table :header-cell-style="rowClass" :max-height="300" border ref="productListTable" :data="productList"
              tooltip-effect="dark">
              <el-table-column label="序号" type="index" width="50" align="center">
              </el-table-column>
              <el-table-column label="编码" prop="categoryCode" align="center" width="130"
                :show-overflow-tooltip="true"></el-table-column>
              <el-table-column label="名称" align="center" width="200" prop="categoryName"
                :show-overflow-tooltip="true"></el-table-column>
              <el-table-column label="型号" align="center" width="100" prop="categoryModel"
                :show-overflow-tooltip="true"></el-table-column>
              <el-table-column label="规格" align="center" width="100" prop="specification"
                :show-overflow-tooltip="true"></el-table-column>
              <el-table-column label="牌号" align="center" width="100" prop="brandNum"
                :show-overflow-tooltip="true"></el-table-column>
              <el-table-column v-for="(item, index) in newColumns" :label="item.label" :align="item.align"
                :prop="item.prop" :show-overflow-tooltip="item.showOverflowTooltip"></el-table-column>
              <el-table-column label="批次号" align="center" width="100" prop="batchNo">
                <template slot-scope="{ row, $index }">
                  <template v-if="row.isSave">
                    {{ row.batchNo }}
                  </template>
                  <el-form-item v-else :prop="`productList.${$index}.batchNo`" required>
                    <el-input :ref="'batchNo' + $index" @keyup.native="
                      moveFocus($event, $index, 'batchNo', '产品', row)
                      " v-model.number="row.batchNo">
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- <el-table-column label="物料代号" prop="materielCode">
                <template slot-scope="{ row, $index }">
                  {{ row.extInfo.materielCode }}
                </template>
              </el-table-column> -->

              <el-table-column label="数量" align="center" width="180" prop="packingQuantity">
                <template slot-scope="{ row, $index }">
                  <template v-if="row.isSave">
                    {{ row.packingQuantity }}
                  </template>
                  <el-form-item v-else :prop="`productList.${$index}.packingQuantity`" required>
                    <el-input :ref="'packingQuantity' + $index" type="number" placeholder="请输入" @keyup.native="
                      moveFocus(
                        $event,
                        $index,
                        'packingQuantity',
                        '产品',
                        row
                      )
                      " v-model="row.packingQuantity" @input="computeNum(row, $index, true)" :disabled="row.isSave">
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="单位" align="center" prop="packingUnit" width="100">
                <template slot-scope="{ row, $index }">
                  <template v-if="row.isSave">
                    {{ row.packingUnit }}
                  </template>
                  <el-form-item v-else :prop="`productList.${$index}.packingUnit`" required>
                    <el-select :disabled="row.isSave" v-model="row.packingUnit" placeholder="请选择"
                      @change="computeNum(row, $index)">
                      <el-option v-for="item in row.packingSpecificationOption" :label="`${item.conversionUnit}`"
                        :value="item.conversionUnit" :key="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="包装规格" align="center" prop="packingSpecificationLabel" width="300"
                :show-overflow-tooltip="true">
                <template slot-scope="{ row, $index }">
                  <el-tag v-for="item in row.packingSpecificationLabel">{{
                    item
                  }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="允许拆包" prop="isUnpack">
                <template slot-scope="{ row, $index }">
                  {{ row.isUnpack ? '是' : '否' }}
                </template>
              </el-table-column>
              <el-table-column label="计量数量" align="center" prop="measureQuantity"
                :show-overflow-tooltip="true"></el-table-column>
              <el-table-column label="计量单位" align="center" prop="measureUnit"
                :show-overflow-tooltip="true"></el-table-column>
              <el-table-column label="单重" align="center" prop="singleWeight" :show-overflow-tooltip="true" width="180">
                <template slot-scope="{ row, $index }">
                  <el-input :disabled="row.isSave" v-model="row.singleWeight" placeholder="请输入" :min="0"
                    style="width: 100%" @input="inputSingleWeight(row, $index)">
                    <template slot="append"> {{ row.weightUnit + '/' + row.measureUnit }} </template>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="总重" align="center" prop="weight" width="150" :show-overflow-tooltip="true">
                <template slot-scope="{ row, $index }">
                  <el-input :disabled="row.isSave" v-model="row.weight" placeholder="请输入"
                    @input="inputAllweight(row, $index)">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="重量单位" align="center" prop="weightUnit" :show-overflow-tooltip="true">
                <template slot-scope="{ row, $index }">
                  {{ row.weightUnit }}
                  <template slot="append"> </template>
                </template>
              </el-table-column>
              <el-table-column label="单价" prop="unitPrice" width="200" align="center">
                <template slot-scope="{ row, $index }">
                  <template v-if="row.isSave">
                    {{ row.unitPrice ? row.unitPrice + '/元' : '' }}
                  </template>
                  <el-form-item v-else>
                    <el-input type="number" :ref="'unitPrice' + $index" @keyup.native="
                      moveFocus($event, $index, 'unitPrice', '产品', row)
                      " v-model.number="row.unitPrice" placeholder="非必填" @input="
                        (value) =>
                          (row.unitPrice = value.replace(/[^0-9.]+/g, ''))
                      ">
                      <template slot="append">
                        元/{{ row.measureUnit }}
                      </template>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="金额" align="center" prop="totalMoney" :show-overflow-tooltip="true">
                <template slot-scope="{ row, $index }">
                  {{
                    changeCount(
                      calcSumTotal(row.measureQuantity, row.unitPrice, row)
                    )
                  }}
                </template>
              </el-table-column>
              <el-table-column label="供应商" align="center" prop="supplierId" width="200" :show-overflow-tooltip="true">
                <template slot-scope="{ row, $index }">
                  <template v-if="row.isSave">
                    {{ row.supplierName }}
                  </template>
                  <el-select v-else @change="selectSupplier($event, row)" v-model="row.supplierId" placeholder="请选择">
                    <el-option v-for="item in row.supplierListOptions" :label="item.name" :value="item.id"
                      :key="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="供应商代号" align="center" prop="supplierCode" :show-overflow-tooltip="true"
                width="100">
                <template slot-scope="{ row, $index }">
                  {{ row.supplierCode }}
                </template>
              </el-table-column>
              <el-table-column label="仓库" align="center" prop="warehouseName" :show-overflow-tooltip="true" width="300">
                <template slot-scope="{ row, $index }">
                  <el-form-item :prop="`productList.${$index}.warehouseId`" required>
                    <div :class="row.warehouseName
                      ? 'wareHouse_style'
                      : 'wareHouse_style red_color'
                      " @click="handleWareHouse(row, $index)">
                      <span>
                        {{
                          row.warehouseName ? row.warehouseName : '请选择仓库'
                        }}
                      </span>
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="采购原因" align="center" width="200" prop="purpose" :show-overflow-tooltip="true">
                <template slot-scope="{ row, $index }">
                  <template v-if="row.isSave">
                    {{ row.purpose }}
                  </template>
                  <el-input v-else :ref="'purpose' + $index" @keyup.native="
                    moveFocus($event, $index, 'purpose', '产品', row)
                    " v-model="row.purpose">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right" align="center">
                <template slot="header" slot-scope="scope"> 操作 </template>
                <template slot-scope="{ row, $index }">
                  <el-button type="text" v-show="!row.isSave" @click="listSave(row, $index)">保存</el-button>
                  <el-button type="text" v-show="row.isSave" @click="listEdit(row, $index)">编辑</el-button>
                  <el-button type="text" @click="listDel(row, $index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </div>
      <div v-if="showPackingList.length > 0" class="inbound_details">
        <header-title :title="`包装明细`">
          <div class="switch_right">
            <el-button style="margin-left: 20px" type="text" @click="dateSetting">批量设置{{
              curDateType === 'productionDate' ? '生产日期' : '采购日期'
            }}</el-button>
          </div>
        </header-title>
        <el-table v-if="isWrapTable" ref="packingListTable" :data="showPackingList" tooltip-effect="dark"
          :key="formData.bizType" :header-cell-style="rowClass" style="width: 100%" border stripe :max-height="300"
          v-el-table-infinite-scroll="pickingHandleScroll" @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" width="50">
          </el-table-column>
          <el-table-column label="序号" type="index" width="50">
          </el-table-column>
          <el-table-column label="批次号" prop="batchNo" width="80" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="包装编码" prop="packageNo" width="130" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="名称" prop="categoryName" width="120" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="编码" prop="categoryCode" width="120" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="型号" prop="categoryModel" width="80" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="规格" prop="specification" width="80" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="牌号" prop="brandNum" width="80" :show-overflow-tooltip="true"></el-table-column>

          <el-table-column label="包装数量" prop="packingQuantity" width="80"></el-table-column>
          <el-table-column label="包装单位" prop="packingUnit"></el-table-column>
          <el-table-column label="计量数量" prop="measureQuantity" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="计量单位" prop="measureUnit"></el-table-column>

          <el-table-column label="仓库" :show-overflow-tooltip="true" prop="warehouseName" width="200"></el-table-column>
          <el-table-column label="供应商" align="center" prop="supplierName" width="200" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column label="供应商代号" prop="supplierCode" width="130">
          </el-table-column>
          <el-table-column label="物料代号" prop="materielDesignation" width="130">
            <template slot-scope="{ row, $index }">
              <el-input v-if="!row.isPack" :ref="'packing_materielDesignation' + $index" @keyup.native="
                moveFocus(
                  $event,
                  $index,
                  'packing_materielDesignation',
                  '包装',
                  row
                )
                " v-model="row.materielDesignation"></el-input>
              <span v-else>{{ row.materielDesignation }}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户代号" prop="clientCode">
            <template slot-scope="{ row, $index }">
              <el-input v-model="row.clientCode"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="刻码" prop="engrave" width="140">
            <template slot-scope="{ row, $index }">
              <el-input v-if="!row.isPack" :ref="'packing_engrave' + $index" @keyup.native="
                moveFocus($event, $index, 'packing_engrave', '包装', row)
                " v-model="row.engrave"></el-input>
              <span v-else>{{ row.engrave }}</span>
            </template>
          </el-table-column>
          <el-table-column label="重量" prop="weight" width="100">
            <template slot-scope="{ row, $index }">
              <el-input v-if="!row.isPack && row.measureUnit != row.weightUnit" :ref="'packing_weight' + $index"
                @keyup.native="
                  moveFocus($event, $index, 'packing_weight', '包装', row)
                  " v-model.number="row.weight" @input="weightInput($event, row, '包装')"></el-input>
              <span v-else>{{ row.weight }}</span>
            </template>
          </el-table-column>
          <el-table-column label="重量单位" prop="weightUnit">
            <template slot-scope="{ row }">
              {{ row.weightUnit }}
            </template>
          </el-table-column>

          <el-table-column label="质检结果" prop="result" width="120">
            <template slot-scope="{ row }">
              <el-select v-if="!row.isPack" @change="changeWrapStatus($event, row, '包装')" v-model="row.result"
                placeholder="请选择">
                <el-option v-for="item in qualityResultsOptions" :label="item.label" :value="item.value"
                  :key="item.value">
                </el-option>
              </el-select>
              <span v-else>{{ qualityResults[row.result] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="质检状态" prop="status" width="120">
            <template slot-scope="{ row }">
              <span>{{ qualityStatus[row.status] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" prop="" width="220">
            <template slot="header" slot-scope="scope">
              <el-select filterable v-model="curDateType">
                <el-option value="productionDate" label="生产日期"></el-option>
                <el-option value="purchaseDate" label="采购日期"></el-option>
              </el-select>
            </template>
            <template slot-scope="{ row }">
              <template v-if="formData.bizType == 5">
                {{ row[curDateType] }}
              </template>
              <el-date-picker v-else :disabled="row.isPack" size="small" v-model="row[curDateType]" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="{ row, $index }">
              <el-button type="text" @click="wrapDelete(row, $index)">
                删除
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div v-if="showMaterialList.length > 0" class="inbound_details">
        <header-title :title="`物料明细`"></header-title>
        <el-table ref="materialListTable" :data="showMaterialList" tooltip-effect="dark" :key="formData.bizType"
          :header-cell-style="rowClass" style="width: 100%" border stripe :max-height="300"
          v-el-table-infinite-scroll="materielHandleScroll">
          <el-table-column label="序号" type="index" width="50">
          </el-table-column>
          <el-table-column label="编码" prop="categoryCode" width="130" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="名称" prop="categoryName" width="150" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="批次号" prop="batchNo" width="70"></el-table-column>
          <el-table-column label="物料编码" prop="materialCode" width="200" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="计量数量" prop="measureQuantity" width="90"
            :show-overflow-tooltip="true"></el-table-column>
          <el-table-column width="80" label="计量单位" prop="measureUnit"></el-table-column>
          <el-table-column label="物料代号" prop="materielDesignation" width="130">
            <template slot-scope="{ row, $index }">
              <el-input v-if="!row.isPack" :ref="'material_materielDesignation' + $index" @keyup.native="
                moveFocus(
                  $event,
                  $index,
                  'material_materielDesignation',
                  '物料',
                  row
                )
                " v-model="row.materielDesignation"></el-input>
              <span v-else>{{ row.materielDesignation }}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户代号" prop="clientCode">
            <template slot-scope="{ row, $index }">
              <el-input v-if="!row.isPack" :ref="'material_clientCode' + $index" @keyup.native="
                moveFocus($event, $index, 'material_clientCode', '物料', row)
                " v-model="row.extInfo.clientCode"></el-input>
              <span v-else>{{ row.extInfo.clientCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="刻码" prop="engrave" width="140">
            <template slot-scope="{ row, $index }">
              <el-input v-if="!row.isPack" :ref="'material_engrave' + $index" @keyup.native="
                moveFocus($event, $index, 'material_engrave', '物料', row)
                " v-model="row.engrave"></el-input>
              <span v-else>{{ row.engrave }}</span>
            </template>
          </el-table-column>
          <el-table-column label="重量" prop="weight" width="100">
            <template slot-scope="{ row, $index }">
              <el-input v-if="!row.isPack && row.measureUnit != row.weightUnit" :ref="'material_weight' + $index"
                @keyup.native="
                  moveFocus($event, $index, 'material_weight', '物料', row)
                  " @input="weightInput($event, row, '物料')" v-model.number="row.weight"></el-input>
              <span v-else>{{ row.weight }}</span>
            </template>
          </el-table-column>
          <el-table-column label="重量单位" prop="weightUnit" width="100"></el-table-column>
          <el-table-column label="质检结果" prop="result" width="120">
            <template slot-scope="{ row }">
              <el-select v-if="!row.isPack" @change="changeWrapStatus($event, row, '物料')" v-model="row.result"
                placeholder="请选择">
                <el-option v-for="item in qualityResultsOptions" :label="item.label" :value="item.value"
                  :key="item.value">
                </el-option>
              </el-select>
              <span v-else>{{ qualityResults[row.result] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="质检状态" prop="status" width="120">
            <template slot-scope="{ row }">
              <span>{{ qualityStatus[row.status] }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="{ row, $index }">
              <el-button type="text" @click="materialDelete(row, $index)">
                删除
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="storage_btn">
        <el-button type="primary" :loading="saveLoading" @click="storage">入库</el-button>
      </div>
    </el-card>
    <!-- 产品选择弹框 -->
    <selectType :visibleDialog.sync="visibleDialog" :title="title" :bizScene="formData.bizType"
      :treeIds="formData.extInfo.assetType" :loadTree.sync="loadTree" @selectTableData="addGoods" />
    <!-- 仓库选择弹框 -->
    <WarehousingDialog ref="wareHouseDailogRef" @selection="wareHouseSelection"></WarehousingDialog>
    <!-- 生产日期、采购日期弹框 -->
    <el-dialog :visible.sync="dateVisible" title="选择日期" width="400px">
      <el-date-picker size="small" v-model="batchTime" type="datetime" style="width: 320px"
        value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期">
      </el-date-picker>
      <div style="text-align: right; margin-top: 20px">
        <el-button @click="dateVisible = false">取消</el-button>
        <el-button type="primary" @click="dateConfirm" :disabled="!batchTime">确认</el-button>
      </div>
    </el-dialog>
    <outboundRequisitionDialog ref="outboundRequisitionDialogRef" @detailData="outboundRequisitionSelection" type="1"
      :bizType="formData.bizType" />
  </div>
</template>

<script>
import XLSX from 'xlsx';
import { mapActions, mapGetters } from 'vuex';
import outboundRequisitionDialog from '../components/outboundRequisitionDialog.vue';
import elTableInfiniteScroll from 'el-table-infinite-scroll';
import storageApi from '@/api/warehouseManagement/index.js';
import WarehousingDialog from '../components/WarehousingDialog.vue';
import { getCode } from '@/api/codeManagement/index.js';
import selectType from './components/selectType';
import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';
import {
  sceneState,
  qualityResultsOptions,
  qualityResults,
  qualityStatus
} from '@/utils/dict/index';
import { getTreeByGroup } from '@/api/classifyManage';
import outin from '@/api/warehouseManagement/outin';
import { deepClone } from '@/utils';
import BigNumber from 'bignumber.js';
import { isBoolean } from 'mathjs';
export default {
  components: {
    selectType,
    WarehousingDialog,
    outboundRequisitionDialog
  },
  // 虚拟列表滚动方法
  directives: {
    'el-table-infinite-scroll': elTableInfiniteScroll
  },
  data() {
    return {
      newColumns: [], // 动态表头
      sceneState,
      saveLoading: false,
      dateVisible: false,
      loadTree: true,
      visibleDialog: false,
      title: '选择产品',
      goodsLists: [],
      formData: {
        bizType: '',
        storageTime: '',
        extInfo: {
          assetType: []
        }
      },
      rules: {
        'extInfo.assetType': {
          required: true,
          message: '请选择物品类型',
          trigger: 'blur'
        },
        bizType: {
          required: true,
          message: '请选择入库场景',
          trigger: 'change'
        }
      },
      qualityResultsOptions, // 质检结果下拉选项 0无 1合格 2不合格
      qualityStatus, // 质检状态 0未检 1已检
      qualityResults, // 质检结果 0无 1合格 2不合格
      productList: [], // 产品列表
      packingList: [], // 包装列表
      showPackingList: [], // 包装列表(虚拟列表)
      materialList: [], // 物料列表
      showMaterialList: [], // 物料列表(虚拟列表)
      curDateType: 'productionDate',
      packingListSelected: [], // 包装选择列表
      isWrapTable: true, // 解决表格不刷新问题（包装）
      currentPackingQuantity: '', // 当前包装数量
      batchTime: '', // 生产日期、采购日期
      pageSize: 20, // 物料和包装列表条数
      pickingPageNum: 1, // 包装虚拟分页页数
      materielPageNum: 1, // 物料虚拟分页页数
      packingSpecificationOption: [], // 包装规格下拉
    };
  },
  computed: {
    ...mapGetters(['dict', 'getDict']),
    clientEnvironmentId() {
      return this.$store.state.user.info.clientEnvironmentId;
    }
  },
  watch: {
    packingList: {
      handler(newVal) {
        console.log('包装列表', newVal);
        console.log('当前包装列表加载页数', this.pickingPageNum);
        this.showPackingList = newVal.slice(
          0,
          this.pageSize * (this.pickingPageNum > 0 ? this.pickingPageNum : 1)
        );
        this.pickingPageNum = Math.ceil(
          this.showPackingList.length / this.pageSize
        );
      },
      deep: true
    },
    materialList: {
      handler(newVal) {
        console.log('物料列表', newVal);
        console.log('当前物料列表加载页数', this.materielPageNum);
        this.showMaterialList = newVal.slice(
          0,
          this.pageSize *
          (this.materielPageNum > 0 ? this.materielPageNum : 1)
        );
      },
      deep: true
    }
  },
  created() {
    if (this.$route.query.name == 'inboundRequests') {
      this.getProduct();
    }
    this.requestDict('不拆物料层规格');
    this.getFieldModel();
    this.getListItems();
    this.initUserInfo();
    this.getNowFormatDate();
    if (this.$route.query.id && !this.$route.query.name) {
      storageApi
        .getApplystorageDetailById(this.$route.query.id)
        .then(async (data) => {
          this.formData.extInfo.assetType = [data.rootCategoryLevelId];
          this.formData.bizType = String(data.type);
          this.formData.sourceBizNo = data.code;
          const batchNo = await getCode('lot_number_code');
          this.productList = data.detailList.map((item, index) => {
            return {
              index: this.productList.length + index,
              categoryId: item.categoryId, // 物品id
              categoryName: item.categoryName, // 物品名称
              categoryCode: item.categoryCode, // 物品编码
              categoryModel: item.modelType, // 物品型号
              specification: item.specification, // 规格
              brandNum: item.brandNum, // 牌号
              batchNo: batchNo, // 批次号
              minPackingQuantity: item.quantity, // 最小包装单元数量
              packingQuantity: 1, // 包装数量
              packingUnit: item.packingUnit, // 单位
              measureQuantity: 0, // 计量数量
              measureUnit: item.measuringUnit, // 计量单位
              netWeight: item.netWeight > -1 ? item.netWeight : 0, // 净重
              weight: item?.packingWeight || 0, // 重量
              weightUnit: item.weightUnit, // 重量单位
              totalMoney: '', // 总价
              unitPrice: item.unitPrice, // 单价
              purpose: item.purpose, // 用途
              isUnpack: item.isUnpack, // 是否允许拆包
              warehouseId: item.warehouseId, // 仓库Id
              warehouseName: item.warehouseName, // 仓库名称
              warehouseIds: [item.warehouseId],
              warehouseNames: [item.warehouseName]
            };
          });
          // this.$nextTick(() => {
          //   this.listSaveArrs();
          // });
        });
    }
    if (this.$route.query.detailId) {
      storageApi
        .getInboundDetailsById(this.$route.query.detailId)
        .then(async (data) => {
          this.formData.extInfo.assetType = data.extInfo.assetType.split(',');
          this.formData.bizType = String(data.bizType);
          const batchNo = await getCode('lot_number_code');
          this.productList = data.outInDetailList.map(
            (productItem, productIndex) => {
              return {
                ...productItem,
                index: this.productList.length + productIndex,
                isSave: true,
                batchNo: batchNo, // 批次号
                warehouseIds: [productItem.warehouseId], // 仓库Id
                warehouseNames: [productItem.warehouseName], // 仓库名称
                outInDetailRecordRequestList:
                  productItem.outInDetailRecordRequestList?.length > 0
                    ? productItem.outInDetailRecordRequestList.map(
                      (packingItem, packingIndex) => {
                        return {
                          ...packingItem,
                          index:
                            this.productList.length +
                            productIndex +
                            '-' +
                            packingIndex, // 包装索引
                          batchNo: batchNo, // 批次号
                          parentIndex:
                            this.productList.length + productIndex, // 物品索引
                          categoryName: productItem.categoryName,
                          categoryCode: productItem.categoryCode,
                          materialDetailList:
                            packingItem.materialDetailList.map(
                              (materialItem, materialIndex) => {
                                return {
                                  ...materialItem,
                                  index:
                                    this.productList.length +
                                    productIndex +
                                    '-' +
                                    packingIndex +
                                    '——' +
                                    materialIndex, // 包装索引
                                  parentIndex:
                                    this.productList.length +
                                    productIndex +
                                    '-' +
                                    packingIndex, // 物品索引
                                  batchNo: batchNo, // 批次号
                                  categoryName: productItem.categoryName,
                                  categoryCode: productItem.categoryCode
                                };
                              }
                            )
                        };
                      }
                    )
                    : []
              };
            }
          );
          console.log('this.productList-----------', this.productList);
          // 获取包装维度数据
          const arr = [];
          for (const key in this.productList) {
            for (const k in this.productList[key]
              .outInDetailRecordRequestList) {
              arr.push({
                ...this.productList[key].outInDetailRecordRequestList[k]
              });
            }
          }
          this.packingList = arr;
          // 获取物料维度数据
          let iArr = [];
          arr.forEach((item) => {
            item.materialDetailList.forEach((ele) => {
              iArr.push({ ...ele });
            });
          });
          this.materialList = iArr;
        });
    }
  },
  methods: {
    ...mapActions('dict', ['requestDict']),
    changeCount(number) {
      return new BigNumber(number).toString();
    },
    selectSupplier(val, row) {
      row.supplierId = val;
      row.supplierName = row.supplierListOptions.filter(
        (item) => item.id == val
      )[0].name;
      row.supplierCode = row.supplierListOptions.filter(
        (item) => item.id == val
      )[0].serialNo;
    },
    inputSingleWeight(row, index) {
      console.log(row, 'row1')
      if (row.singleWeight < 0) {
        this.$set(this.productList[index], 'singleWeight', 1);
      } else if (row.packingQuantity > 9999) {
        this.$set(this.productList[index], 'singleWeight', 9999);
      }
      console.log(row.singleWeight)
      console.log(row.measureQuantity)

      //重量
      if (row.measureType == '2') {
        if (row.packingUnit == 'KG') {

          const weight = Number(row.measureQuantity) * Number(row.singleWeight);
          this.$set(this.productList[index], 'weight', weight)
        } else {
          this.$set(this.productList[index], 'weight', measureQuantity)
        }
      }

      console.log(row, 'row2')

    },
    inputAllweight(row, index) {
      if (row.weight < 0) {
        this.$set(this.productList[index], 'weight', 1);
      }
      const singleWeight = Number(row.weight) / Number(row.measureQuantity);
      this.$set(this.productList[index], 'singleWeight', singleWeight)
    },
    // 仓库选择
    wareHouseSelection(val, index) {
      console.log('仓库选择', val);
      let arr = this.productList[index].outInDetail
    },
    // 计算最小单元数量
    async computeNum(row, index, isClear) {
      console.log('row, index', row, index);

      // 清空仓库(包装数量输入)
      if (isClear) {
        if (row.packingQuantity < 0) {
          this.$set(this.productList[index], 'packingQuantity', 1);
        } else if (row.packingQuantity > 999999) {
          this.$set(this.productList[index], 'packingQuantity', 999999);
        }
      }
      //如果有包装数量和包装单位
      if (row.packingQuantity && row.packingUnit) {

        //获取仓库
        const res = await warehouseDefinition.list({
          inventoryType: row?.categoryLevelPathIdParent
        });
        // 只有一个仓库自动显示出来
        if (res.length == 1) {
          let name = res[0]?.factoryName + '-' + res[0]?.name;
          console.log('仓库-----------------------------', res);
          this.$set(this.productList[index], 'warehouseId', res[0].id);
          this.$set(this.productList[index], 'warehouseName', name);

          let table1 = [];
          table1.push({
            measureQuantity: row.measureQuantity,
            packingQuantity: row.packingQuantity,
            warehouseName: name,
            warehouseId: res[0].id
          });

          this.wareHouseSelection(table1, index);
        } else {
          this.$set(this.productList[index], 'warehouseId', '');
          this.$set(this.productList[index], 'warehouseName', '');
        }
        // -----------------------------------------------------------------
        let startIndex = row.packingSpecificationOption.findIndex((ite) => {

          return (
            row.measuringUnit == ite.packingUnit &&
            ite.packingUnit != ite.conversionUnit
          );
        });
        let endIndex = row.packingSpecificationOption.findIndex(
          (ite) => row.packingUnit == ite.conversionUnit
        );

        console.log(row, 'rowwwwwwwwwwwwww')


        let total = Number(row.packingQuantity);
        //计量数量
        row.measureQuantity = this.changeCount(total);
        console.log(total, '包装数量')

        if (row.packingUnit == row.measureUnit) {
          // total = Number(row.packingQuantity) * row.netWeight;
          console.log(total, '22')
        } else {
          let num = 0;
          for (; startIndex < endIndex; endIndex--) {
            // total = 
            num = this.$math.format(
              row.packingSpecificationOption[endIndex].packageCell * total,
              14
            );
          }
          console.log(num, 'numnumnum')
          total = Number(num);
          console.log(total, '333')
        }

        // 判断单位和计量单位是否为不拆物料层规格
        let packingBoolen = !!this.getDict('不拆物料层规格', row.packingUnit)
          .dictValue;
        let measureBoolen = !!this.getDict('不拆物料层规格', row.measureUnit)
          .dictValue;
        console.log(packingBoolen, 'packingBoolen')
        console.log(measureBoolen, 'measureBoolen')

        if (packingBoolen && measureBoolen && row.packingUnit != 'L') {

          console.log(total, '55555')
          this.$set(this.productList[index], 'weight', total);
          if (row.packingUnit == row.measureUnit) {
            this.$set(this.productList[index], 'measureQuantity', row.packingQuantity)
          }
        } else {
          console.log(row, 'row')
          if (row.measureType != 1) {
            if (row.packingUnit == 'KG') {
              if (row.packingUnit == row.measureUnit) {
                this.$set(this.productList[index], 'weight', row.measureQuantity)
              } else {
                const weight = total * Number(row.singleWeight);
                this.$set(this.productList[index], 'weight', weight)
              }
              console.log(total, '66')
            } else {
              const weight = row.measureQuantity * Number(row.singleWeight);
              this.$set(this.productList[index], 'weight', weight)
              console.log(total, '77')
            }
          } else {
            const weight = total * Number(row.singleWeight);
            this.$set(this.productList[index], 'weight', weight)
            console.log(total, '8')
          }
        }
        this.$set(this.productList[index], 'measureQuantity', total)
      }
    },
    //出入库申请列表操作直接入库
    getProduct() {
      let aaa = [this.$route.query.inId];
      console.log(aaa, '出入库申请入库操作直接入库');
      storageApi.getApplystoragedetails(aaa).then(async (res) => {
        if (this.$route.query.type == 2) {
          // 出库
          let data = await storageApi.getHierarchyFifo({
            type: 1,
            builders: res.map((item) => {
              return {
                categoryId: item.categoryId,
                num: item.measureQuantity
              };
            })
          });
          if (data?.length > 0) {
            this.outboundRequisitionSelection(data, 1, {
              sourceBizNo: this.$route.query.code,
              bizType: this.$route.query.sourceType,
              assetType: Array.from(
                new Set(res.map((item) => item.rootCategoryLevelId))
              ).join(',')
            });
          } else {
            this.$message.warning('该出库申请单无库存');
          }
        } else {
          // 入库
          const batchNo = await getCode('lot_number_code');
          console.log(res, '入库');
          let data = res.map((item, index) => {
            return {
              ...item,
              index,
              batchNo,
              id: '',
              warehouseIds: [item.warehouseId],
              warehouseNames: [item.warehouseName]
            };
          });
          this.outboundRequisitionSelection(data, 1, {
            sourceBizNo: this.$route.query.code,
            bizType: this.$route.query.sourceType,
            assetType: Array.from(
              new Set(res.map((item) => item.rootCategoryLevelId))
            ).join(',')
          });
        }
      });
    },
    async outboundRequisitionSelection(data, dimension, query) {
      console.log('data-----------', data);
      console.log('query-----------', query);
      console.log(this.formData.bizType, 'bbbbbtype')
      if (this.formData.bizType != 10) {

        this.formData.sourceBizNo = query.sourceBizNo;
        this.formData.bizType = query.bizType;
        this.formData.extInfo.assetType = query.assetType.split(',');
        const batchNo = await getCode('lot_number_code');
        // 获取包装规格
        let packingSpecification =
          await storageApi.getCategoryPackageDisposition({
            categoryIds: data.map((item) => item.categoryId)
          });
        this.packingSpecificationOption = data.map((item) => {
          return packingSpecification
            .filter((ite) => item.categoryId == ite.categoryId)
            .sort((a, b) => a.sort - b.sort);
        });
        console.log(
          'this.packingSpecificationOption------------------------------------------包装组',
          this.packingSpecificationOption
        );
        console.log(data, 'datadatadatadatadata');
        data.map((productItem, productIndex) => {
          // 显示规格
          let packingSpecificationLabel = this.packingSpecificationOption[
            productIndex
          ]
            .map((item) => {
              if (item.sort > 0) {
                return `${item.packageCell}${item.packageUnit}/${item.conversionUnit}`;
              }
            })
            .filter((item) => !!item);

          // let r= {
          // ...productItem,
          console.log(productItem, 'productItem')
          productItem.weight = productItem.weight ? Number(productItem.weight) : 0;
          // productItem.singleWeight = 0;
          productItem.measureUnit = productItem.measuringUnit; // 计量单位

          productItem.index = this.productList.length + productIndex;
          productItem.isSave =
            productItem.outInDetailRecordRequestList?.length > 0
              ? true
              : false;
          productItem.netWeight =
            productItem.netWeight > 0 ? productItem.netWeight : 0;
          productItem.materielCode = productItem.materielCode;
          productItem.categoryModel = productItem.modelType; // 物品型号
          productItem.specification = productItem.specification; // 规格
          productItem.batchNo = batchNo; // 批次号
          productItem.warehouseIds = [productItem.warehouseId]; // 仓库Id
          productItem.warehouseNames = [productItem.warehouseName]; // 仓库名称
          productItem.packingSpecificationOption =
            this.packingSpecificationOption[productIndex]; // 包装规格选项
          productItem.packingSpecificationLabel = packingSpecificationLabel; // 包装规格显示
          productItem.outInDetailRecordRequestList =
            productItem.outInDetailRecordRequestList?.length > 0
              ? productItem.outInDetailRecordRequestList.map(
                (packingItem, packingIndex) => {
                  return {
                    ...packingItem,
                    index:
                      this.productList.length +
                      productIndex +
                      '-' +
                      packingIndex, // 包装索引
                    batchNo: batchNo, // 批次号
                    parentIndex: this.productList.length + productIndex, // 物品索引
                    categoryName: productItem.categoryName,
                    categoryCode: productItem.categoryCode,
                    materialDetailList:
                      packingItem.materialDetailList.map(
                        (materialItem, materialIndex) => {
                          return {
                            ...materialItem,
                            index:
                              this.productList.length +
                              productIndex +
                              '-' +
                              packingIndex +
                              '——' +
                              materialIndex, // 包装索引
                            parentIndex:
                              this.productList.length +
                              productIndex +
                              '-' +
                              packingIndex, // 物品索引
                            batchNo: batchNo, // 批次号
                            categoryName: productItem.categoryName,
                            categoryCode: productItem.categoryCode
                          };
                        }
                      )
                  };
                }
              )
              : [];
        });

        // this.productList = data;
        this.productList = data.map((item) => {
          if (item.weight === null || item.weight === undefined) {
            item.weight = 0;
          }
          if (this.formData.bizType == 4) {
            item.packingUnit = '箱'
          } else {
            item.packingUnit = ''
          }
          return item;
        });
        console.log(this.productList, 'productList')
        // this.productList.map((v) => {
        //   v.weight = isNaN(v.weight);
        // });

        // 获取包装维度数据
        const arr = [];
        for (const key in this.productList) {
          for (const k in this.productList[key]
            .outInDetailRecordRequestList) {
            arr.push({
              ...this.productList[key].outInDetailRecordRequestList[k]
            });
          }
        }
        this.packingList = arr;
        // 获取物料维度数据
        let iArr = [];
        arr.forEach((item) => {
          item.materialDetailList.forEach((ele) => {
            iArr.push({ ...ele });
          });
        });
        this.materialList = iArr;
      } else {
        this.selWWData = query;
        this.$set(this.formData, 'sourceBizNo', query.sourceBizNo);
      }
    },
    // 获取动态表头
    getFieldModel() {
      storageApi.fieldModel({ fieldModel: 't_main_category' }).then((res) => {
        let newRes = res.map((m) => {
          return {
            prop: 'extField.' + m.prop,
            label: m.label,
            align: 'center',
            showOverflowTooltip: true
          };
        }).filter(item => item.label !== '包装规格');

        console.log(newRes, 'newRes');
        this.newColumns = [...newRes];
      });
    },
    // 初始化当前用户信息
    async initUserInfo() {
      const res = await warehouseDefinition.tree();
      let info = JSON.parse(localStorage.getItem('info'));
      console.log(info, 'infoinfoinfo')
      let obj = res.find(
        (item) => item.id === info.deptIds[info.deptIds.length - 1]
      );
      // if (!obj) return;

      if (obj) {
        console.log(obj, 'objobjobjobjobjobjobjobjobjobjobjobjobjobjobjobjobj')

        this.formData.extInfo.deptCode = obj?.id;
        this.formData.extInfo.deptName = obj?.name;
      } else {
        this.formData.extInfo.deptName = info.deptName ? info.deptName : info.groupName ? info.groupName : '';

      }

      this.formData.extInfo.createUserName = info.name;
      this.formData.createUserId = info.userId;
    },
    // 获取当前时间函数
    getNowDate() {
      let date = new Date(),
        obj = {
          year: date.getFullYear(), //获取完整的年份(4位)
          month: date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
          strDate: date.getDate(), // 获取当前日(1-31)
          hour: date.getHours(), //获取当前小时(0 ~ 23)
          minute: date.getMinutes(), //获取当前分钟(0 ~ 59)
          second: date.getSeconds() //获取当前秒数(0 ~ 59)
        };
      Object.keys(obj).forEach((key) => {
        if (obj[key] < 10) obj[key] = `0${obj[key]}`;
      });
      return obj;
    },
    // 赋值入库时间
    getNowFormatDate() {
      let obj = this.getNowDate();
      this.formData.storageTime = `${obj.year}-${obj.month}-${obj.strDate} ${obj.hour}:${obj.minute}:${obj.second}`;
    },
    // 获取物品列表
    async getListItems() {
      const res2 = await warehouseDefinition.getTreeByGroup({ type: 2 });
      this.goodsLists = res2;
    },
    // 打开单据来源弹窗
    openDocumentSourceDialog() {
      console.log('打开单据来源弹窗');
      this.$refs.outboundRequisitionDialogRef.open();
    },
    // 清除单据来源
    clearSourceBizNo() {
      this.formData.sourceBizNo = '';
    },
    // 返回
    back() {
      this.$router.go(-1);
    },
    // 添加产品
    addProduct() {
      if (this.formData.extInfo.assetType.length <= 0) {
        return this.$message.error('请选择物品类型');
      }
      if (!this.formData.bizType) {
        return this.$message.error('请选择入库类型');
      }
      this.visibleDialog = true;
    },
    // 键盘移动
    moveFocus(event, index, key, type, row) {
      let keyfield = [];
      let listLength = 0;
      switch (type) {
        case '产品':
          listLength = this.productList.length;
          keyfield = ['batchNo', 'packingQuantity', 'unitPrice', 'purpose'];
          break;
        case '包装':
          listLength = this.showPackingList.length;
          if (row.measureUnit != row.weightUnit) {
            keyfield = [
              'packing_materielDesignation',
              'packing_clientCode',
              'packing_engrave',
              'packing_weight'
            ];
          } else {
            keyfield = [
              'packing_materielDesignation',
              'packing_clientCode',
              'packing_engrave'
            ];
          }
          break;
        case '物料':
          listLength = this.showMaterialList.length;
          if (row.measureUnit != row.weightUnit) {
            keyfield = [
              'material_materielDesignation',
              'material_clientCode',
              'material_engrave',
              'material_weight'
            ];
          } else {
            keyfield = [
              'material_materielDesignation',
              'material_clientCode',
              'material_engrave'
            ];
          }
          break;
      }

      if (event.keyCode === 13) {
        // 回车
        if (
          index === listLength - 1 &&
          key === keyfield[keyfield.length - 1]
        ) {
          // 最后一行最后一个
          return;
        }

        this.$refs[key + index].blur();
        if (key === keyfield[keyfield.length - 1]) {
          // 当前行最后一个,跳转下一行第一个
          if (this.$refs[keyfield[0] + (index + 1)].value == 0) {
            this.$refs[keyfield[0] + (index + 1)].value = '';
          }
          this.$refs[keyfield[0] + (index + 1)].focus();
        } else {
          // 跳转下一个
          const nextkeyindex = keyfield.findIndex((k) => k === key) + 1;
          this.$nextTick(() => {
            if (this.$refs[keyfield[nextkeyindex] + index].value == 0) {
              this.$refs[keyfield[nextkeyindex] + index].value = '';
            }
            this.$refs[keyfield[nextkeyindex] + index].focus();
          });
        }
      }

      // 向上 =38
      if (event.keyCode === 38) {
        console.log('向上');
        if (index === 0) {
          // 第一行
          console.log('第一行无法向上');
          return;
        }
        this.$refs[key + index].blur();
        this.$nextTick(() => {
          if (this.$refs[key + (index - 1)].value == 0) {
            this.$refs[key + (index - 1)].value = '';
          }
          this.$refs[key + (index - 1)].focus();
        });
      }

      // 下 = 40
      if (event.keyCode === 40) {
        console.log('向下');
        if (index === listLength - 1) {
          // 最后一行
          console.log('最后一行无法向下');
          return;
        }
        this.$refs[key + index].blur();
        this.$nextTick(() => {
          if (this.$refs[key + (index + 1)].value == 0) {
            this.$refs[key + (index + 1)].value = '';
          }
          this.$refs[key + (index + 1)].focus();
        });
      }

      // 左 = 37
      if (event.keyCode === 37) {
        console.log('向左');
        if (index === 0 && key === keyfield[0]) {
          // 第一行第一个
          console.log('第一行第一个无法向左');
          return;
        }
        this.$refs[key + index].blur();
        if (key === keyfield[0]) {
          if (
            this.$refs[keyfield[keyfield.length - 1] + (index - 1)].value == 0
          ) {
            this.$refs[keyfield[keyfield.length - 1] + (index - 1)].value =
              '';
          }
          // 当前行第一个,跳转上一行最后一个
          this.$refs[keyfield[keyfield.length - 1] + (index - 1)].focus();
        } else {
          // 跳转上一个
          const prevkeyindex = keyfield.findIndex((k) => k === key) - 1;
          this.$nextTick(() => {
            if (this.$refs[keyfield[prevkeyindex] + index].value == 0) {
              this.$refs[keyfield[prevkeyindex] + index].value = '';
            }
            this.$refs[keyfield[prevkeyindex] + index].focus();
          });
        }
      }

      // 右 = 39
      if (event.keyCode === 39) {
        console.log('向右');
        if (
          index === listLength - 1 &&
          key === keyfield[keyfield.length - 1]
        ) {
          // 最后一行最后一个
          console.log('最后一行最后一个无法向左');
          return;
        }
        console.log(this.$refs);
        this.$refs[key + index].blur();
        if (key === keyfield[keyfield.length - 1]) {
          // 当前行最后一个,跳转下一行第一个
          if (this.$refs[keyfield[0] + (index + 1)].value == 0) {
            this.$refs[keyfield[0] + (index + 1)].value = '';
          }
          this.$refs[keyfield[0] + (index + 1)].focus();
        } else {
          // 跳转下一个
          const nextkeyindex = keyfield.findIndex((k) => k === key) + 1;
          this.$nextTick(() => {
            if (this.$refs[keyfield[nextkeyindex] + index].value == 0) {
              this.$refs[keyfield[nextkeyindex] + index].value = '';
            }
            this.$refs[keyfield[nextkeyindex] + index].focus();
          });
        }
      }
    },
    handleAvatarSuccess() {
      this.$refs.fileUploadBtn.clearFiles(); //上传成功之后清除历史记录**加粗样式**
    },
    async onChange(file) {
      console.log(XLSX);
      this.warehousingMaterialList = [];
      this.resultArray = [];
      const loading = this.$loading({
        lock: true,
        text: '加载中...'
      });
      /**
       * 1. 使用原生api去读取好的文件
       * */
      // console.log("原始上传的文件", file);
      // 读取文件不是立马能够读取到的，所以是异步的，使用Promise
      let dataBinary = await new Promise((resolve) => {
        // Web API构造函数FileReader，可实例化对象，去调用其身上方法，去读取解析文件信息
        let reader = new FileReader(); // https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
        // console.log("实例化对象有各种方法", reader);
        reader.readAsBinaryString(file.raw); // 读取raw的File文件
        reader.onload = (ev) => {
          // console.log("文件解析流程进度事件", ev);
          resolve(ev.target.result); // 将解析好的结果扔出去，以供使用
        };
      });
      // console.log("读取出的流文件", dataBinary);

      /**
       * 2. 使用xlsx插件去解析已经读取好的二进制excel流文件
       * */
      let workBook = XLSX.read(dataBinary, {
        type: 'binary',
        cellDates: true
      });
      // excel中有很多的sheet，这里取了第一个sheet：workBook.SheetNames[0]
      let firstWorkSheet = workBook.Sheets[workBook.SheetNames[0]];
      // 分为第一行的数据，和第一行下方的数据
      // const header = this.getHeaderRow(firstWorkSheet);
      // console.log('读取的excel表头数据（第一行）', header);
      const xlsxData = XLSX.utils.sheet_to_json(firstWorkSheet);
      console.log('读取所有excel数据', xlsxData);
      // let modelTypeList = xlsxData.map((item) => {
      //   return item['型号'];
      // });
      // let nameList = xlsxData.map((item) => {
      //   return item['物品名称'];
      // });
      let codeList = xlsxData.map((item) => {
        return item['sap物料码'];
      });
      let functionType = {};
      xlsxData.map((item) => {
        functionType[item['sap物料码']] = item['采购原因'];
      });
      this.formData.extInfo.assetType = ['6']; //备品备件
      this.formData.bizType = '2'; // 采购入库
      outin
        .getListByNameOrModeType({
          // modelTypeList,
          // nameList,
          codeList,
          categoryLevelId: '6'
        })
        .then(async (data) => {
          console.log('查询到的备件数据', data);
          const batchNo = await getCode('lot_number_code');
          // 添加包装数量和最小包装单元
          this.productList = data.map((item, index) => {
            console.log(xlsxData);
            let filterArray = xlsxData.filter(
              (xlsxItem) => xlsxItem['sap物料码'] == item.code
            );
            console.log(filterArray);
            return {
              index: this.productList.length + index,
              categoryId: item.id, // 物品id
              categoryName: item.name, // 物品名称
              categoryCode: item.code, // 物品编码
              categoryModel: item.modelType, // 物品型号
              specification: item.specification, // 规格
              brandNum: item.brandNum, // 牌号
              batchNo: batchNo, // 批次号
              minPackingQuantity: 1, // 最小包装单元数量
              packingQuantity: filterArray[0]['数量'], // 包装数量
              packingUnit: item.packingUnit, // 单位
              measureQuantity: 0, // 计量数量
              measureUnit: item.measuringUnit, // 计量单位
              netWeight: item.netWeight > -1 ? item.netWeight : 0, // 净重
              weight: 0, // 重量
              weightUnit: item.weightUnit, // 重量单位
              totalMoney: '', // 总价
              unitPrice: item.unitPrice, // 单价
              purpose: functionType[item.code], // 用途
              isUnpack: item.isUnpack // 是否允许拆包
            };
          });
          console.log(this.productList);
          this.handleAvatarSuccess();
          loading.close();
        })
        .catch(() => {
          loading.close();
        });
    },
    // 入库
    storage() {
      let boolen = this.productList.every((item) => item.isSave);
      if (!boolen) {
        this.$message.warning('请先保存所有产品信息');
        return;
      }
      // 处理包装数据
      this.packingList = this.packingList.map((packingItem) => {
        return {
          ...packingItem,
          materialDetailList: this.materialList.filter(
            (item) => item.parentIndex === packingItem.index
          ),
          taskId: this.selWWData?.taskId,
          workOrderId: this.selWWData?.workOrderId
        };
      });
      // 处理产品数据
      this.productList = this.productList.map((productItem) => {
        return {
          ...productItem,
          outInDetailRecordRequestList: this.packingList.filter(
            (item) => item.parentIndex === productItem.index
          )
        };
      });
      this.formData.outInDetailList = this.productList;
      let obj = deepClone(this.formData);
      // 处理物品类型assetType
      obj.extInfo.assetType = obj.extInfo.assetType.join(',');
      // 处理仓库id
      let warehouseId = [];
      let warehouseName = [];
      let warehouseIds = this.productList
        .map((item) => item.warehouseIds)
        .flat();
      let warehouseNames = this.productList
        .map((item) => item.warehouseNames)
        .flat();
      warehouseIds.forEach((item, index) => {
        if (!warehouseId.includes(item)) {
          warehouseId.push(item);
          warehouseName.push(warehouseNames[index]);
        }
      });
      obj.warehouseIds = warehouseId;
      obj.warehouseNames = warehouseName;

      console.log('入库数据', obj);

      // 是否需要审核(0审核 1跳过审核)
      if (obj.bizType == '12') {
        obj.isSkip = 1;
      } else {
        obj.isSkip = 0;
      }
      // obj.isSkip = 1;
      this.saveLoading = true;
      console.log(obj, 'objobjobjobjobjobj');

      storageApi
        .storage(obj)
        .then(async (res) => {
          console.log('入库成功', res);
          if (res.code == 0) {
            try {
              // 委外入库（非采购）
              if (obj.bizType == '12') {
                await storageApi.qualityInspectionTwo({
                  outInId: res.data[0]
                });
              } else {
                await storageApi.submitTwo({ outInId: res.data[0] });
              }
              this.$message.success('入库成功');
              this.saveLoading = false;
              this.$router.push('/warehouseManagement/stockManagement');
            } catch (error) {
              this.saveLoading = false;
              console.log('提交流程失败', error);
            }
          }
        })
        .catch((err) => {
          console.log('入库失败', err);
          this.saveLoading = false;
        });
    },
    pickingHandleScroll() {
      // console.log('---------pickingHandleScroll------------');
      // console.log(this.packingList);
      // console.log(this.showPackingList);
      // console.log(this.pageSize);
      if (this.showPackingList.length < this.packingList.length) {
        if (this.packingList.length > this.pageSize) {
          this.pickingPageNum += 1;
        }
        this.pickingFetchData();
      }
    },
    pickingFetchData() {
      const start = (this.pickingPageNum - 1) * this.pageSize;
      const end = start + this.pageSize;
      console.log(start);
      console.log(end);
      this.showPackingList = this.showPackingList.concat(
        this.packingList.slice(start, end)
      );
    },
    materielHandleScroll() {
      console.log('---------materielHandleScroll------------');
      if (this.showMaterialList.length < this.materialList.length) {
        if (this.materialList.length > this.pageSize) {
          this.materielPageNum += 1;
        }
        this.materielFetchData();
      }
    },
    materielFetchData() {
      const start = (this.materielPageNum - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.showMaterialList = this.showMaterialList.concat(
        this.materialList.slice(start, end)
      );
      console.log(this.showMaterialList);
    },
    // 日期选择
    dateConfirm() {
      this.packingListSelected.forEach((item) => {
        this.$set(item, this.curDateType, this.batchTime);
      });
      this.batchTime = '';
      this.dateVisible = false;
    },
    // 包装重量修改
    packingWeightCahnge(value, row) {
      // 修改物品重量
      let filterPackingList = this.packingList.filter((item) => {
        return item.parentIndex === row.parentIndex;
      });
      let productIndex = this.productList.findIndex((item) => {
        return item.index === row.parentIndex;
      });
      let totalWeight = filterPackingList.reduce(
        (accumulator, currentValue) => {
          return this.$math.format(+accumulator + +currentValue.weight, 14);
        },
        0
      );
      this.$set(this.productList[productIndex], 'weight', totalWeight);
      this.$set(
        this.productList[productIndex],
        'singleWeight',
        totalWeight / this.productList[productIndex].measureQuantity
      );
      // 修改拆分物料
      this.materialList.map((item, index) => {
        if (item.parentIndex === row.index) {
          console.log(value / row.measureQuantity);
          this.$set(
            this.materialList[index],
            'weight',
            this.$math.format(value / row.measureQuantity, 14) >= 0
              ? this.$math.format(value / row.measureQuantity, 14)
              : 0
          );
        }
      });
    },
    // 物料重量修改
    materialWeightCahnge(row) {
      // 修改包装重量
      let filterMaterialList = this.materialList.filter((item) => {
        return item.parentIndex === row.parentIndex;
      });
      let packingIndex = this.packingList.findIndex((item) => {
        return item.index === row.parentIndex;
      });
      let totalMaterialWeight = filterMaterialList.reduce(
        (accumulator, currentValue) => {
          return this.$math.format(+accumulator + +currentValue.weight, 14);
        },
        0
      );
      this.$set(
        this.packingList[packingIndex],
        'weight',
        totalMaterialWeight
      );
      // 修改物品重量
      let filterPackingList = this.packingList.filter((item) => {
        return (
          item.parentIndex === this.packingList[packingIndex].parentIndex
        );
      });
      let productIndex = this.productList.findIndex((item) => {
        return item.index === this.packingList[packingIndex].parentIndex;
      });
      let totalWeight = filterPackingList.reduce(
        (accumulator, currentValue) => {
          return this.$math.format(+accumulator + +currentValue.weight, 14);
        },
        0
      );
      this.$set(this.productList[productIndex], 'weight', totalWeight);
    },
    // 包装质检结果修改
    packingResultCahnge(value, row) {
      // 修改物料质检结果( 1合格 2不合格)
      this.materialList.map((item, index) => {
        if (item.parentIndex === row.index) {
          this.$set(this.materialList[index], 'result', value);
        }
      });
    },
    // 物料质量结果修改
    materialResultCahnge(value, row) {
      // 修改包装质检结果
      let filterMaterialList = this.materialList.filter((item) => {
        return item.parentIndex == row.parentIndex;
      });
      let packingIndex = this.packingList.findIndex((item) => {
        return item.index == row.parentIndex;
      });
      let boolen = filterMaterialList.every((item) => {
        return item.result == 1;
      });
      this.$set(this.packingList[packingIndex], 'result', boolen ? 1 : 2);
    },
    // 重量限制
    weightInput(value, row, type) {
      const newValue = value.replace(/[^\d.]/g, ''); // 保留数字和小数点
      const decimalCount = (newValue.match(/\./g) || []).length; // 计算小数点的个数
      if (row.weight < 0) {
        row.weight = 0;
      } else if (row.weight > 9999) {
        row.weight = 9999;
      } else {
        if (decimalCount > 1) {
          // 如果小数点个数大于1，移除多余的小数点
          const lastIndex = newValue.lastIndexOf('.');
          row.weight =
            newValue.slice(0, lastIndex) + newValue.slice(lastIndex + 1);
        } else if (decimalCount === 1) {
          // 如果小数点个数等于1，允许小数点的输入
          row.weight = newValue;
        } else {
          row.weight = newValue === '' ? 0 : parseFloat(newValue); // 如果输入为空，则设为0
        }
      }
      if (type === '包装') {
        this.packingWeightCahnge(value, row);
      } else {
        this.materialWeightCahnge(row);
      }
    },
    //计算金额
    calcSumTotal(measureQuantity, unitPrice, row) {
      //最小包装单元,包装数量,单价
      console.log(measureQuantity, unitPrice, ';;;;;;;;;;')
      const total = {
        measureQuantity: Number(measureQuantity > 0 ? measureQuantity : 0),
        unitPrice: Number(unitPrice > 0 ? unitPrice : 0)
      };
      let number = Number(
        this.$math.format(total.measureQuantity * total.unitPrice, 14)
      );

      row.totalMoney = number;
      console.log(number, 'number')
      return number;
    },

    // 包装维度最小包装单元改变——>总重量
    minPackingQuantityChange(row, value, index) {
      console.log(value);
      if (row.measureUnit !== 'KG') {
        if (value.replace(/^(0+)|[^\d]+/g, '') > 9999) {
          this.$set(this.productList[index], 'minPackingQuantity', 9999);
        } else {
          this.$set(
            this.productList[index],
            'minPackingQuantity',
            value.replace(/^(0+)|[^\d]+/g, '')
          );
        }
      } else {
        if (value < 1) {
          this.$set(this.productList[index], 'minPackingQuantity', 1);
        } else if (value > 9999) {
          this.$set(this.productList[index], 'minPackingQuantity', 9999);
        }
      }
      if (row.packingQuantity >= 0 && value >= 0) {
        this.packNum(row, row.packingQuantity, index);
      }
    },
    // 包装数量过滤处理改变——>总重量
    packNum(row, value, index) {
      const total = {
        minPackingQuantity: Number(
          row.minPackingQuantity > 0
            ? row.minPackingQuantity > 9999
              ? 9999
              : row.minPackingQuantity
            : 0
        ),
        packingQuantity: Number(
          row.packingQuantity > 0
            ? row.packingQuantity > 9999
              ? 9999
              : row.packingQuantity
            : 0
        )
      };
      const totals = Number(
        this.$math.format(
          total.minPackingQuantity * total.packingQuantity,
          14
        )
      );
      if (row.measureUnit == row.weightUnit) {
        row.weight = Number(
          this.$math.format(
            total.minPackingQuantity *
            1 *
            Number(total.packingQuantity).toFixed(2),
            14
          )
        );
      } else {
        row.weight = Number(
          this.$math.format(
            totals *
            (row.netWeight > 0 ? Number(row.netWeight).toFixed(2) : 0),
            14
          )
        );
      }
      this.$set(this.productList[index], 'measureQuantity', totals);
      // 清空仓库
      this.$set(this.productList[index], 'warehouseId', '');
      this.$set(this.productList[index], 'warehouseName', '');
      if (value.replace(/^(0+)|[^\d]+/g, '') > 9999) {
        this.$set(this.productList[index], 'packingQuantity', 9999);
      } else {
        this.$set(
          this.productList[index],
          'packingQuantity',
          value.replace(/^(0+)|[^\d]+/g, '')
        );
      }
      // return (row.packingQuantity = value.replace(/^(0+)|[^\d]+/g, ''));
    },
    // 表格样式
    rowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 1) {
        return {
          display: 'none',
          background: '#EEEEEE'
        };
      }
      return { background: '#0000' };
    },
    getNewSpecificationOption(packingSpecificationOption) {
      return packingSpecificationOption.map(arr => {
        return arr.reduce((acc, current) => {
          const conversionUnit = current.conversionUnit;
          if (!acc.some(item => item.conversionUnit === conversionUnit)) {
            acc.push(current);
          }
          return acc;
        }, []);
      });
    },
    async addGoods(data) {
      if (data.length === 0) return this.$message.warning('请选择产品信息')
      console.log(data, 'datadatadatadatadatadatadata111')

      // 获取批次号
      const batchNo = await getCode('lot_number_code');
      // 获取供应商
      const supplierList = await storageApi.contactQueryByCategoryIdsAPI({
        categoryIds: data.map((item) => item.id)
      });
      console.log(supplierList, '供应商列表');
      // 获取包装规格
      let packingSpecification =
        await storageApi.getCategoryPackageDisposition({
          categoryIds: data.map((item) => item.id)
        });

      console.log(packingSpecification, 'packingSpecification')

      this.packingSpecificationOption = data.map((item) => {
        return packingSpecification
          .filter((ite) => item.id == ite.categoryId)
          .sort((a, b) => a.sort - b.sort);
      });
      console.log('yeyyeyey----------------', data);

      const newSpecificationOption = this.getNewSpecificationOption(this.packingSpecificationOption)

      let productList = data.map((item, index) => {
        // 显示规格
        let packingSpecificationLabel = this.packingSpecificationOption[index]
          .map((item) => {
            if (item.sort > 0) {
              return `${item.packageCell}${item.packageUnit}/${item.conversionUnit}`;
            }
          })
          .filter((item) => !!item);

        return {
          index:
            this.productList.length - 1 > -1
              ? this.productList[this.productList.length - 1].index +
              index +
              1
              : this.productList.length + index,

          // extField: {
          //   packingSpecification: item.extField.packingSpecification
          // }, // 包装规格
          categoryId: item.id, // 物品id
          categoryName: item.name, // 物品名称
          categoryCode: item.code, // 物品编码
          categoryModel: item.modelType, // 物品型号
          specification: item.specification, // 规格
          brandNum: item.brandNum, // 牌号
          batchNo: batchNo, // 批次号
          supplierListOptions: supplierList[item.id], // 供应商列表
          supplierId: '', // 供应商id
          supplierName: '', // 供应商名称
          supplierCode: '',
          measureType: item.measureType, // 计量类型
          approvalNumber: item.approvalNumber, // 批准文号
          packingSpecification: item.packingSpecification, // 包装规格
          packingSpecificationOption: newSpecificationOption[index], // 包装规格选项
          packingSpecificationLabel: packingSpecificationLabel, // 包装规格显示
          minPackingQuantity: '', // 最小包装单元数量
          packingQuantity: '', // 包装数量
          packingUnit: '', // 单位
          measureQuantity: 0, // 计量数量
          measureUnit: item.measuringUnit, // 计量单位
          netWeight: item.netWeight > -1 ? item.netWeight : 0, // 净重
          weight: 0, // 重量
          singleWeight: item.netWeight, //单重  进来获取净重
          weightUnit: item.weightUnit, // 重量单位
          totalMoney: '', // 总价
          unitPrice: item.unitPrice, // 单价
          purpose: '', // 用途
          isUnpack: item.isUnpack, // 是否允许拆包
          categoryLevelPathIdParent: item.categoryLevelPathIdParent
        };
      });
      this.productList = this.productList.concat(productList);
      console.log('this.productList--------', this.productList);
    },
    // 物品保存验证表单（批量）
    validateForm() {
      return new Promise(async (resolve, reject) => {
        let list = this.productList.map(async (row, index) => {
          let fileds = [
            `productList.${index}.batchNo`,
            `productList.${index}.packingQuantity`,
            `productList.${index}.packingUnit`,
            `productList.${index}.warehouseId`
          ];
          console.log(fileds);
          if (row.isSave) {
            return Promise.resolve(true);
          } else {
            return await Promise.all(
              fileds.map(
                (item) =>
                  new Promise(async (res, rej) => {
                    this.$refs.productListRef.validateField(item, (err) => {
                      if (err) {
                        rej(err);
                      } else {
                        res(true);
                      }
                    });
                  })
              )
            );
          }
        });
        console.log(list);
        Promise.all(list)
          .then(() => {
            console.log('保存成功！');
            resolve();
          })
          .catch((err) => {
            console.log('保存失败！');
            this.$message.error('请填入必填项！');
            reject(err);
          });
      });
    },
    // 产品批量保存
    // async listSaveArrs() {
    //   this.validateForm()
    //     .then(async () => {
    //       // 批量获取包装编码并处理
    //       let packingCodePrams = this.productList.map((row) => {
    //         // 判断单位和计量单位是否为不拆物料层规格
    //         let packingBoolen = !!this.getDict(
    //           '不拆物料层规格',
    //           row.packingUnit
    //         ).dictValue;
    //         let measureBoolen = !!this.getDict(
    //           '不拆物料层规格',
    //           row.measureUnit
    //         ).dictValue;
    //         let num = 0;
    //         if (packingBoolen) {
    //           let filterArr = row.packingSpecificationOption.filter(
    //             (item) => {
    //               return (
    //                 item.packageUnit == row.packingUnit &&
    //                 item.packageUnit != item.conversionUnit
    //               );
    //             }
    //           );
    //           num = Math.ceil(row.packingQuantity / filterArr[0].packageCell);
    //         }
    //         if (row.isSave) {
    //           return {};
    //         } else {
    //           console.log(packingBoolen, 'packingBoolen怕怕怕怕怕怕怕')
    //           // 处理单位为KG类的情况
    //           if (packingBoolen) {
    //             return {
    //               assetCode: row.categoryCode + row.index,
    //               batchNum: row.batchNo,
    //               num
    //             };
    //           } else {
    //             if (row.isUnpack) {
    //               if (measureBoolen) {
    //                 // 处理单位不为KG类,计量单位为KG类的情况
    //                 let num = row.packingQuantity;
    //                 let splitIndex = row.packingSpecificationOption.findIndex(
    //                   (item) =>
    //                     item.conversionUnit == row.packingUnit &&
    //                     item.packageUnit != item.conversionUnit
    //                 );
    //                 for (; splitIndex > 1; splitIndex--) {
    //                   num = this.$math.format(
    //                     num *
    //                     row.packingSpecificationOption[splitIndex]
    //                       .packageCell,
    //                     14
    //                   );
    //                 }
    //                 return {
    //                   assetCode: row.categoryCode + row.index,
    //                   batchNum: row.batchNo,
    //                   num
    //                 };
    //               } else {
    //                 console.log('拆包情况------：', row.measureQuantity, row.packingSpecificationOption[1]?.packageCell);

    //                 // 处理拆包到最小包装单元数量的情况
    //                 let num = Math.ceil(
    //                   row.measureQuantity / row.packingSpecificationOption[1]?.packageCell
    //                 );
    //                 return {
    //                   assetCode: row.categoryCode + row.index,
    //                   batchNum: row.batchNo,
    //                   num: num
    //                 };
    //               }
    //             } else {
    //               return {
    //                 assetCode: row.categoryCode + row.index,
    //                 batchNum: row.batchNo,
    //                 num: row.packingQuantity
    //               };
    //             }
    //           }
    //         }
    //       });
    //       let filterPackingCodePrams = packingCodePrams.filter(
    //         (item) => item.assetCode
    //       );
    //       let { data } = await storageApi.getAssetNum(filterPackingCodePrams);
    //       console.log('data-----11111111111111111---', data);
    //       let packingCodeList = [];
    //       packingCodePrams.forEach((item, index) => {
    //         packingCodeList[index] = data.filter(
    //           (ite) => ite.assetCode == item.assetCode
    //         );
    //       });
    //       // 批量生成包装
    //       this.productList.map((row, index) => {
    //         if (!row.isSave) {
    //           this.generateWrappers(row, index, packingCodeList[index]);
    //           this.$set(this.productList[index], 'isSave', true);
    //           console.log('this.productList[index]----', this.productList[index]);
    //           console.log('row----', row);

    //           this.$set(
    //             this.productList[index],
    //             'warehouseId',
    //             row.warehouseId
    //           );
    //           this.$set(
    //             this.productList[index],
    //             'warehouseName',
    //             row.warehouseName
    //           );

    //           this.$set(
    //             this.productList[index],
    //             'warehouseIds',
    //             [row.warehouseId]
    //           );
    //           this.$set(
    //             this.productList[index],
    //             'warehouseNames',
    //             [row.warehouseName]
    //           );
    //         }
    //       });
    //       // 加载虚拟列表数据(分页)
    //       // this.pickingFetchData();
    //       // this.materielFetchData();
    //     })
    //     .catch((err) => {
    //       console.log(err);
    //     });
    // },
    // 物品保存验证表单（单独）
    validateFormIndividually(index) {
      return new Promise(async (resolve) => {
        console.log(index);
        let fileds = [
          `productList.${index}.batchNo`,
          `productList.${index}.packingQuantity`,
          `productList.${index}.packingUnit`,
          `productList.${index}.warehouseId`
        ];
        Promise.all(
          fileds.map(
            (item) =>
              new Promise(async (res, rej) => {
                this.$refs.productListRef.validateField(item, (err) => {
                  if (err) {
                    rej(err);
                  } else {
                    res(true);
                  }
                });
              })
          )
        )
          .then(() => {
            resolve();
          })
          .catch(() => {
            this.$message.error('请填入必填项！');
          });
      });
    },
    // 产品编辑
    listEdit(row) {
      console.log(row);
      this.$set(row, 'isSave', false);
      this.deletePackingAndMaterial(row);
    },
    // 根据产品信息删除包装和物料
    deletePackingAndMaterial(row) {
      console.log('row--------', row);
      console.log('packingList------', this.packingList);
      // 删除包装(去掉不相同的包装)
      this.packingList = this.packingList.filter(
        (item) => item.parentIndex !== row.index
      );
      this.showPackingList = this.showPackingList.filter(
        (item) => item.parentIndex !== row.index
      );
      this.pickingPageNum = Math.ceil(
        this.showPackingList.length / this.pageSize
      );
      console.log('包装当前页数');
      console.log(this.pickingPageNum);
      // 删除物料(获取相同物料)
      let packingIndexs = this.packingList.map((item) => item.index);
      this.materialList = this.materialList.filter((item) =>
        packingIndexs.includes(item.parentIndex)
      );
      this.showMaterialList = this.showMaterialList.filter((item) =>
        packingIndexs.includes(item.parentIndex)
      );
      this.materielPageNum = Math.ceil(
        this.showMaterialList.length / this.pageSize
      );
      console.log('物料当前页数');
      console.log(this.showMaterialList.length);
      console.log(this.pageSize);
      console.log(this.materielPageNum);
    },
    // 新增批量保存方法
    async batchSave() {
      try {
        // 验证所有未保存的表单
        await this.validateForm()

        // 遍历所有产品进行保存
        for (let i = 0; i < this.productList.length; i++) {
          const row = this.productList[i]
          if (!row.isSave) {
            // 执行单个保存逻辑
            await this.listSave(row, i)
          }
        }
      } catch (error) {
        this.$message.error('批量保存失败，请检查必填项')
      }
    },
    //产品保存操作
    async listSave(row, index) {
      console.log('row22222222', row);
      return new Promise(async (resolve, reject) => {
        try {
          await this.validateFormIndividually(index)

          // 判断单位和计量单位是否为不拆物料层规格
          let packingBoolen = !!this.getDict('不拆物料层规格', row.packingUnit)
            .dictValue;
          let measureBoolen = !!this.getDict('不拆物料层规格', row.measureUnit)
            .dictValue;
          console.log('packingBoolen---------', packingBoolen);
          console.log('measureBoolen---------', measureBoolen);
          let packingNum = 0;

          // 处理单位为KG类的情况
          if (packingBoolen) {

            if (!row.isUnpack && row.packingUnit == '立方') {
              packingNum = 1;
            } else {
              let filterArr = row.packingSpecificationOption.filter((item) => {
                return (
                  item.packageUnit == row.packingUnit &&
                  item.packageUnit != item.conversionUnit
                );
              });
              packingNum = Math.ceil(
                row.packingQuantity / filterArr[0].packageCell
              );
            }
          }
          // 处理单位不为KG类,计量单位为KG类的情况
          let measureNum = row.packingQuantity;
          let num = 0;

          if (measureBoolen) {
            let splitIndex = row.packingSpecificationOption.findIndex(
              (item) =>
                item.conversionUnit == row.packingUnit &&
                item.packageUnit != item.conversionUnit
            );
            for (; splitIndex > 1; splitIndex--) {
              measureNum = this.$math.format(
                measureNum *
                row.packingSpecificationOption[splitIndex].packageCell,
                14
              );
            }
          } else {
            num = Math.ceil(
              row.measureQuantity / row.packingSpecificationOption[1]?.packageCell
            );
          }
          console.log(packingNum, measureNum, num, '加油加油加油')

          if (row.packingSpecificationLabel?.length < 1) {
            this.$message.error('请到主数据维护包装组信息！')
            return;
          }
          // 不拆包
          if (!row.isUnpack) {
            if (row.packingUnit != row.measureUnit) {
              let pNum = row.packingQuantity;
              const { data } = await storageApi.getAssetNum([
                {
                  assetCode: row.categoryCode + row.index,
                  batchNum: row.batchNo,
                  num: pNum,
                }
              ]);
              this.generateWrappers(row, index, data)
            } else {
              let pNum = 0;
              const { data } = await storageApi.getAssetNum([
                {
                  assetCode: row.categoryCode + row.index,
                  batchNum: row.batchNo,
                  num: pNum,
                }
              ]);
            }
          } else {
            //拆包
            const { data } = await storageApi.getAssetNum([
              {
                assetCode: row.categoryCode + row.index,
                batchNum: row.batchNo,
                num: packingBoolen ? packingNum : measureBoolen ? measureNum : num,
              }
            ]);

            this.generateWrappers(row, index, data);
          }
          this.$set(this.productList[index], 'isSave', true)
          this.$set(this.productList[index], 'warehouseId', row.warehouseId);
          this.$set(
            this.productList[index],
            'warehouseName',
            row.warehouseName
          );

          this.$set(this.productList[index], 'warehouseIds', row.warehouseId);
          this.$set(
            this.productList[index],
            'warehouseNames',
            row.warehouseName
          );

          resolve()
        } catch (error) {
          reject(error)
        }
      })
    },
    // 生成包装
    generateWrappers(row, productIndex, packingCodeList) {
      console.log(packingCodeList, 'packingCodeListROW', row.measureType)
      //计量类型不是数量
      if (!row.isUnpack && row.measureType != 1) {
        // 计量单位=包装单位，则不生成包装层数据
        if (row.measureUnit == row.packingUnit) {
          // 直接生成物品层数据
          this.productList[productIndex].measureQuantity = row.measureQuantity;
          this.productList[productIndex].weight = row.weight;
          return;
        }
      }

      console.log('包装数据--------', row);
      // console.log('包装规格----', row.packingSpecificationOption);
      console.log('计量单位----', row.measureUnit);
      let packingList = [];
      let obj = this.getNowDate();
      let productionDate = '';
      let purchaseDate = '';
      if (this.formData.bizType == '1') {
        // 生产入库
        productionDate = `${obj.year}-${obj.month}-${obj.strDate} ${obj.hour}:${obj.minute}:${obj.second}`;
        this.curDateType = 'productionDate';
      } else if (this.formData.bizType == '2') {
        // 采购入库
        purchaseDate = `${obj.year}-${obj.month}-${obj.strDate} ${obj.hour}:${obj.minute}:${obj.second}`;
        this.curDateType = 'purchaseDate';
      }


      // 判断单位和计量单位是否为不拆物料层规格
      let packingBoolen = !!this.getDict('不拆物料层规格', row.packingUnit)
        .dictValue;
      let measureBoolen = !!this.getDict('不拆物料层规格', row.measureUnit)
        .dictValue;

      let num = row.packingQuantity;
      let filterArr = [];
      // 处理单位为KG类的情况
      if (packingBoolen) {
        console.log(packingBoolen, 'packingBoolenpackingBoolenpackingBoolenpackingBoolenpackingBoolenpackingBoolen')
        if (!row.isUnpack && row.packingUnit == '立方') {
          num = 1;
        } else {
          filterArr = row.packingSpecificationOption.filter((item) => {
            return (
              item.packageUnit == row.packingUnit &&
              item.packageUnit != item.conversionUnit
            );
          });
          num = Math.ceil(row.packingQuantity / filterArr[0]?.packageCell);
        }

      } else {
        if (measureBoolen) {
          // 处理单位不为KG类,计量单位为KG类的情况
          let splitIndex = row.packingSpecificationOption.findIndex(
            (item) =>
              item.conversionUnit == row.packingUnit &&
              item.packageUnit != item.conversionUnit
          );
          for (; splitIndex > 1; splitIndex--) {
            num = this.$math.format(
              num * row.packingSpecificationOption[splitIndex].packageCell,
              14
            );
          }
        } else {
          num = Math.ceil(
            row.measureQuantity / row.packingSpecificationOption[1]?.packageCell
          );
          filterArr = row.packingSpecificationOption.filter((item) => {
            return (
              item.packageUnit == row.packingUnit &&
              item.packageUnit != item.conversionUnit
            );
          });
        }
      }
      console.log('num-----------', num);

      if (!row.isUnpack) {
        let packingUnit = !row.isUnpack ? row.packingUnit : row.packingSpecificationOption[1].conversionUnit;
        let packingQuantity = row.packingQuantity / packingCodeList.length;
        let measureUnit = row.measureUnit;
        let measureQuantity = row.measureQuantity / row.packingQuantity;

        for (let index = 0; index < packingCodeList.length; index++) {
          let item = {
            index: row.index + '-' + index, // 包装索引
            warehouseId: row.warehouseId, // 仓库id
            warehouseName: row.warehouseName, // 仓库名称
            categoryName: row.categoryName, // 产品名称
            categoryCode: row.categoryCode, // 产品编码
            categoryModel: row.categoryModel, // 物品型号
            specification: row.specification, // 规格
            supplierCode: row.supplierCode, // 供应商编码
            brandNum: row.brandNum, // 牌号
            parentIndex: row.index, // 产品索引
            batchNo: row.batchNo, // 批次号
            packageNo: packingCodeList[index]?.onlyCode, // 包装编码
            packingQuantity: packingQuantity, // 包装数量
            packingUnit: packingUnit,
            measureQuantity: measureQuantity, // 计量数量
            measureUnit: measureUnit, // 计量单位
            weight: 0, // 重量
            packingSpecificationOption: row.packingSpecificationOption, // 包装规格
            weightUnit: row.weightUnit, // 重量单位
            netWeight: row.netWeight, // 净重
            barcodes: '', // 发货条码
            clientCode: row.extInfo ? row.extInfo.clientCode : '', // 客户代号
            materielDesignation: row.extInfo ? row.extInfo.materielCode : '', // 物料代号
            supplierName: row.supplierName, // 供应商名称
            supplierCode: row.supplierCode, // 供应商代号
            engrave: '', // 刻码
            isUnpack: row.isUnpack, // 是否允许拆包
            productionDate: productionDate, // 生产日期
            purchaseDate: purchaseDate, // 采购时间
            result: 1, // 结果(1合格 2不合格)
            status: 2 // 状态(0=未质检 1待检 2已检)
          };
          let outBoolen = !!this.getDict('不拆物料层规格', item.measureUnit)
            .dictValue;
          if (outBoolen) {
            // 计量单位为KG类，直接替换
            item.weight = item.measureQuantity ? Number(item.measureQuantity) : 0;
          } else {
            console.log('计量单位为不为KG类======================');
            // 计量单位为不为KG类，重新统计计算
            let inBoolen = !!this.getDict(
              '不拆物料层规格',
              item.packingSpecificationOption[0].packageUnit
            ).dictValue;
            let startIndex = item.packingSpecificationOption.findIndex(
              (ite) => {
                return (
                  item.measureUnit == ite.packingUnit &&
                  ite.packingUnit != ite.conversionUnit
                );
              }
            );

            let endIndex = item.packingSpecificationOption.findIndex(
              (ite) => item.packingUnit == ite.conversionUnit
            );
            if (measureBoolen) {
              let total = item.packingQuantity ? Number(item.packingQuantity) : 0;
              for (; startIndex < endIndex; endIndex--) {
                total = this.$math.format(
                  item.packingSpecificationOption[endIndex].packageCell * total,
                  14
                );
              }
              if (inBoolen) {
                // 第二层为KG类
                item.weight = total ? Number(total) : 0;
              } else {
                // 第二层不为KG类
                item.weight = this.$math.format(total * item.netWeight, 14);
              }
            } else if (!measureBoolen) {
              if (inBoolen) {
                // 第二层为KG类
                item.weight = item.measureQuantity ? Number(item.measureQuantity) : 0;

              } else {
                // 第二层不为KG类
                if (row.singleWeight && item.measureQuantity) {
                  item.weight = Number(item.measureQuantity) * Number(row.singleWeight);
                } else {
                  item.weight = 0;
                }
              }
            }
          }
          packingList.push(item);
        }
      } else {

        console.log('拆包处理', row);
        for (let index = 0; index < num; index++) {
          let measureQuantity = 1;
          let packingQuantity = 1;
          let packingUnit = row.packingUnit;

          // 处理单位为KG类,计算每桶KG值
          if (packingBoolen) {
            if (!row.isUnpack && row.packingUnit == '立方') {
              let result = row.packingQuantity / row.packingSpecificationOption[1].packageCell;
              packingQuantity = Math.ceil(result * 100) / 100;
              console.log(packingQuantity, '包装数oppppp量')
              measureQuantity = row.measureQuantity
              console.log(measureQuantity, '计量数oppppp量')
              packingUnit = row.packingUnit;
            } else {
              measureQuantity =
                Number(row.packingQuantity) >
                  this.$math.format(filterArr[0].packageCell * (index + 1), 14)
                  ? filterArr[0].packageCell
                  : Number(row.packingQuantity) -
                  this.$math.format(filterArr[0].packageCell * index, 14);
            }
          } else {
            if (row.isUnpack == 1) {

              console.log('1 拆--------', measureBoolen)
              if (measureBoolen) {
                // 处理单位不为KG类,计量单位为KG类的情况
                let splitIndex = row.packingSpecificationOption.findIndex(
                  (item) =>
                    item.conversionUnit == row.packingUnit &&
                    item.packageUnit != item.conversionUnit
                );
                for (; splitIndex > 0; splitIndex--) {
                  measureQuantity = this.$math.format(
                    measureQuantity *
                    row.packingSpecificationOption[splitIndex].packageCell,
                    14
                  );
                }
                console.log('2 拆--------', measureQuantity)
              } else {
                measureQuantity = row.packingSpecificationOption[1]?.packageCell;

                console.log('3 拆--------', measureQuantity)

              }
            } else {
              console.log('4 拆--------')
              if (row.packingQuantity) {
                measureQuantity = row.measureQuantity / row.packingQuantity;
              }
            }
            console.log(measureQuantity, 'measureQuantity')
          }
          console.log(filterArr[0], 'filterArr[0]')
          let item = {

            index: row.index + '-' + index, // 包装索引
            warehouseId: row.warehouseId, // 仓库id
            warehouseName: row.warehouseName, // 仓库名称
            categoryName: row.categoryName, // 产品名称
            categoryCode: row.categoryCode, // 产品编码
            categoryModel: row.categoryModel, // 物品型号
            specification: row.specification, // 规格
            supplierCode: row.supplierCode, // 供应商编码
            brandNum: row.brandNum, // 牌号
            parentIndex: row.index, // 产品索引
            batchNo: row.batchNo, // 批次号
            packageNo: packingCodeList[index]?.onlyCode, // 包装编码
            packingQuantity: packingQuantity, // 包装数量
            measureQuantity: row.isUnpack
              ? packingBoolen
                ? measureQuantity
                : measureBoolen
                  ? row.packingSpecificationOption[1]
                    ? row.packingSpecificationOption[1].packageCell
                    : row.packingSpecificationOption[0].packageCell
                  : measureQuantity
              : measureQuantity, // 计量数量
            measureUnit: row.isUnpack
              ? measureBoolen
                ? row.packingSpecificationOption[1]
                  ? row.packingSpecificationOption[1].packageUnit
                  : row.packingSpecificationOption[0].packageUnit
                : row.measureUnit
              : row.measureUnit, // 计量单位
            weight: 0, // 重量
            packingSpecificationOption: row.packingSpecificationOption, // 包装规格
            weightUnit: row.weightUnit, // 重量单位
            netWeight: row.netWeight, // 净重
            barcodes: '', // 发货条码
            clientCode: row.extInfo ? row.extInfo.clientCode : '', // 客户代号
            materielDesignation: row.extInfo ? row.extInfo.materielCode : '', // 物料代号
            supplierName: row.supplierName, // 供应商名称
            supplierCode: row.supplierCode, // 供应商代号
            engrave: '', // 刻码
            isUnpack: row.isUnpack, // 是否允许拆包
            productionDate: productionDate, // 生产日期
            purchaseDate: purchaseDate, // 采购时间
            result: 1, // 结果(1合格 2不合格)
            status: 2 // 状态(0=未质检 1待检 2已检)
          };
          /**
           * packingUnit: row.isUnpack ? packingBoolen ? filterArr[0].conversionUnit : measureBoolen  ? row.packingSpecificationOption[2] ? row.packingSpecificationOption[2].conversionUnit
           *                     : row.packingSpecificationOption[1].conversionUnit: row.measureUnit: packingBoolen ? filterArr[0].conversionUnit : row.packingUnit,
           */
          if (row.isUnpack) {
            // 第二层条件: packingBoolen
            if (packingBoolen) {
              // 空值保护: 确保 filterArr[0] 存在
              item.packingUnit = filterArr?.[0]?.conversionUnit;
            } else {
              // 第三层条件: measureBoolen
              if (measureBoolen) {
                // 处理 packingSpecificationOption 的索引
                const option = row.packingSpecificationOption?.[1] || row.packingSpecificationOption?.[0];
                item.packingUnit = option?.conversionUnit;
              } else {
                item.packingUnit = row.packingSpecificationOption?.[1].conversionUnit;
              }
            }
          } else {
            // 第二层条件: packingBoolen (isUnpack 为 false 时的分支)
            if (packingBoolen) {
              item.packingUnit = filterArr?.[0]?.conversionUnit;
            } else {
              item.packingUnit = row.packingUnit;
            }
          }

          let outBoolen = !!this.getDict('不拆物料层规格', item.measureUnit)
            .dictValue;
          if (outBoolen) {
            // 计量单位为KG类，直接替换
            item.weight = item.measureQuantity ? Number(item.measureQuantity) : 0;
          } else {
            console.log('计量单位为不为KG类======================');
            // 计量单位为不为KG类，重新统计计算
            let inBoolen = !!this.getDict(
              '不拆物料层规格',
              item.packingSpecificationOption[0].packageUnit
            ).dictValue;
            let startIndex = item.packingSpecificationOption.findIndex(
              (ite) => {
                return (
                  item.measureUnit == ite.packingUnit &&
                  ite.packingUnit != ite.conversionUnit
                );
              }
            );

            let endIndex = item.packingSpecificationOption.findIndex(
              (ite) => item.packingUnit == ite.conversionUnit
            );
            if (measureBoolen) {
              let total = item.packingQuantity ? Number(item.packingQuantity) : 0;
              for (; startIndex < endIndex; endIndex--) {
                total = this.$math.format(
                  item.packingSpecificationOption[endIndex].packageCell * total,
                  14
                );
              }
              if (inBoolen) {
                // 第二层为KG类
                item.weight = total ? Number(total) : 0;
              } else {
                // 第二层不为KG类
                item.weight = this.$math.format(total * item.netWeight, 14);
              }
            } else if (!measureBoolen) {
              if (inBoolen) {
                // 第二层为KG类
                item.weight = item.measureQuantity ? Number(item.measureQuantity) : 0;

              } else {
                // 第二层不为KG类
                if (row.singleWeight && item.measureQuantity) {
                  item.weight = Number(item.measureQuantity) * Number(row.singleWeight);
                } else {
                  item.weight = 0;
                }
              }
            }
          }
          packingList.push(item);
        }
        const existingIndex = this.packingList.findIndex(p =>
          p.parentIndex === row.index
        );
        if (existingIndex > -1) {
          this.packingList.splice(existingIndex, 1); // 移除旧数据
        }

      }
      console.log(productIndex, 'productIndex')
      // 单独点击保存并插入对应位置(包装)
      if (productIndex == 0) {
        this.packingList.splice(productIndex, 0, ...packingList);
      } else {
        let packingIndex = this.packingList.findLastIndex(
          (item) =>
            item.parentIndex == this.productList[productIndex - 1].index
        );
        this.packingList.splice(packingIndex + 1, 0, ...packingList);
      }

      const lastIndex = this.packingList.length - 1

      let remainder = row.measureQuantity % row.packingSpecificationOption[1]?.packageCell
      console.log(remainder, 'remainder')
      if (remainder > 0) {
        this.$set(this.packingList[lastIndex], 'measureQuantity', remainder)
      }

    },
    //入库明细删除
    listDel(row, index) {
      this.productList.splice(index, 1);
      this.deletePackingAndMaterial(row);
    },
    // 打开仓库弹框
    handleWareHouse(row, idx, type) {
      console.log(row, 'row')
      if (row.packingSpecificationLabel?.length < 1) {
        this.$message.error('请到主数据维护包装组信息！')
        return;
      }
      if (row.isSave) {
        return false;
      }
      let packingBoolen = !!this.getDict('不拆物料层规格', row.packingUnit)
        .dictValue;
      let measureBoolen = !!this.getDict('不拆物料层规格', row.measureUnit)
        .dictValue;
      console.log(packingBoolen, 'packingBoolen')
      console.log(measureBoolen, 'measureBoolen')
      //行内选择仓库
      if (idx > -1 && type != 'batch') {

        if (row.packingQuantity > 0) {
          //不拆
          if (!row.isUnpack) {
            //计量和包装单位相同
            if (row.measureUnit == row.packingUnit) {
              let pNum = 0;
              let mNum = row.measureQuantity
              this.$refs.wareHouseDailogRef.open(
                pNum,
                mNum,
                idx,
                row.warehouseId,
                row.warehouseName + '',
                row.categoryLevelPathIdParent
              );
            } else {
              let pNum = row.packingQuantity;
              let mNum = row.measureQuantity
              this.$refs.wareHouseDailogRef.open(
                pNum,
                mNum,
                idx,
                row.warehouseId,
                row.warehouseName + '',
                row.categoryLevelPathIdParent
              );
            }
          } else {

            if (packingBoolen) {
              console.log(packingBoolen, 'packingBoolen', row.packageUnit, row.isUnpack);

              let filterArr = row.packingSpecificationOption.filter((item) => {
                return (
                  item.packageUnit == row.packingUnit &&
                  item.packageUnit != item.conversionUnit
                );
              });

              let num = Math.ceil(
                row.packingQuantity / filterArr[0].packageCell
              );
              this.$refs.wareHouseDailogRef.open(
                num,
                row.measureQuantity,
                idx,
                row.warehouseId,
                row.warehouseName + '',
                row.categoryLevelPathIdParent
              );
            } else {
              console.log(measureBoolen, 'measureBoolen');
              let num = row.packingQuantity;
              if (measureBoolen) {
                let splitIndex = row.packingSpecificationOption.findIndex(
                  (item) =>
                    item.conversionUnit == row.packingUnit &&
                    item.packageUnit != item.conversionUnit
                );
                for (; splitIndex > 1; splitIndex--) {
                  num = this.$math.format(
                    num *
                    row.packingSpecificationOption[splitIndex].packageCell,
                    14
                  );
                }
                this.$refs.wareHouseDailogRef.open(
                  num,
                  row.measureQuantity,
                  idx,
                  row.warehouseId,
                  row.warehouseName + '',
                  row.categoryLevelPathIdParent
                );
              } else {
                if (row.measureType != 1 && row.measureUnit == row.packingUnit) {
                  let pNum = 0;
                  let mNum = row.measureQuantity
                  this.$refs.wareHouseDailogRef.open(
                    pNum,
                    mNum,
                    idx,
                    row.warehouseId,
                    row.warehouseName + '',
                    row.categoryLevelPathIdParent
                  );
                } else {
                  let num = Math.ceil(
                    row.measureQuantity / row.packingSpecificationOption[1]?.packageCell
                  );
                  console.log(num, 'num')
                  this.$refs.wareHouseDailogRef.open(
                    num,
                    row.measureQuantity,
                    idx,
                    row.warehouseId,
                    row.warehouseName + '',
                    row.categoryLevelPathIdParent);
                }
              }
            }
          }
        } else {
          this.$message.error('请先填写包装数量！');
        }
      } else {
        //批量
        console.log(row, `row`)
        console.log(idx, `idx`)
        console.log(type, 'type')
        // 批量设置
        if (row.some(item => !item.packingQuantity)) {
          this.$message.error('请先填写所有行的包装数量！');
          return;
        }

        for (let i = 0; i < row.length; i++) {
          //测量单位等于包装单位
          if (row[i].measureType != 1 && row[i].measureUnit === row[i].packingUnit) {
            row[i].packingQuantity2 = 0;
            console.log(row[i].packingQuantity2)
          } else {
            row[i].packingQuantity2 = Math.ceil(
              row[i].measureQuantity / row[i].packingSpecificationOption[1]?.packageCell
            );
            console.log(row[i].packingQuantity2, '单位不一样')
          }
        }
        console.log(row, 'rowrowrowrowrowrow我看看')


        const pNum = row.reduce((sum, item) => {
          if (item.packingQuantity2 !== undefined && item.packingQuantity2 !== null) {
            return sum + Number(item.packingQuantity2);
          }
          return sum;
        }, 0);

        const mNum = row.reduce((sum, item) => {
          if (item.measureQuantity !== undefined && item.measureQuantity !== null) {
            return sum + Number(item.measureQuantity);
          }
          return sum;
        }, 0);
        console.log(pNum, 'pppp')
        console.log(mNum, 'mmmmm')
        this.$refs.wareHouseDailogRef.open(
          pNum,
          mNum
        );
      }
    },
    wareHouseSelection(argum, idx) {
      console.log(argum, 'argumargumargumargumargumargum');
      // 方便包装遍历获取仓库id和名称
      let warehouseIds = [];
      let warehouseNames = [];
      argum.forEach((item) => {
        console.log(item, 'itemitem')
        for (let index = 0; index < item.packingQuantity; index++) {
          warehouseIds.push(item.warehouseId);
          warehouseNames.push(item.warehouseName);
        }
      });

      console.log(idx, this.productList, 'idxidxidxidx')

      if (idx > -1) {
        this.$set(

          this.productList[idx],
          'warehouseId',
          argum.map((item) => item.warehouseId).join(',')
        );
        this.$set(
          this.productList[idx],
          'warehouseName',
          argum.map((item) => item.warehouseName).join(',')
        );
        this.$set(this.productList[idx], 'warehouseIds', warehouseIds);
        this.$set(this.productList[idx], 'warehouseNames', warehouseNames);
        console.log(this.productList, 'productList')
      } else {
        this.productList.map((item, index) => {
          this.$set(
            this.productList[index],
            'warehouseId',
            argum.map((item) => item.warehouseId).join(',')
          );
          this.$set(
            this.productList[index],
            'warehouseName',
            argum.map((item) => item.warehouseName).join(',')
          );
          this.$set(this.productList[index], 'warehouseIds', warehouseIds);
          this.$set(
            this.productList[index],
            'warehouseNames',
            warehouseNames
          );
        });
      }
      this.$forceUpdate();
    },

    // 生成物料
    generateMaterial(row) {
      let materialList = [];
      for (let index = 0; index < row.measureQuantity; index++) {
        materialList.push({
          materialCode: row.packageNo + index.toString().padStart(4, '0'), // 物料编码
          index: row.index + '——' + index, // 包装索引
          warehouseId: row.warehouseId, // 仓库id
          warehouseName: row.warehouseName, // 仓库名称
          categoryName: row.categoryName, // 产品名称
          categoryCode: row.categoryCode, // 产品编码
          parentIndex: row.index, // 产品索引
          batchNo: row.batchNo, // 批次号
          packageNo: row.packageNo, // 包装编码
          measureQuantity: 1, // 计量数量
          measureUnit: row.measureUnit, // 计量单位
          weight: Number(
            this.$math.format(row.weight / row.packingQuantity, 14)
          ), // 重量
          weightUnit: row.weightUnit, // 重量单位
          barcodes: '', // 发货条码
          clientCode: '', // 客户代号
          materielDesignation: '', // 物料代号
          engrave: '', // 刻码
          result: 1, // 结果(1合格 2不合格)
          status: 2 // 状态(0=未质检 1待检 2已检)
        });
      }
      return materialList;
    },
    // 设置时间
    dateSetting() {
      if (!this.packingListSelected.length) {
        return this.$message.error(`请选择${this.title}明细！`);
      }
      this.dateVisible = true;
    },
    // 选择包装列表
    handleSelectionChange(val) {
      this.packingListSelected = val;
    },
    // 选择质检结果改变质检状态
    changeWrapStatus(resultValue, row, type) {
      console.log(resultValue);
      switch (resultValue) {
        case 0:
          // 清空质检状态
          row.status = 0;
          break;
        default:
          // 默认已检质检状态
          row.status = 2;
          break;
      }
      if (type === '包装') {
        this.packingResultCahnge(resultValue, row);
      } else {
        this.materialResultCahnge(resultValue, row);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.inbound_details {
  margin-top: 10px;

  .el-form-item {
    margin-bottom: 0 !important;
  }
}

.el-form-item {
  margin-bottom: 5px;
}

.right_control {
  display: flex;

  >button {
    margin-left: 5px;
  }
}

.storage_btn {
  margin-top: 20px;
  display: flex;
  align-content: center;
  justify-content: center;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100% !important;
}

.red_color {
  color: red;
}

.wareHouse_style {
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
  white-space: nowrap;
}
</style>
