<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="24">
          <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="">
              <el-input
                placeholder="请选择"
                v-model="formData.clientName"
                style="width: calc(100% - 80px)"
              >
              </el-input>
              <openContactDialog
                style="margin-left: 3px"
                @changeParent="contactDialogSuccess"
              ></openContactDialog>
            </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="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="入库时间">
              <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"
          >
            <ele-pro-table
              ref="table"
              :columns="columns"
              :datasource="productList"
              :needPage="false"
              @columns-change="handleColumnChange"
              :cache-key="cacheKeyUrl"
            >
              <template v-slot:toolbar>
                <el-button
                  v-if="productList.length != 0"
                  type="success"
                  plain
                  style="float: right; margin-right: 20px"
                  size="mini"
                  @click="batchSave"
                  >批量保存</el-button
                >
                <el-button
                  v-if="productList.length != 0"
                  type="success"
                  plain
                  style="float: right; margin-right: 20px"
                  size="mini"
                  @click="handleWareHouse(productList, '', 'batch')"
                  >批量选择仓库</el-button
                >
              </template>
              <template v-slot:batchNo="{ 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)
                    "
                    type="number"
                    v-model="row.batchNo"
                  >
                  </el-input>
                </el-form-item>
              </template>
              <template v-slot:packingQuantity="{ 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>
              <template v-slot:packingUnit="{ 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.packingUnitId"
                    placeholder="请选择"
                    @change="computeNum(row, $index)"
                  >
                    <el-option
                      v-for="item in row.packingSpecificationOption"
                      :label="`${item.conversionUnit}`"
                      :value="item.id"
                      :key="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
              <template v-slot:packingSpecificationLabel="{ row, $index }">
                <el-tag v-for="item in row.packingSpecificationLabel">{{
                  item
                }}</el-tag>
              </template>
              <template v-slot:singleWeight="{ row, $index }">
                <el-input
                  :disabled="row.isSave || row.weightUnit == row.packingUnit"
                  v-model="row.singleWeight"
                  placeholder="请输入"
                  :min="0"
                  style="width: 100%"
                  @input="inputSingleWeight(row, $index)"
                >
                  <template slot="append">
                    {{ row.weightUnit }}
                  </template>
                </el-input>
              </template>
              <template v-slot:weight="{ row, $index }">
                <el-input
                  :disabled="row.isSave || row.weightUnit == row.packingUnit"
                  v-model="row.weight"
                  placeholder="请输入"
                  @input="inputAllweight(row, $index)"
                >
                </el-input>
              </template>
              <template v-slot:unitPrice="{ 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>
              <template v-slot:totalMoney="{ row, $index }">
                {{
                  changeCount(
                    calcSumTotal(row.measureQuantity, row.unitPrice, row)
                  )
                }}
              </template>
              <template v-slot:supplierId="{ 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>
              <template v-slot:warehouseName="{ 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>
              <template v-slot:purpose="{ 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>
              <template v-slot:modelKey="{ row, $index }">
                <el-form-item>
                  <DictSelection
                    dictName="物品机型"
                    clearable
                    v-model="row.modelKey"
                    :isOne="$index === 0"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                  >
                  </DictSelection>
                </el-form-item>
              </template>
              <template v-slot:colorKey="{ row, $index }">
                <el-form-item>
                  <DictSelection
                    dictName="物品颜色"
                    clearable
                    v-model="row.colorKey"
                    :isOne="$index === 0"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                  >
                  </DictSelection>
                </el-form-item>
              </template>

              <template v-slot:detailProductionDate="{ row, $index }">
                <template v-if="row.isSave">
                  {{ row.detailProductionDate }}
                </template>
                <el-date-picker
                  v-else
                  :disabled="row.isPack"
                  size="small"
                  v-model="row.detailProductionDate"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </template>
              <template v-slot:detailPurchaseDate="{ row, $index }">
                <template v-if="row.isSave">
                  {{ row.detailPurchaseDate }}
                </template>
                <el-date-picker
                  v-else
                  :disabled="row.isPack"
                  size="small"
                  v-model="row.detailPurchaseDate"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </template>
              <template v-slot:detailExpireDate="{ row, $index }">
                <template v-if="row.isSave">
                  {{ row.detailExpireDate }}
                </template>
                <el-date-picker
                  v-else
                  :disabled="row.isPack"
                  size="small"
                  v-model="row.detailExpireDate"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </template>
              <template v-slot:action="{ 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>
            </ele-pro-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('productionDate')"
              >批量设置生产日期</el-button
            >
            <el-button
              style="margin-left: 20px"
              type="text"
              @click="dateSetting('purchaseDate')"
              >批量设置采购日期</el-button
            >
            <el-button
              style="margin-left: 20px"
              type="text"
              @click="dateSetting('expireDate')"
              >批量设置失效日期</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="150"
            :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="modelKey" width="300">
            <template slot-scope="{ row }">
              <DictSelection
                dictName="物品机型"
                clearable
                v-model="row.modelKey"
                :isOne="false"
                multiple
                filterable
                allow-create
                default-first-option
              >
              </DictSelection>
            </template>
          </el-table-column>
          <el-table-column label="颜色" prop="colorKey" width="300">
            <template slot-scope="{ row }">
              <DictSelection
                dictName="物品颜色"
                clearable
                v-model="row.colorKey"
                :isOne="false"
                multiple
                filterable
                allow-create
                default-first-option
              >
              </DictSelection>
            </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>
          <template v-if="formData.bizType == 5">
            <el-table-column
              label="生产日期"
              prop="productionDate"
              width="220"
            ></el-table-column>
            <el-table-column
              label="采购日期"
              prop="purchaseDate"
              width="220"
            ></el-table-column>
          </template>
          <template v-else>
            <el-table-column label="生产日期" prop="productionDate" width="220">
              <template slot-scope="{ row, $index }">
                <el-date-picker
                  :disabled="row.isPack"
                  size="small"
                  v-model="row.productionDate"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                >
                </el-date-picker
              ></template>
            </el-table-column>

            <el-table-column label="采购日期" prop="purchaseDate" width="220">
              <template slot-scope="{ row, $index }">
                <el-date-picker
                  :disabled="row.isPack"
                  size="small"
                  v-model="row.purchaseDate"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                >
                </el-date-picker
              ></template>
            </el-table-column>
            <el-table-column label="失效日期" prop="expireDate" width="220">
              <template slot-scope="{ row, $index }">
                <el-date-picker
                  :disabled="row.isPack"
                  size="small"
                  v-model="row.expireDate"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                >
                </el-date-picker
              ></template>
            </el-table-column>
          </template>
          <!-- <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="150"
          ></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="handleStorage('save')"
          >保存</el-button
        >
        <el-button
          type="primary"
          :loading="saveLoading"
          @click="handleStorage('Storage')"
          >入库</el-button
        >
      </div>
    </el-card>
    <!-- 产品选择弹框 -->
    <selectType
      :visibleDialog.sync="visibleDialog"
      :title="title"
      :bizScene="formData.bizType"
      :treeIds="formData.extInfo.assetType"
      :loadTree.sync="loadTree"
      @selectTableData="addGoods"
      :cacheKeyUrl="'wms-warehouseManagement-stockManagement-add'"
    />
    <!-- 仓库选择弹框 -->
    <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 openContactDialog from '@/components/contactDialog/openContactDialog.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';
  import { parameterGetByCode } from '@/api/sys/index.js';
  import tabMixins from '@/mixins/tableColumnsMixin';
  import { color } from 'echarts';

  export default {
    mixins: [tabMixins],
    name: 'stockManagementAdd',
    components: {
      selectType,
      WarehousingDialog,
      outboundRequisitionDialog,
      openContactDialog
    },
    // 虚拟列表滚动方法
    directives: {
      'el-table-infinite-scroll': elTableInfiniteScroll
    },
    data() {
      return {
        newColumns: [], // 动态表头
        sceneState,
        saveLoading: false,
        dateVisible: false,
        loadTree: true,
        visibleDialog: false,
        title: '选择产品',
        goodsLists: [],
        cacheKeyUrl: 'wms-stockManagement-add-goods',
        formData: {
          bizType: '',
          storageTime: '',
          extInfo: {
            assetType: []
          }
        },
        rules: {
          'extInfo.assetType': {
            required: true,
            message: '请选择物品类型',
            trigger: ['change', '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: [], // 包装规格下拉
        isPrice: 1
      };
    },
    computed: {
      ...mapGetters(['dict', 'getDict']),
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      columns() {
        return [
          {
            label: '序号',
            type: 'index',
            width: 50,
            align: 'center'
          },
          {
            label: '产品编码',
            prop: 'categoryCode',
            width: 130,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            showOverflowTooltip: true,
            label: '产品名称',
            prop: 'categoryName',
            width: 200,
            align: 'center'
          },

          {
            label: '型号',
            showOverflowTooltip: true,
            prop: 'categoryModel',
            width: 100,
            align: 'center'
          },
          {
            label: '规格',
            prop: 'specification',
            showOverflowTooltip: true,
            width: 100,
            align: 'center'
          },
          {
            label: '牌号',
            prop: 'brandNum',
            showOverflowTooltip: true,
            width: 100,
            align: 'center'
          },
          ...this.newColumns.map((item) => {
            return {
              label: item.label,
              prop: item.prop,
              showOverflowTooltip: true,
              width: 100,
              align: 'center'
            };
          }),
          {
            label: '批次号',
            showOverflowTooltip: true,
            prop: 'batchNo',
            width: 200,
            slot: 'batchNo',
            align: 'center'
          },
          {
            label: '数量',
            showOverflowTooltip: true,
            prop: 'packingQuantity',
            slot: 'packingQuantity',
            width: 180,
            align: 'center'
          },
          {
            label: '单位',
            showOverflowTooltip: true,
            prop: 'packingUnit',
            slot: 'packingUnit',
            width: 100,
            align: 'center'
          },
          {
            label: '包装规格',
            showOverflowTooltip: true,
            prop: 'packingSpecificationLabel',
            slot: 'packingSpecificationLabel',
            width: 300,
            align: 'center'
          },
          {
            label: '允许拆包',
            prop: 'isUnpack',
            width: 80,
            formatter: (_row, _column, cellValue) => {
              return cellValue ? '是' : '否';
            },
            align: 'center'
          },
          {
            label: '计量数量',
            prop: 'measureQuantity',
            width: 100,
            align: 'center'
          },
          {
            label: '计量单位',
            prop: 'measureUnit',
            width: 100,
            align: 'center'
          },
          {
            label: '单重',
            prop: 'singleWeight',
            slot: 'singleWeight',
            showOverflowTooltip: true,
            width: 180,
            align: 'center'
          },
          {
            label: '总重',
            prop: 'weight',
            slot: 'weight',
            showOverflowTooltip: true,
            width: 150,
            align: 'center'
          },
          {
            label: '重量单位',
            prop: 'weightUnit',
            showOverflowTooltip: true,
            width: 100,
            align: 'center'
          },
          this.isPrice == 1
            ? {
                label: '单价',
                slot: 'price',
                prop: 'price',
                showOverflowTooltip: true,
                width: 150,
                align: 'center'
              }
            : {
                label: '单价',
                prop: 'price',
                width: 1
              },
          this.isPrice == 1
            ? {
                label: '金额',
                slot: 'totalMoney',
                prop: 'totalMoney',
                showOverflowTooltip: true,
                width: 100,
                align: 'center'
              }
            : {
                label: '金额',
                prop: 'totalMoney',
                width: 1
              },
          {
            label: '供应商',
            slot: 'supplierId',
            prop: 'supplierId',
            showOverflowTooltip: true,
            width: 200,
            align: 'center'
          },
          {
            label: '供应商代号',
            slot: 'supplierCode',
            showOverflowTooltip: true,
            width: 100,
            align: 'center'
          },
          {
            label: '仓库',
            prop: 'warehouseName',
            slot: 'warehouseName',
            showOverflowTooltip: true,
            width: 300,
            align: 'center'
          },
          {
            minWidth: 300,
            prop: 'modelKey',
            showOverflowTooltip: true,
            label: '机型',
            slot: 'modelKey',
            align: 'center'
          },
          {
            minWidth: 300,
            prop: 'colorKey',
            showOverflowTooltip: true,
            label: '颜色',
            slot: 'colorKey',
            align: 'center'
          },
          {
            label: '采购原因',
            prop: 'purpose',
            slot: 'purpose',
            showOverflowTooltip: true,
            width: 200,
            align: 'center'
          },

          {
            label: '生产日期',
            prop: 'detailProductionDate',
            slot: 'detailProductionDate',
            showOverflowTooltip: true,
            width: 220,
            align: 'center'
          },
          {
            label: '采购日期',
            prop: 'detailPurchaseDate',
            slot: 'detailPurchaseDate',
            showOverflowTooltip: true,
            width: 220,
            align: 'center'
          },
          {
            label: '失效日期',
            prop: 'detailExpireDate',
            slot: 'detailExpireDate',
            showOverflowTooltip: true,
            width: 220,
            align: 'center'
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 250,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ];
      }
    },
    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
      },
      '$route.query': {
        handler(newQuery, oldQuery) {
          if (newQuery?.detailId) {
            this.viewInit();
          }
        },
        deep: true // 确保对象内部的属性变化也能被监听到
      }
    },
    created() {
      //仓库出入库是否显示金额（0：不显示 1：显示）
      parameterGetByCode({
        code: 'wms_price'
      }).then((res) => {
        this.isPrice = res.value;
      });
      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;
            this.formData.id = data.id;
            this.formData.bizNo = data.bizNo;

            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: item.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]
                // 编辑时单位选择消失bug
              };
            });
            // this.$nextTick(() => {
            //   this.listSaveArrs();
            // });
          });
      }
      if (this.$route.query.detailId) {
        this.viewInit();
      }
    },
    methods: {
      ...mapActions('dict', ['requestDict']),
      changeCount(number) {
        return new BigNumber(number).toString();
      },
      viewInit() {
        const _this = this;
        // 编辑时选单位没有选项bug
        let packingSpecification;

        storageApi
          .getInboundDetailsById(this.$route.query.detailId)
          .then(async (data) => {
            this.formData.extInfo.assetType = data.extInfo.assetType.split(',');
            this.formData.bizType = String(data.bizType);
            this.formData.sourceBizNo = data.code;
            this.formData.id = data.id;
            this.formData.bizNo = data.bizNo;
            const batchNo = await getCode('lot_number_code');

            packingSpecification =
              await storageApi.getCategoryPackageDisposition({
                categoryIds: data.outInDetailList.map((item) => item.categoryId)
              });

            console.log(packingSpecification);

            this.packingSpecificationOption = data.outInDetailList.map(
              (item) => {
                return packingSpecification
                  .filter((ite) => item.categoryId == ite.categoryId)
                  .sort((a, b) => a.sort - b.sort);
              }
            );

            const newSpecificationOption = this.packingSpecificationOption;
            this.productList = data.outInDetailList.map(
              (productItem, productIndex) => {
                return {
                  ...productItem,
                  index: this.productList.length + productIndex,
                  isSave: true,
                  // 编辑时没有单位选项
                  packingSpecificationOption:
                    newSpecificationOption[productIndex],
                  //
                  packingSpecificationLabel:
                    productItem.extField?.packingSpecification?.split(','),
                  batchNo: productItem.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: productItem.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;
          });
      },
      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);
        }
        if (row.measureUnit == row.weightUnit) {
          row.weight = row.singleWeight * row.packingQuantity;
          row.measureQuantity = row.weight;
        } else {
          row.weight = row.singleWeight * 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);
        }
        if (row.measureUnit == row.weightUnit) {
          row.measureQuantity = row.weight;
          row.singleWeight =
            Math.trunc((row.measureQuantity / row.packingQuantity) * 100) / 100;
        } else {
          row.singleWeight = row.measureQuantity
            ? row.weight / row.measureQuantity
            : 0;
        }
        // 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
      // },
      // 计算最小单元数量

      // 小数处理，最大3位
      format3(str) {
        let value = str;
        value = value.toString().replace(/[^0-9.]/g, '');
        const parts = value.split('.');
        if (parts.length > 2) {
          value = parts[0] + '.' + parts.slice(1).join('');
        }
        if (parts.length === 2) {
          value = parts[0] + '.' + parts[1].slice(0, 3);
        }
        console.log(value);

        return value;
      },
      async computeNum(row, index, isClear) {
        row.packingQuantity = this.format3(row.packingQuantity);
        console.log(row.packingSpecificationOption);
        console.log(row.packingUnit);

        let data = row.packingSpecificationOption.find(
          (item) => item.id == row.packingUnitId
        );
        row.packingUnit = data.conversionUnit;
        // 清空仓库(包装数量输入)
        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 (
          //     data.id == ite.id &&
          //     ite.packingUnit != ite.conversionUnit
          //   );
          // });

          let endIndex = row.packingSpecificationOption.findIndex(
            (ite) => data.id == ite.id
          );
          console.log(endIndex, 'endIndex');
          let total = Number(row.packingQuantity);

          for (; 0 < endIndex; endIndex--) {
            total = this.$math.format(
              row.packingSpecificationOption[endIndex].packageCell * total,
              14
            );
          }
          //计量数量
          row.measureQuantity = this.changeCount(total);

          // --------------------------------------------------------------------
          //计量单位不是数量时，配置了单重的重量计算
          // row.measureType != 1 &&
          let weight = 0;
          if (row.measureUnit == row.weightUnit) {
            weight = row.measureQuantity;
            //包装单位与重量单位相等时，单重重量为0
            if (row.packingUnit == row.weightUnit) {
              row.singleWeight = 0;
            } else {
              row.singleWeight =
                Math.trunc((row.measureQuantity / row.packingQuantity) * 100) /
                100;
            }
          } else if (row.singleWeight) {
            weight = row.measureQuantity * Number(row.singleWeight);
          }
          this.$set(this.productList[index], 'weight', weight);
        }
      },
      //出入库申请列表操作直接入库
      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) => {
              delete item.extInfo;
              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)
            });
          // 获取供应商
          const supplierList = await storageApi.contactQueryByCategoryIdsAPI({
            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.engrave = productItem.engrave; // 刻码
            productItem.materielDesignation = productItem.materielDesignation; //物料代号
            productItem.clientCode = productItem.clientCode; // 客户代号
            productItem.batchNo = 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: productItem.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;
            }
            (item.supplierListOptions = supplierList[item.categoryId]), // 供应商列表
              (item.packingUnit = item.measuringUnit); // 单位
            item.packingUnitId = item.packingSpecificationOption.find(
              (v) => v.conversionUnit == item.measuringUnit
            )?.id; // 单位

            // if (this.formData.bizType == 4) {
            //   item.packingUnit = '箱';
            // } else {
            //   item.packingUnit = '';
            // }
            return item;
          });
          console.log(this.productList, 'productList');
          this.$nextTick(() => {
            this.batchSave();
          });
          // 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]
          //     });
          //   }
          // }

          // 获取物料维度数据
          // 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.$set(this.formData, 'sourceBizNo', '');
        this.productList = [];
        this.packingList = [];
      },
      // 返回
      back() {
        this.$router.go(-1);
      },
      // 添加产品
      addProduct() {
        this.$refs.formName.validate((valid) => {
          if (valid) {
            this.visibleDialog = true;
          } else {
            console.log('error submit!!');
            return false;
          }
        });

        // if (this.formData.extInfo.assetType.length <= 0) {
        //   return this.$message.error('请选择物品类型');
        // }
        // if (!this.formData.bizType) {
        //   return this.$message.error('请选择入库类型');
        // }
      },
      contactDialogSuccess(data) {
        this.$set(this.formData, 'clientName', data.name);
        this.$set(this.formData, 'clientCode', data.code);
      },
      // 键盘移动
      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: item.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();
          });
      },
      // 入库
      handleStorage(type) {
        this.$refs.formName.validate(async (valid) => {
          if (valid) {
            if (!this.productList.length) {
              return this.$message.warning('请至少添加一条产品');
            }

            let boolen = this.productList.every((item) => item.isSave);
            console.log(boolen);

            if (!boolen) {
              this.$message.warning('请先保存所有产品信息');
              return;
            }
            // 处理包装数据
            this.packingList = this.packingList.map((packingItem) => {
              if (packingItem.modelKey) {
                packingItem.modelKey = packingItem.modelKey.toString();
              }
              if (packingItem.colorKey) {
                packingItem.colorKey = packingItem.colorKey.toString();
              }
              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) => {
              if (productItem.modelKey) {
                productItem.modelKey = productItem.modelKey.toString();
              }
              if (productItem.colorKey) {
                productItem.colorKey = productItem.colorKey.toString();
              }
              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');
            // if(){}
            if (!(await this.isVerifyRepeatIsStock())) {
              this.saveLoading = false;

              return;
            }
            let api = obj.id ? storageApi.update : storageApi.storage;
            api(obj)
              .then(async (res) => {
                console.log('入库成功', res);
                console.log('入库成功', obj.id);
                if (res.code == 0) {
                  try {
                    if (type != 'save') {
                      if (obj.bizType == '12') {
                        await storageApi.qualityInspectionTwo({
                          outInIds: res.data
                        });
                      } else {
                        await storageApi.submitTwo({ outInIds: res.data });
                      }
                      this.$message.success('入库成功');
                    } else {
                      this.$message.success('操作成功');
                    }
                    // 委外入库（非采购）

                    this.saveLoading = false;
                    // this.$router.push('/warehouseManagement/stockManagement');
                    this.back();
                  } catch (error) {
                    this.saveLoading = false;
                    // this.$router.push('/warehouseManagement/stockManagement');
                    this.back();
                    console.log('提交流程失败', error);
                  }
                }
              })
              .catch((err) => {
                console.log('入库失败', err);
                this.saveLoading = false;
              });
          } else {
            return;
          }
        });
      },
      async isVerifyRepeatIsStock() {
        const isVerifyData = await storageApi.isVerifyRepeatIsStock({
          categoryCodes: this.productList.map((item) => item.categoryCode),
          batchNos: this.productList.map((item) => item.batchNo)
        });

        return new Promise((resolve, reject) => {
          if (isVerifyData?.length) {
            this.$confirm(
              `当前批次：${isVerifyData[0].batchNo},物品${isVerifyData
                .map((item) => item.categoryName)
                .join(',')}已有入库记录，是否继续入库！`,
              {
                confirmButtonText: '是',
                cancelButtonText: '否'
              }
            )
              .then(() => {
                resolve(true);
              })
              .catch(() => {
                resolve(false);
              });
          } else {
            resolve(true);
          }
        });
      },

      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) {
        //最小包装单元,包装数量,单价
        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;
        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.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, // 规格
            modelKey: item.modelKey ? item.modelKey.split(',') : '', // 机型
            colorKey: item.colorKey ? item.colorKey.split(',') : '', // 颜色
            color: item.color,
            brandNum: item.brandNum, // 牌号
            batchNo: item.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: item.measuringUnit, // 单位
            packingUnitId: newSpecificationOption[index].find(
              (v) => v.conversionUnit == item.measuringUnit
            )?.id, // 单位
            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);
                        }
                      });
                    })
                )
              );
            }
          });
          Promise.all(list)
            .then(() => {
              console.log('保存成功！');
              resolve();
            })
            .catch((err) => {
              console.log('保存失败！');
              this.$message.error('请填入必填项！');
              reject(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(row, ';ddd');
        return new Promise(async (resolve, reject) => {
          try {
            await this.validateFormIndividually(index);

            if (row.packingSpecificationLabel?.length < 1) {
              this.$message.error('请到主数据维护包装组信息！');
              return;
            }

            // 不拆包
            if (!row.isUnpack) {
              if (row.packingUnit != row.measureUnit) {
                let pNum = row.packingQuantity;
                let splitIndex = row.packingSpecificationOption.findIndex(
                  (item) =>
                    item.conversionUnit == row.packingUnit &&
                    item.packageUnit != item.conversionUnit
                );
                for (; splitIndex > 1; splitIndex--) {
                  pNum = this.$math.format(
                    pNum *
                      row.packingSpecificationOption[splitIndex].packageCell,
                    14
                  );
                }
                console.log(pNum, 'pNum12');
                const { data } = await storageApi.getAssetNum([
                  {
                    assetCode: row.categoryCode + row.index,
                    batchNum: row.batchNo,
                    num: Math.ceil(pNum)
                  }
                ]);
                // this.generateWrappers(row, index, data)
              } else {
                let pNum = 0;
                const { data } = await storageApi.getAssetNum([
                  {
                    assetCode: row.categoryCode + row.index,
                    batchNum: row.batchNo,
                    num: Math.ceil(pNum)
                  }
                ]);
              }
            } else {
              let pNum = 0;
              if (row.packingUnitId) {
                let splitIndex = row.packingSpecificationOption.findIndex(
                  (item) => item.id == row.packingUnitId
                );
                if (splitIndex == 0) {
                  pNum = Math.ceil(
                    row.measureQuantity /
                      row.packingSpecificationOption[1]?.packageCell
                  );
                }
                if (splitIndex == 1) {
                  pNum = row.packingQuantity;
                }

                for (; splitIndex > 1; splitIndex--) {
                  pNum = Math.ceil(
                    row.packingQuantity *
                      row.packingSpecificationOption[splitIndex].packageCell
                  );
                }
              } else {
                pNum = Math.ceil(
                  row.measureQuantity /
                    row.packingSpecificationOption[1]?.packageCell
                );
              }
              // row.packingQuantity;
              // console.log(row.packingQuantity,'row.packingQuantity')
              // return
              //拆包
              const { data } = await storageApi.getAssetNum([
                {
                  assetCode: row.categoryCode + row.index,
                  batchNum: row.batchNo,
                  num: Math.ceil(pNum)
                }
              ]);
              console.log(data, 'data');

              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 = row.detailProductionDate || '';
        let purchaseDate = row.detailPurchaseDate || '';
        let expireDate = row.detailExpireDate || '';
        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 {
            if (row.packingSpecificationOption[1]?.packageCell) {
              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) {
          console.log(row.packingSpecificationOption[1]);
          // let packingUnit = !row.isUnpack ? row.packingUnit : row.packingSpecificationOption[1].conversionUnit;
          // let packingQuantity = row.packingQuantity / packingCodeList.length;

          let packingUnit = row.packingSpecificationOption[1]?.conversionUnit;
          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
          );
          let total = Number(row.packingQuantity);
          for (; startIndex < endIndex; endIndex--) {
            total = this.$math.format(
              row.packingSpecificationOption[endIndex].packageCell * total,
              14
            );
          }
          console.log('total-----------', total);
          let packingQuantity = row.measureQuantity / total;

          let measureUnit = row.measureUnit;

          let measureQuantity = row.measureQuantity / packingCodeList.length;

          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, // 计量单位
              modelKey: row.modelKey, // 机型
              colorKey: row.colorKey, //颜色
              measureType: row.measureType,
              measureUnit: measureUnit, // 计量单位
              weight: 0, // 重量
              packingSpecificationOption: row.packingSpecificationOption, // 包装规格
              weightUnit: row.weightUnit, // 重量单位
              netWeight: row.netWeight, // 净重
              barcodes: '', // 发货条码
              clientCode: row.extInfo ? row.extInfo.clientCode : '', // 客户代号
              materielDesignation:
                row.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 {
          for (let index = 0; index < packingCodeList.length; 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.weightUnit == row.measureUnit && row.weight) {
                measureQuantity =
                  Math.trunc((row.weight / packingCodeList.length) * 100) / 100;
              } else {
                measureQuantity = row.packingSpecificationOption[1].packageCell;
              }
            }
            console.log(
              'meadasdassureQuantity',
              row.weight / row.packingQuantity
            );
            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, // 产品索引
              modelKey: row.modelKey, // 机型
              colorKey: row.colorKey, //颜色
              batchNo: row.batchNo, // 批次号
              packageNo: packingCodeList[index]?.onlyCode, // 包装编码
              packingQuantity: packingQuantity, // 包装数量
              measureQuantity: measureQuantity, // 计量数量
              measureUnit: row.isUnpack
                ? measureBoolen
                  ? row.packingSpecificationOption[1]
                    ? row.packingSpecificationOption[1].packageUnit
                    : row.packingSpecificationOption[0].packageUnit
                  : row.measureUnit
                : row.measureUnit, // 计量单位
              weight: row.weight / row.packingQuantity,
              packingSpecificationOption: row.packingSpecificationOption, // 包装规格
              weightUnit: row.weightUnit, // 重量单位
              netWeight: row.netWeight, // 净重
              barcodes: '', // 发货条码
              clientCode:
                row.clientCode || (row.extInfo ? row.extInfo.clientCode : ''), // 客户代号
              materielDesignation:
                row.materielDesignation ||
                (row.extInfo ? row.extInfo.materielCode : ''), // 物料代号
              supplierName: row.supplierName, // 供应商名称
              supplierCode: row.supplierCode, // 供应商代号
              engrave: row.engrave, // 刻码
              isUnpack: row.isUnpack, // 是否允许拆包
              productionDate: productionDate, // 生产日期
              purchaseDate: purchaseDate, // 采购时间
              expireDate: expireDate,
              result: 1, // 结果(1合格 2不合格)
              status: 2 // 状态(0=未质检 1待检 2已检)
            };
            console.log(
              row.packingSpecificationOption[1],
              'row.packingSpecificationOption[1]'
            );
            if (row.isUnpack) {
              // 第二层条件: packingBoolen
              if (packingBoolen) {
                // 空值保护: 确保 filterArr[0] 存在
                item.packingUnit =
                  row.packingSpecificationOption[1].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;
                }
              }
            }

            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 = 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 = 0;
        if (row.weightUnit != row.measureUnit) {
          remainder =
            row.measureQuantity %
            row.packingSpecificationOption[1]?.packageCell;
        }
        console.log(remainder, 'remainder');
        if (remainder > 0) {
          let onlyCode = packingCodeList[packingCodeList.length - 1]?.onlyCode;
          let index = this.packingList.findIndex(
            (packingItem) => packingItem.packageNo == onlyCode
          );
          this.$set(this.packingList[index], 'measureQuantity', remainder);
          if (row.singleWeight) {
            this.$set(
              this.packingList[index],
              'weight',
              row.singleWeight * remainder
            );
          }
        }
      },
      //入库明细删除
      listDel(row, index) {
        this.productList.splice(index, 1);
        this.deletePackingAndMaterial(row);
      },
      // 打开仓库弹框
      handleWareHouse(row, idx, type) {
        console.log(row, 'row');
        console.log(idx, 'idx');
        console.log(type, 'type');

        if (row.packingSpecificationLabel?.length < 1) {
          this.$message.error('请到主数据维护包装组信息！');
          return;
        }
        if (row.isSave) {
          return false;
        }
        //单个
        if (idx > -1 && type != 'batch') {
          if (row.packingQuantity > 0) {
            if (!row.isUnpack) {
              console.log('不拆');
              //计量和包装单位相同
              if (row.measureUnit == row.packingUnit) {
                let pNum = 0;
                let mNum = row.measureQuantity;
                this.$refs.wareHouseDailogRef.open({
                  packingQuantity: pNum,
                  measureQuantity: mNum,
                  idx,
                  warehouseId: row.warehouseId,
                  warehouseName: row.warehouseName + '',
                  categoryType: row.categoryLevelPathIdParent
                });
              } else {
                if (row.packingSpecificationOption[1]?.packageCell) {
                  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
                    );
                  }
                  this.$refs.wareHouseDailogRef.open({
                    packingQuantity: num,
                    measureQuantity: row.measureQuantity,
                    idx,
                    warehouseId: row.warehouseId,
                    warehouseName: row.warehouseName + '',
                    categoryType: row.categoryLevelPathIdParent
                  });
                } else {
                  this.$refs.wareHouseDailogRef.open({
                    packingQuantity: num,
                    measureQuantity: row.measureQuantity,
                    idx,
                    warehouseId: row.warehouseId,
                    warehouseName: row.warehouseName + '',
                    categoryType: row.categoryLevelPathIdParent
                  });
                }
              }
            } else {
              console.log('拆');
              // let filterArr = row.packingSpecificationOption.filter((item) => {
              //   return (
              //     item.packageUnit == row.packingUnit &&
              //     item.packageUnit != item.conversionUnit
              //   );
              // });

              let num = Math.ceil(
                row.measureQuantity /
                  row.packingSpecificationOption[1]?.packageCell
              );
              console.log(num);

              this.$refs.wareHouseDailogRef.open({
                packingQuantity: num,
                measureQuantity: row.measureQuantity,
                idx,
                warehouseId: row.warehouseId,
                warehouseName: row.warehouseName + '',
                categoryType: 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;
          }

          // 计算总需求数量
          let totalPacking = row.reduce((sum, item) => {
            return sum + Number(this.calculateRequiredWarehouseNum(item));
          }, 0);
          const mNum = row.reduce((sum, item) => {
            if (
              item.measureQuantity !== undefined &&
              item.measureQuantity !== null
            ) {
              return sum + Number(item.measureQuantity);
            }
            return sum;
          }, 0);
          // 打开仓库选择弹窗

          this.$refs.wareHouseDailogRef.open({
            packingQuantity: totalPacking,
            measureQuantity: mNum,
            batch: this.formData.extInfo.assetType
          });
          // this.$refs.wareHouseDailogRef.open(totalPacking, mNum);
        }
      },
      calculateRequiredWarehouseNum(row) {
        if (!row.isUnpack && row.measureUnit !== row.packingUnit) {
          let splitIndex = row.packingSpecificationOption.findIndex(
            (item) => item.conversionUnit === row.packingUnit
          );
          let num = row.packingQuantity;
          for (; splitIndex > 1; splitIndex--) {
            num = Math.ceil(
              num * row.packingSpecificationOption[splitIndex].packageCell
            );
          }
          return num;
        }
        console.log(row.packingQuantity, 'row.calculateRequiredWarehouseNum');
        return row.packingQuantity;
      },
      wareHouseSelection(argum, idx) {
        console.log(argum, 'argumargumargumargumargumargum', idx);
        // 方便包装遍历获取仓库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, 'idxidxidxidx', this.productList, 'this.productList');

        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(curDateType) {
        if (!this.packingListSelected.length) {
          return this.$message.error(`请选择${this.title}明细！`);
        }
        this.curDateType = curDateType;
        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;
  }

  :deep(.el-col) {
    margin-bottom: 12px;
  }
</style>
