<template>
  <div class="p-2">
    <el-card shadow="never">
      <el-form label-width="120px" label-position="right" :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="入库单号">
          <el-input v-model="queryForm.instockCode" placeholder="输入调拨单号" clearable/>
        </el-form-item>
<!--        <el-form-item label="工单类型" prop="instockType">-->
<!--          <el-select v-model="queryForm.instockType" placeholder="请选择工单类型" clearable >-->
<!--            <el-option v-for="dict in wms_instock_type" :key="dict.value" :label="dict.label" :value="dict.value"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <!--        <el-form-item label="入库方式" prop="instockMethond">-->
        <!--          <el-select v-model="queryForm.instockMethond" placeholder="请选择入库方式" clearable >-->
        <!--            <el-option v-for="dict in instock_methond" :key="dict.value" :label="dict.label" :value="dict.value"/>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
<!--        <el-form-item label="审核状态" prop="auditStatus">
          <el-select v-model="queryForm.auditStatus" placeholder="请选择审核状态" clearable >
            <el-option v-for="dict in approve_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>-->
        <el-form-item label="仓库" prop="warehouseId">
          <el-select v-model="queryForm.warehouseId" placeholder="请选择所属仓库" clearable>
            <el-option
              v-for="item in baseStoreList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :loading="parentTableLoad" type="primary" @click="query">刷新</el-button>
<!--          <el-button @click="reset">重置</el-button>-->
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 8px" shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="parentTableAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
<!--            <el-button type="success" plain icon="Edit" :disabled="ids.length !== 1" @click="parentTableUpdate()">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="ids.length < 1" @click="parentTableDelete()">删除
            </el-button>-->
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true"
                         @queryTable="getParentTable"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="parentTableLoad" :data="parentTableData" style="width: 100%" highlight-current-row
                @current-change="parentTableCellClick"
                @selection-change="selectionChange" ref="parentTableRef">
        <el-table-column type="selection" width="55"/>
        <!-- <el-table-column label="入库单 主键" align="center" prop="instockId"/> -->
        <el-table-column label="入库单号" align="center" prop="instockCode"/>
        <!--        <el-table-column label="物料大类" align="center" prop="materialCategoryName">-->
        <!--        </el-table-column>-->
        <el-table-column label="工单类型" align="center" prop="instockType">
          <template #default="scope">
            <dict-tag :options="wms_instock_type" :value="scope.row.instockType"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="入库方式" align="center" prop="instockMethond">
          <template #default="scope">
            <dict-tag :options="instock_methond" :value="scope.row.instockMethond"/>
          </template>
        </el-table-column>-->
        <el-table-column label="订单编号" align="center" prop="orderNo"/>
<!--        <el-table-column label="审核人" align="center" prop="auditBy"/>
        <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="auditStatus">
          <template #default="scope">
            <dict-tag :options="approve_status" :value="scope.row.auditStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="审核意见" align="center" prop="auditComments"/>-->
        <el-table-column label="仓库" align="center" prop="warehouseCode"/>
        <!-- <el-table-column label="入库方式" align="center" prop="inMethod">
          <template #default="scope">
            <dict-tag :options="wms_allocate_way" :value="scope.row.inMethod"/>
          </template>
        </el-table-column> -->
<!--        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            &lt;!&ndash;            <el-button size="small" @click.stop="viewDetails(scope.row)">&ndash;&gt;
            &lt;!&ndash;              查看&ndash;&gt;
            &lt;!&ndash;            </el-button>&ndash;&gt;
            <el-button size="small" @click.stop="parentTableApprove(scope.row)" v-if="scope.row.auditStatus==0&&scope.row.auditBy!=''">
              审批
            </el-button>
            <el-button size="small" @click.stop="parentTableUpdate(scope.row)">
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click.stop="parentTableDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>-->
      </el-table>
      <pagination v-show="parentTableTotal > 0" :total="parentTableTotal" v-model:page="queryForm.pageNum"
                  v-model:limit="queryForm.pageSize" @pagination="getParentTable"/>
    </el-card>

    <el-card style="margin-top: 8px" shadow="never">
      <el-table :data="childrenTableData" style="width: 100%" v-loading="childrenTableLoad">
        <el-table-column label="物料编码" align="center" prop="materialCode"/>
        <el-table-column label="物料名称" align="center" prop="materialName"/>
        <el-table-column label="入库数量" align="center" prop="instockQty"/>
<!--        <el-table-column label="质检标识" align="center" prop="isInspection">
          <template #default="scope">
            <dict-tag :options="wsm_is_inspection" :value="scope.row.isInspection"/>
          </template>
        </el-table-column>-->
<!--        <el-table-column label="已分包数量" align="center" prop="printedNum" />-->
        <el-table-column label="物料规格" align="center" prop="materialSpe"/>
        <el-table-column label="计量单位名称" align="center" prop="unitName"/>
<!--        <el-table-column label="是否有条码" align="center" prop="codeYesNo">
          <template #default="scope">
            <dict-tag :options="wms_barcode_if" :value="scope.row.codeYesNo"/>
          </template>
        </el-table-column>-->
        <!--        <el-table-column label="物料大类" align="center" prop="materialCategoryName">-->
        <!--        </el-table-column>-->
<!--        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
&lt;!&ndash;            <el-button size="small" @click="childrenTableUpdate( scope.row)" v-if="auditStatusLoad && partntTableSelectCell.instockType !== '6'">
              打印
            </el-button>&ndash;&gt;
            <el-button
              size="small"
              type="danger"
              @click="childrenTableUDelete(scope.row)"
            >
              删除
            </el-button>
             <el-tooltip content="打印" placement="top">
              <el-button type="primary" @click="handlePrint(scope.row)">打印</el-button>
            </el-tooltip>
          </template>
        </el-table-column>-->
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%">
      <el-card shadow="never">
        <el-form :model="dialogForm" :inline="true" label-width="120px" :disabled="isView" ref="dialogFormRef" :rules="dialogFormRules">
<!--          <el-form-item label="物料大类" prop="materialCategoryId">-->
<!--            <el-select v-model="dialogForm.materialCategoryId" placeholder="请选择物料大类" @change="setMaterialList">-->
<!--              <el-option v-for="item in mategoryOptions"-->
<!--                         :key="item.materialCategoryId"-->
<!--                         :label="item.materialCategoryName"-->
<!--                         :value="item.materialCategoryId"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="工单类型" prop="instockType">
            <el-select v-model="dialogForm.instockType" placeholder="请选择工单类型">
              <el-option
                v-for="dict in wms_instock_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="dialogForm.orderNo" placeholder="请输入订单编号" />
          </el-form-item>
          <el-form-item label="采购订单" v-if="state.showPurchaseOrderSelect">
            <el-select v-model="state.selectedPurchaseOrder" placeholder="请选择采购订单" value-key="poId" style="width: 200px" clearable>
              <el-option v-for="item in state.purchaseOrders" :key="item.poId" :label="item.poNo" :value="item" />
            </el-select>
            <el-button type="primary" @click="handleAssociatePurchaseOrder" style="margin-left: 10px" :disabled="!state.selectedPurchaseOrder">
              关联
            </el-button>
          </el-form-item>
          <el-form-item label="生产订单" v-if="state.showProductionOrderSelect">
            <el-select v-model="state.selectedProductionOrder" placeholder="请选择生产订单" @change="handleProductionOrderSelect" value-key="productOrderId" clearable>
              <el-option v-for="item in state.productionOrders" :key="item.productOrderId" :label="item.orderCode" :value="item" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="审核人" prop="auditBy">
            <el-select v-model="dialogForm.auditBy" placeholder="请选择审核人">
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userName"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="仓库" prop="warehouseId" >
            <el-select v-model="dialogForm.warehouseId" placeholder="请选择所属仓库" clearable>
              <el-option
                v-for="item in baseStoreList"
                :key="item.warehouseId"
                :label="item.warehouseName"
                :value="item.warehouseId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card style="margin-top: 8px" shadow="never">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="addDialogTableCell" :disabled="isAddDisabled">新增</el-button>
          </el-col>
        </el-row>
        <el-table :data="dialogtable" style="width: 100%">
          <el-table-column label="字段1" prop="date" v-if="false">
          </el-table-column>

          <el-table-column label="物料编码" prop="materialCode">
            <!--            <template #default="scope">
                          <el-select
                            v-model="scope.row.materialId"
                            placeholder="选择物料"
                            style="width: 240px"
                          >
                            <el-option
                              v-for="i in materialList"
                              :label="i.materialCode+'('+i.materialName+')'"
                              :value="i.materialId"
                              :key="i.materialId"
                            />
                          </el-select>
                        </template>-->
            <template #default="scope">
              <el-input
                v-model="scope.row.materialCode"
                placeholder="请点击检索物料"
                @click="handleMaterialAdd('material', scope.$index)" >
                <template #append>
                  <el-icon class="el-input__icon"><search/></el-icon>
                </template>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column label="物料名称" prop="materialName">
            <template #default="scope">
              <el-select
                v-model="scope.row.materialName"
                placeholder="选择物料"
                style="width: 240px"
                :disabled="true"
              >
                <el-option
                  v-for="i in materialList"
                  :label="i.materialName"
                  :value="i.materialName"
                  :key="i.materialId"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="物料单位" prop="unitName">
            <template #default="scope">
              <el-select
                v-model="scope.row.unitName"
                placeholder="选择物料"
                style="width: 240px"
                :disabled="true"
              >
                <el-option
                  v-for="i in materialList"
                  :label="i.materialUnit"
                  :value="i.materialUnit"
                  :key="i.materialId"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="物料规格" prop="materialSpe">
            <template #default="scope">
              <el-select
                v-model="scope.row.materialSpe"
                placeholder="选择物料"
                style="width: 240px"
                :disabled="true"
              >
                <el-option
                  v-for="i in materialList"
                  :label="i.materialSpec"
                  :value="i.materialSpec"
                  :key="i.materialId"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 采购订单相关列，只在工单类型为采购订单时显示 -->
          <el-table-column label="采购数量" prop="purchaseQty" v-if="dialogForm.instockType === '1'">
            <template #default="scope">
              <span>{{ scope.row.purchaseQty || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已入库数量" prop="instockedQty" v-if="dialogForm.instockType === '1'">
            <template #default="scope">
              <span>{{ scope.row.instockedQty || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="剩余可入库" prop="remainingQty" v-if="dialogForm.instockType === '1'">
            <template #default="scope">
              <span style="color: #409EFF; font-weight: bold;">{{ scope.row.remainingQty || (scope.row.purchaseQty - (scope.row.instockedQty || 0)) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="入库数量" prop="instockQty">
            <template #default="scope">
              <el-input-number
                v-if="scope.row._showQtyInput"
                v-model.number="scope.row.instockQty"
                :min="0"
                :max="dialogForm.instockType === '1' ? scope.row.remainingQty : scope.row.deliveryQty"
                :precision="0"
                :controls="false"
                placeholder="请输入入库数量"
                @change="(val) => validateQty(scope.row, val)"
                style="width: 100%"
              />
              <span v-else>{{ scope.row.instockQty }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column label="有无条码" prop="codeYesNo">-->
          <!--            <template #default="scope">-->
          <!--              <el-select-->
          <!--                v-model="scope.row.codeYesNo"-->
          <!--                placeholder="选择有无条码"-->
          <!--                style="width: 240px"-->
          <!--              >-->
          <!--                <el-option-->
          <!--                  v-for="i in wms_barcode_if"-->
          <!--                  :label="i.label"-->
          <!--                  :value="i.value"-->
          <!--                  :key="i.value"-->
          <!--                />-->
          <!--              </el-select>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
<!--          <el-table-column label="操作" fixed="right" width="200">
            <template #default="scope">
&lt;!&ndash;              <el-button
                size="small"
                type="danger"
                @click="tableUDelete(scope.row)"
              >
                删除
              </el-button>&ndash;&gt;
            </template>
          </el-table-column>-->
          <!-- <el-table-column label="已包数量" prop="printedNum">
            <template #default="scope">
              <el-input v-model="scope.row.printedNum" placeholder="请输入已包数量" />
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="分包数量" prop="printNum">
            <template #default="scope">
              <el-input v-model="scope.row.printNum" placeholder="请输入分包数量" />
            </template>
          </el-table-column>
          <el-table-column label="打印数量" prop="barcodeNum">
            <template #default="scope">
              <el-input v-model="scope.row.barcodeNum" placeholder="请输入打印数量" />
            </template> -->
          <!-- </el-table-column> -->

          <!--          <el-table-column label="erp同步状态" prop="erpSynchronousStatus">-->
          <!--            <template #default="scope">-->
          <!--              <el-select-->
          <!--                v-model="scope.row.erpSynchronousStatus"-->
          <!--                placeholder="选择erp同步状态"-->
          <!--              >-->
          <!--                <el-option-->
          <!--                  label="1"-->
          <!--                  value="1"-->
          <!--                />-->
          <!--                <el-option-->
          <!--                  label="2"-->
          <!--                  value="2"-->
          <!--                />-->
          <!--              </el-select>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="dialogSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="parentTableInfoVisible" title="修改父表格" width="40%">
      <el-form :model="parentTableInfoForm" label-width="120px">
        <el-form-item label="物料大类" prop="materialCategoryId">
          <el-select v-model="parentTableInfoForm.materialCategoryId" placeholder="请选择物料大类" :disabled="true">
            <el-option v-for="item in mategoryOptions"
                       :key="item.materialCategoryId"
                       :label="item.materialCategoryName"
                       :value="item.materialCategoryId"
            />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="工单类型" prop="instockType">-->
<!--          <el-select v-model="parentTableInfoForm.instockType" placeholder="请选择工单类型">-->
<!--            <el-option-->
<!--              v-for="dict in wms_instock_type"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <!-- <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item> -->
        <el-form-item label="审核人" prop="auditBy">
          <el-select v-model="parentTableInfoForm.auditBy" placeholder="请选择审核人" :disabled="true">
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-select v-model="parentTableInfoForm.warehouseCode" placeholder="请选择所属仓库" :disabled="true">
            <el-option
              v-for="item in baseStoreList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="parentTableInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="parentTableInfoSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="parentTableApproveVisible" title="审批" width="40%">
      <el-form :model="parentTableApproveForm" label-width="120px">
        <!--        <el-form-item label="审核人" prop="auditBy">-->
        <!--          <el-select v-model="parentTableApproveForm.auditBy" placeholder="请选择审核人" style="width:100px;" :disabled="true">-->
        <!--            <el-option-->
        <!--              v-for="item in userList"-->
        <!--              :key="item.userId"-->
        <!--              :label="item.userName"-->
        <!--              :value="item.userName"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="审核状态" prop="auditStatus">
          <el-radio-group v-model='parentTableApproveForm.auditStatus'>
            <el-radio
              v-for='dict in audit_behave'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditComments">
          <el-input
            v-model='parentTableApproveForm.auditComments'
            style="width: 500px"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="Please input"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="parentTableApproveVisible = false">关闭</el-button>
          <el-button type="primary" @click="parentTableApproveSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="childrenTableInfoVisible" title="条码生成" width="40%">
      <el-form :model="childrenTableInfoForm" label-width="120px">
        <el-form-item label="物料" prop="materialCode">
          <el-select v-model="childrenTableInfoForm.materialCode" placeholder="请选择物料" :disabled="true">
            <el-option
              v-for="item in materialList"
              :key="item.materialId"
              :label="item.materialCode"
              :value="item.materialId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库数量" prop="instockQty">
          <el-input v-model="childrenTableInfoForm.instockQty" placeholder="请输入入库数量" :disabled="true"/>
        </el-form-item>
        <el-form-item label="有无条码" prop="codeYesNo">
          <el-radio-group v-model="childrenTableInfoForm.codeYesNo" :disabled="true">
            <el-radio
              v-for="dict in wms_barcode_if"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item>
          <el-button @click="batchConfigVisible = true">配置条码</el-button>
        </el-form-item>


        <el-form-item label="已包数量" prop="printedNum">
          <el-input v-model="childrenTableInfoForm.printedNum" placeholder="" :disabled="true"/>
        </el-form-item>
        <el-form-item label="分包数量" prop="splitPackageCount">
          <el-input-number v-model="childrenTableInfoForm.splitPackageCount" :min="1" :max="remainingQty" placeholder="请输入分包数量" @change="onSplitPackageCountChange" />
        </el-form-item>

        <!-- 当分包数量大于1时显示分包模式选择和每包数量配置 -->
        <el-form-item v-if="childrenTableInfoForm.splitPackageCount > 1" label="分包模式">
          <el-radio-group v-model="packageMode" @change="onPackageModeChange">
            <el-radio value="average">平均分包</el-radio>
            <el-radio value="custom">自定义每包数量</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 平均分包模式显示分包预览 -->
        <el-form-item v-if="childrenTableInfoForm.splitPackageCount > 1 && packageMode === 'average'" label="分包预览">
          <div class="package-preview-container">
            <div class="package-preview-item" v-for="(qty, index) in averagePackageList" :key="index">
              <span class="package-label">第{{index + 1}}包：</span>
              <span class="package-qty">{{qty}}个</span>
            </div>
            <div class="total-qty-info">
              <span>总计：{{averageTotal}} / {{remainingQty}}</span>
            </div>
          </div>
        </el-form-item>

        <!-- 自定义每包数量模式显示输入框 -->
        <el-form-item v-if="childrenTableInfoForm.splitPackageCount > 1 && packageMode === 'custom'" label="每包数量分配">
          <div class="package-qty-container">
            <div v-for="(qty, index) in packageQtyList" :key="index" class="package-qty-item">
              <label>第{{index + 1}}包：</label>
              <el-input-number
                v-model="packageQtyList[index]"
                :min="1"
                :max="remainingQty"
                placeholder="请输入数量"
                @change="validateTotalQty"
                size="small"
                style="width: 120px;"
              />
            </div>
            <div class="total-qty-info">
              <span :class="{'error-text': totalPackageQty > remainingQty}">总计：{{totalPackageQty}} / {{remainingQty}}</span>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="打印数量" prop="printCopies" v-if="childrenTableInfoForm.splitPackageCount === 1 || !childrenTableInfoForm.splitPackageCount">
          <el-input-number v-model="childrenTableInfoForm.printCopies" :min="1" :max="20" placeholder="请输入打印条码数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="childrenTableInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog v-model="batchConfigVisible" title="条码配置" width="40%">
      <el-select v-model="selectedComponents" multiple placeholder="选择并排序组成部分">
        <el-option v-for="comp in batchComponents" :key="comp" :label="comp" :value="comp" />
      </el-select>
      <template #footer>
        <el-button @click="batchConfigVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBatchConfig">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加物料信息对话框 -->
    <el-dialog title="选择物料信息" v-model="materialOpen" width='1200px' append-to-body>
      <MaterialSelectInWMS
        @selection="handleSelection"
        ref="materialSelectRef"
        v-if="materialOpen"
        :materialCategoryId="dialogForm.materialCategoryId"
      ></MaterialSelectInWMS>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
        <el-button @click="materialOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup name="Linkage" lang="ts">
import { listInstockOrder, getInstockOrder, delInstockOrder, addInstockOrder, updateInstockOrder, approveInstockOrder } from '@/api/wms/instockOrder';
import type { InstockOrderForm, InstockOrderVO } from '@/api/wms/instockOrder/types';
import { ref, onMounted, reactive, watch, computed, getCurrentInstance, toRefs, ComponentInternalInstance } from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getBaseWarehouseList} from "@/api/wms/baseWarehouse";
import {UserVO} from "@/api/system/user/types";
import {listUser} from "@/api/system/user";
import { listInstockDetail, getInstockDetail, delInstockDetail, updateInstockDetail, addInstockDetail } from '@/api/wms/instockDetail';
import { InstockDetailVO, InstockDetailQuery, InstockDetailForm } from '@/api/wms/instockDetail/types';
import {
  getMaterialList, getInstockMaterialList
} from '@/api/wms/linkage'

import MaterialSelectInWMS from "@/views/wms/baseMaterialInfo/addMaterialInWMS.vue";

import { getBaseMaterialCategoryListInWMS } from '@/api/wms/baseMaterialCategory';

import { getWmsPurchaseOrderDetailList, getWmsPurchaseOrderDetailWithStatistics } from '@/api/wms/wmsPurchaseOrderDetail';
import { getProdOrderInfoList, listOrderInfo } from '@/api/wms/orderInfo';
import { getWmsPurchaseOrderList } from '@/api/wms/wmsPurchaseOrder';
import { useRoute } from 'vue-router';
import { parseTime } from '@/utils/ruoyi';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {audit_behave,
  wms_barcode_if,
  wms_instock_type,
  approve_status,
  erp_synchronous_status,
  material_mategories,
  mes_material_categories,
  wms_allocate_status,
  wms_allocate_create,
  wms_allocate_way,
  instock_methond,
  wsm_is_inspection
} = toRefs<any>(proxy?.useDict('audit_behave', 'wms_barcode_if', 'wms_instock_type', 'approve_status', 'erp_synchronous_status', 'material_mategories', 'mes_material_categories', 'wms_allocate_status', 'wms_allocate_create', 'wms_allocate_way', 'instock_methond', 'wsm_is_inspection'));


interface User {
  date: string
  name: string
  address: string
}

const parentTableTotal = ref(0)
const dialogVisible = ref(false)
const parentTableInfoVisible = ref(false)
const parentTableApproveVisible = ref(false)
const childrenTableInfoVisible = ref(false)
// const childrenTableInfoSubmit = ref(false)
const updateDialog = ref(false)
const dialogTitle = ref('添加')
const dialogForm = ref<InstockOrderForm>({ instockType: '', orderNo: '', materialCategoryId: '', warehouseId: '' });
const parentTableInfoForm = ref<any>({
  materialCategoryId: '',
  instockType: '6',
  auditBy: '',
  warehouseCode: ''
})
const parentTableApproveForm = ref<any>({
  auditStatus: '',
  auditComments: ''
})
const childrenTableInfoForm = ref<any>({
  materialCode: '',
  instockQty: 0,
  codeYesNo: '',
  printedNum: 0,
  splitPackageCount: 1,
  printCopies: 1,
  packageQtyList: [] as number[],
  packageMode: 'average',
  batchCode: '',
  createTime: '',
})


const queryForm = ref({
  instockCode: '',
  materialCategoryId: '',
  materialCategoryName: '',
  warehouseId: '',
  instockType: '6',
  instockMethond: '',
  auditStatus: '',
  pageNum: 1,
  pageSize: 10,
})

// 获取路由实例
const route = useRoute();// 获取路由实例
// 初始化时获取路由参数并设置到查询表单
let routeInstockMethondValue = '';
if (route.query.instockMethond) {
  // 确保值是字符串类型，如果是数组则取第一个元素
  const instockMethondValue = Array.isArray(route.query.instockMethond)
    ? route.query.instockMethond[0]
    : route.query.instockMethond;
  queryForm.value.instockMethond = instockMethondValue;
  routeInstockMethondValue = instockMethondValue; // 保存路由参数值
}
// 初始化时获取路由参数并设置到查询表单
let routeInstockTypeValue = '';
if (route.query.instockType) {
  // 确保值是字符串类型，如果是数组则取第一个元素
  const instockTypeValue = Array.isArray(route.query.instockType)
    ? route.query.instockType[0]
    : route.query.instockType;
  queryForm.value.instockType = instockTypeValue;
  routeInstockTypeValue = instockTypeValue; // 保存路由参数值
}



const parentTableRef = ref()
const parentTableData = ref([])
const ids = ref([])
const childrenTableData = ref([])
const dialogtable = ref([])
const baseStoreList = ref([]);
const userList = ref([]);
const materialList = ref([]);
const parentTableLoad = ref(false)
const childrenTableLoad = ref(false)
const isView = ref(false)
const partntTableSelectCell = ref({ instockId: null })
const showSearch = ref(true)
const columns = ref([])

const state = reactive({
  showPurchaseOrderSelect: false,
  showProductionOrderSelect: false,
  purchaseOrders: [],
  productionOrders: [],
  selectedPurchaseOrder: null,
  selectedProductionOrder: null,
  isPurchaseOrderAssociated: false
});

// 获取仓库
getBaseWarehouseList(null).then(e => {
  baseStoreList.value = e.data
})

listUser({ pageNum: 1, pageSize: 99999 }).then(e => {
  userList.value = e.rows;
})
/** 提交按钮 */
const submitForm = async() => {
  if (!childrenTableInfoForm.value.instockQty || !childrenTableInfoForm.value.printedNum) {
    ElMessage.error('物料数据未加载完成，请重试')
    return
  }
  const split = Number(childrenTableInfoForm.value.splitPackageCount) || 1
  const copies = Number(childrenTableInfoForm.value.printCopies) || 1
  const remaining = remainingQty.value

  if (split > 1) {
    // 分包逻辑：根据模式选择数据源
    let finalPackageList = []
    if (packageMode.value === 'average') {
      // 平均分包模式：使用平均分包的结果
      finalPackageList = averagePackageList.value
      const total = averageTotal.value
      if (total > remaining) {
        ElMessage.error('平均分包总计不能超过剩余物料量')
        return
      }
      if (total <= 0) {
        ElMessage.error('平均分包数量必须大于0')
        return
      }
    } else {
      // 自定义模式：使用用户输入的数量
      finalPackageList = packageQtyList.value
      const total = totalPackageQty.value
      if (total > remaining) {
        ElMessage.error('每包数量总计不能超过剩余物料量')
        return
      }
      if (total <= 0) {
        ElMessage.error('每包数量必须大于0')
        return
      }
      // 检查是否有空或负数
      if (packageQtyList.value.some(qty => !qty || qty <= 0)) {
        ElMessage.error('每包数量必须大于0')
        return
      }
    }

    // 将最终的分包数量传递给后端
    childrenTableInfoForm.value.packageQtyList = finalPackageList
    childrenTableInfoForm.value.packageMode = packageMode.value // 传递模式信息
  } else {
    // 不分包逻辑
    if (split > remaining) {
      ElMessage.error('分包数量不能超过剩余物料量')
      return
    }
    if (copies < 1) {
      ElMessage.error('重复打印数量至少为1')
      return
    }
  }

  childrenTableInfoForm.value.batchCode = generateBatchCode(childrenTableInfoForm.value)
  await updateInstockDetail(childrenTableInfoForm.value)
  getChildrenTable({instockId: partntTableSelectCell.value.instockId})
  childrenTableInfoVisible.value = false
}


// 新增配置相关代码
const batchConfigVisible = ref(false)
const batchComponents = ref(['当前时间', '入库单号', '物料编码']) // 可选组成部分
const selectedComponents = ref([]) // 用户选择的有序列表
onMounted(() => {
  const saved = localStorage.getItem('batchCodeConfig')
  if (saved) selectedComponents.value = JSON.parse(saved)
})
const saveBatchConfig = () => {
  localStorage.setItem('batchCodeConfig', JSON.stringify(selectedComponents.value))
  batchConfigVisible.value = false
}
const generateBatchCode = (form) => {
  if (!selectedComponents.value.length) return '' // 或默认生成
  return selectedComponents.value.map(comp => {
    if (comp === '当前时间') return new Date().toISOString().slice(0,10).replace(/-/g, '')
    if (comp === '入库单号') return form.instockCode
    if (comp === '物料编码') return form.materialCode
    return ''
  }).join('')
}

//物料大类
let mategoryOptions = ref([]);
const getMaterialCategorySelect = async () => {
  const res = await getBaseMaterialCategoryListInWMS(null);
  mategoryOptions.value = res.data;
};


// 获取父表格数据
const getParentTable = async () => {

  await getMaterialCategorySelect();

  parentTableLoad.value = true
  await listInstockOrder(queryForm.value).then(async (e) => {
    parentTableLoad.value = false
    parentTableData.value = e.rows
    console.log(e.total)
    parentTableTotal.value = e.total
    if (e.rows.length > 0) {
      parentTableRef.value.setCurrentRow(e.rows[0])

      await getChildrenTable({instockId: e.rows[0].instockId,auditStatus: e.rows[0].auditStatus})
    } else {
      childrenTableData.value = []
    }
  })
}
const auditStatusLoad = ref(false)
// 获取子表格数据
const getChildrenTable = async (form) => {
  console.log(form.auditStatus)
  if(form.auditStatus == 1){
    auditStatusLoad.value = true;
  }else{
    auditStatusLoad.value = false;
  }
  childrenTableLoad.value = true
  console.log(form)
  await listInstockDetail(form).then(e => {
    childrenTableLoad.value = false
    console.log(e.rows)
    childrenTableData.value = e.rows
    // parentTableTotal.value = e.total
  })
}

getParentTable()
/** 打印按钮操作 */
const handlePrint = async (row?: InstockDetailVO) => {
  reset();
  const _instockDetailId = row?.instockDetailId || ids.value[0]
  const res = await getInstockDetail(_instockDetailId);
  Object.assign(childrenTableInfoForm.value, res.data);
}
// 查询
const query = async () => {
  ids.value = []
  parentTableRef.value?.clearSelection()
  await getParentTable()
}
const reset = () => {
  queryForm.value = {
    warehouseId: '',
    instockCode: '',
    materialCategoryId: '',
    materialCategoryName: '',
    instockType: '6',
    instockMethond: routeInstockMethondValue,// 使用保存的路由参数值
    auditStatus: '',
    pageNum: 1,
    pageSize: 10
  }
  getParentTable()
}

// 父表格行点击
const parentTableCellClick = async (e) => {
  partntTableSelectCell.value = e
  await getChildrenTable({instockId: e.instockId,auditStatus: e.auditStatus})
}

// 表格多选
const selectionChange = (e) => {
  ids.value = e.map(v => v.instockId)
}
// 查看
const viewDetails = (e) => {
  isView.value = true
  dialogVisible.value = true
  // viewAllocateOrder(e.aoId).then(v => {  // Comment out or remove undefined function
  //   dialogForm.value = v.data
  // })
}

// 父表格新增
const parentTableAdd = () => {
  dialogVisible.value = true;
  dialogForm.value = { instockType: '6', orderNo: '', materialCategoryId: '', warehouseId: '' };
  dialogtable.value = [];
  // 清空表单验证状态
  setTimeout(() => {
    if (dialogFormRef.value) {
      dialogFormRef.value.clearValidate();
    }
  }, 100);
};

// 父表格审批
const parentTableApprove = async (e) => {
  parentTableApproveForm.value = (await getInstockOrder(e.instockId)).data
  parentTableApproveVisible.value = true
  updateDialog.value = true
}
// 父表格修改
const parentTableUpdate = async (e?: any) => {
  let id = ref(null)
  if (e) {
    id.value = e.instockId
  } else {
    id.value = ids.value?.[0]
  }
  if (!id.value) return
  parentTableInfoForm.value = (await getInstockOrder(id.value)).data
  parentTableInfoVisible.value = true
  updateDialog.value = true
}
// 父表格删除
const parentTableDelete = async (e?: any) => {
  const delList = ref([])
  if (e) {
    delList.value = [e.instockId]
  } else {
    delList.value = ids.value
  }
  ElMessageBox.confirm(
    '确定要删除这些数据吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await delInstockOrder(delList.value.toString()).then(e => {
        ElMessage({
          type: 'success',
          message: '删除完成',
        })
        getParentTable()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消',
      })
    })

}

// 获取物料列表
const setMaterialList = (materialCategoryId) => {
  getInstockMaterialList({"materialCategoryId":materialCategoryId}).then(e => {
    materialList.value = e.data
  })
}

// 添加子表格行
// const addDialogTableCell = () => {
//   dialogtable.value.push({})
// }
const addDialogTableCell = () => {
  dialogtable.value.push({
    _showQtyInput: true,  // 确保新增行可以显示数量输入框
    instockQty: 0,        // 初始化入库数量为0
    codeYesNo: '0'        // 默认无条码
  });
}

// 新增提交
const dialogSubmit = async () => {
  // 首先进行表单验证
  if (!dialogFormRef.value) {
    ElMessage.error('表单引用未找到');
    return;
  }

  try {
    await dialogFormRef.value.validate();
  } catch (error) {
    ElMessage.error('请填写完整的表单信息');
    return;
  }

  console.log(dialogtable.value)
  // 将前端行映射为后端明细字段，并进行基本校验与过滤
  const detailList = (dialogtable.value || [])
    .map((item: any) => ({
      materialId: item.materialId,
      materialCode: item.materialCode,
      materialName: item.materialName,
      materialSpe: item.materialSpec, // 前端 materialSpec -> 后端 materialSpe
      unitName: item.materialUnit,   // 前端 materialUnit -> 后端 unitName
      instockQty: Number(item.instockQty || 0),
      codeYesNo: item.codeYesNo || '0',
      materialCategoryId: dialogForm.value.materialCategoryId,
      poDId: item.poDId // 确保采购订单物料主键传递给后端
    }))
    .filter( d =>d.materialCode && Number(d.instockQty) > 0);

  console.log(detailList)
  if (!detailList.length) {
    ElMessage.error('请添加至少一条物料且数量>0');
    return;
  }

  console.log(detailList,dialogtable.value);

  const payload: InstockOrderForm = {
    ...dialogForm.value,
    detailListBo: detailList
  };

  console.log(payload)
  addInstockOrder(payload).then(() => {
    ElMessage.success('保存成功');
    dialogVisible.value = false;
    getParentTable();
  });
}
/**
 * 入库单审批
 */
const parentTableApproveSubmit = () =>{
  approveInstockOrder(parentTableApproveForm.value).then(e=>{
    console.log(e)
    // if(e.data==0){
    //   ElMessage({
    //     type: 'error',
    //     message: '请通知对应负责人审批',
    //   })
    // }
    // if(e.data!=0){
    //   ElMessage({
    //     type: 'success',
    //     message: '审批完成',
    //   })
    // }
    parentTableApproveVisible.value = false
    getParentTable()
  })
}
const parentTableInfoSubmit = () =>{
  updateInstockOrder(parentTableInfoForm.value).then(e=>{
    ElMessage({
      type: 'success',
      message: '修改完成',
    })
    parentTableInfoVisible.value = false
    getParentTable()
  })
}

// 子表格修改
const childrenTableUpdate = async (e) => {
  const detail = (await getInstockDetail(e.instockDetailId)).data
  const remaining = Number(detail.instockQty) - Number(detail.printedNum || 0)
  if(remaining < 1){
    ElMessage.error('无剩余数量可打印')
    return
  }

  childrenTableInfoForm.value = detail
  childrenTableInfoForm.value.splitPackageCount = 1
  childrenTableInfoForm.value.printCopies = 1
  childrenTableInfoVisible.value = true
}
// 子表格数据新增删除
const tableUDelete = (row) => {

  ElMessageBox.confirm(
    '确定要删除这些数据吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const index = dialogtable.value.indexOf(row);
      console.log(index)
      dialogtable.value.splice(index,1)
    })

}

// 子表格删除
const childrenTableUDelete = (e) => {

  ElMessageBox.confirm(
    '确定要删除这些数据吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await delInstockDetail(e.instockDetailId).then(async (e) => {
        ElMessage({
          type: 'success',
          message: '删除完成',
        })
        await getChildrenTable({instockId: partntTableSelectCell.value.instockId})
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消',
      })
    })
}


/*     以下为添加物料信息对话框相关方法   */
let materialSelectRef = ref();//物料选择对话框绑定
const materialOpen = ref(false);//物料选择对话框显示
const selectType = ref(''); // 用于标识当前选择的是哪个字段
const selectedMaterial = ref(null); // 存储选中的物料完整信息
const currentRowIndex = ref(-1); // 存储当前正在编辑的行索引

/** 处理从MaterialSelect组件接收到的选择 */
const handleSelection = (row) => {
  selectedMaterial.value = row;
};

/** 提交物料BOM信息按钮 */
const submitMaterialForm = () => {
  if (!selectedMaterial.value) {
    // 如果没有选中行，则尝试从表格中获取
    selectedMaterial.value = materialSelectRef.value.tableRef.store.states.currentRow.value;
  }

  if (selectedMaterial.value) {
    if (selectType.value === 'material') {
      // 只更新当前正在编辑的行
      console.log(selectedMaterial.value);
      if (currentRowIndex.value >= 0 && dialogtable.value[currentRowIndex.value]) {
        dialogtable.value[currentRowIndex.value].materialId = selectedMaterial.value.materialId;
        dialogtable.value[currentRowIndex.value].materialName = selectedMaterial.value.materialName;
        dialogtable.value[currentRowIndex.value].materialCode = selectedMaterial.value.materialCode;
        dialogtable.value[currentRowIndex.value].unitName = selectedMaterial.value.materialUnit;
        dialogtable.value[currentRowIndex.value].materialSpe = selectedMaterial.value.materialSpec;
        // 可以根据需要添加更多字段
      }
    }
  }

  // 重置选中的物料信息和关闭对话框
  selectedMaterial.value = null;
  materialOpen.value = false;
};

/** 新增按钮操作 */
const handleMaterialAdd = (type, index) => {
  selectType.value = type;
  currentRowIndex.value = index; // 保存当前正在编辑的行索引
  materialOpen.value = true;
}

const loadPurchaseOrders = async () => {
  const res = await getWmsPurchaseOrderList(null)
  state.purchaseOrders = res.data;
};

const loadProductionOrders = async () => {
  const res = await getProdOrderInfoList(null)
  state.productionOrders = res.data;
};

watch(() => dialogForm.value.instockType, async (newVal) => {
  state.showPurchaseOrderSelect = (newVal === '1');
  state.showProductionOrderSelect = (newVal === '2');

  state.selectedPurchaseOrder = null;
  state.selectedProductionOrder = null;
  dialogtable.value = [];

  if (newVal === '1') {
    await loadPurchaseOrders();
  } else if (newVal === '2') {
    await loadProductionOrders();
  }
});

const handleAssociatePurchaseOrder = async () => {
  if (!state.selectedPurchaseOrder) return;

  const order = state.selectedPurchaseOrder;
  dialogForm.value.orderNo = order.poNo;

  try {
    // 使用新的API获取带统计数据的采购订单物料列表
    const res = await getWmsPurchaseOrderDetailWithStatistics({
      poNo: order.poNo
    });
    dialogtable.value = res.data.map(item => ({
      poDId: item.poDId, // 添加采购订单物料主键
      materialId: item.materialCode, // 修正字段名
      materialCode: item.materialCode,
      materialName: item.materialName,
      materialSpe: item.materialSpe,
      unitName: item.unitName || '',
      purchaseQty: item.purchaseQty, // 采购数量
      instockedQty: item.instockedQty || 0, // 已入库数量
      remainingQty: item.remainingQty || item.purchaseQty, // 剩余可入库数量
      instockQty: 0, // 初始化为0，让用户手动输入
      deliveryQty: item.deliveryQty, // 保存交付数量用于验证
      _showQtyInput: true // 标记显示数字输入框
    }));

    ElMessage.success('关联采购订单成功，已加载物料列表及库存信息');
  } catch (error) {
    console.error('获取采购订单物料列表失败:', error);
    ElMessage.error('获取采购订单物料列表失败，请重试');
  }
};

const handlePurchaseOrderSelect = (order) => {
  state.selectedPurchaseOrder = order;
  // 清空之前的物料列表
  dialogtable.value = [];
};

const handleProductionOrderSelect = (order) => {
  state.selectedProductionOrder = order;
  dialogForm.value.orderNo = order.orderCode;
};

// 验证入库数量
const validateQty = (row, val) => {
  if (val === null || val === undefined || val === '') {
    row.instockQty = 0;
    return;
  }

  // 确保是整数
  const intVal = parseInt(val);
  if (isNaN(intVal)) {
    row.instockQty = 0;
    return;
  }

  // 对于采购订单类型，验证不超过剩余可入库数量
  if (dialogForm.value.instockType === '1' && row.remainingQty !== undefined) {
    if (intVal > row.remainingQty) {
      row.instockQty = row.remainingQty;
      ElMessage.warning(`入库数量不能大于剩余可入库数量 ${row.remainingQty}`);
      return;
    }
  }

  // 对于其他类型，验证不超过交付数量（如果有）
  if (row.deliveryQty !== undefined && intVal > row.deliveryQty) {
    row.instockQty = row.deliveryQty;
    ElMessage.warning(`入库数量不能大于交付数量 ${row.deliveryQty}`);
  } else {
    row.instockQty = Math.max(0, intVal);
  }
};

const remainingQty = computed(() => {
  const instock = Number(childrenTableInfoForm.value.instockQty) || 0
  const printed = Number(childrenTableInfoForm.value.printedNum) || 0
  return Math.max(0, instock - printed)  // 添加 Math.max 防护负值
})

// 分包相关的响应式数据
const packageQtyList = ref([])
const packageMode = ref('average') // 分包模式：'average' 或 'custom'
const totalPackageQty = computed(() => {
  return packageQtyList.value.reduce((sum, qty) => sum + (Number(qty) || 0), 0)
})

// 平均分包的数量列表和总数
const averagePackageList = ref([])
const averageTotal = computed(() => {
  return averagePackageList.value.reduce((sum, qty) => sum + (Number(qty) || 0), 0)
})

// 分包数量变化时的处理函数
const onSplitPackageCountChange = (count) => {
  if (count > 1) {
    // 默认使用平均分包模式
    packageMode.value = 'average'

    // 初始化数组
    packageQtyList.value = new Array(count).fill(1)
    averagePackageList.value = new Array(count).fill(1)

    // 计算平均分包
    calculateAveragePackage(count)

    // 同时初始化自定义数量为平均值（作为备用）
    packageQtyList.value = [...averagePackageList.value]
  } else {
    packageQtyList.value = []
    averagePackageList.value = []
    packageMode.value = 'average'
  }
}

// 计算平均分包数量
const calculateAveragePackage = (count) => {
  const remaining = remainingQty.value
  if (remaining > 0 && count > 0) {
    const avgQty = Math.floor(remaining / count)
    const remainder = remaining % count

    for (let i = 0; i < count; i++) {
      averagePackageList.value[i] = avgQty + (i < remainder ? 1 : 0)
    }
  }
}

// 分包模式变化时的处理
const onPackageModeChange = (mode) => {
  if (mode === 'custom') {
    // 切换到自定义模式时，使用平均分包的结果作为初始值
    packageQtyList.value = [...averagePackageList.value]
  }
  // 切换到平均模式时不需要特殊处理，因为平均值已经计算好了
}

// 验证总数量是否超出限制
const validateTotalQty = () => {
  const total = totalPackageQty.value
  const remaining = remainingQty.value

  if (total > remaining) {
    ElMessage.warning(`每包数量总计不能超过剩余数量 ${remaining}`)
  }
}

const dialogFormRef = ref();
const dialogFormRules = ref({
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  // instockType: [{ required: true, message: '请选择工单类型', trigger: 'change' }]
});

const isAddDisabled = computed(() => {
  return dialogForm.value.instockType === '1';
});

</script>
<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.package-qty-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px;
  background-color: #fafafa;
}

.package-qty-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.package-qty-item label {
  min-width: 60px;
  font-size: 14px;
  color: #606266;
}

.package-preview-container {
  display: flex;
  flex-direction: column;
  gap: 6px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  background-color: #f9f9f9;
}

.package-preview-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.package-label {
  min-width: 60px;
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.package-qty {
  font-size: 14px;
  color: #409EFF;
  font-weight: bold;
}

.total-qty-info {
  padding-top: 8px;
  border-top: 1px solid #e4e7ed;
  font-weight: bold;
  text-align: right;
}

.error-text {
  color: #f56c6c;
}
</style>
