<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.allocateOrderCode" placeholder="输入调拨单号" clearable/>
        </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="danger" plain icon="Delete" :disabled="ids.length < 1" @click="parentTableDelete(null)">删除
            </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="aoId" v-if="false"/>
        <el-table-column label="调拨单号" align="center" prop="allocateOrderCode"/>
        <el-table-column label="出库仓库" align="center" prop="planWarehouseName"/>
        <el-table-column label="工单状态" align="center" prop="orderStatus">
          <template #default="scope">
            <dict-tag :options="wms_allocate_status" :value="scope.row.orderStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="入库仓库" align="center" prop="targetWarehouseName"/>
        <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="inMethod">
          <template #default="scope">
            <dict-tag :options="wms_allocate_way" :value="scope.row.inMethod"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button size="small" @click.stop="viewDetails(scope.row)">
              查看
            </el-button>
<!--            <el-button size="small" @click.stop="parentTableUpdate(scope.row)">
              修改
            </el-button>-->
            <el-button size="small" @click.stop="parentTableApprove(scope.row)" v-if="scope.row.auditStatus == '0' ">审批
            </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="aoDId" v-if="false"/>
        <el-table-column label="调拨单号" align="center" prop="allocateCode"/>
        <el-table-column label="物料" align="center" prop="materialName"/>
        <el-table-column label="调拨数量" align="center" prop="allocateOrderQty"/>
        <el-table-column label="出库数量" align="center" prop="outSum"/>
        <el-table-column label="erp同步状态" align="center" prop="erpSynchronousStatus">
          <template #default="scope">
            <dict-tag :options="erp_synchronous_status" :value="scope.row.erpSynchronousStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="erp同步数量" align="center" prop="erpSynchronousQty"/>
        <el-table-column label="已分包数量" align="center" prop="printedQty" />
        <el-table-column label="操作" fixed="right" width="300">
          <template #default="scope">
            <el-button size="small" @click="handleAllocatePrint(scope.row)"
              v-if="partntTableSelectCell && partntTableSelectCell.auditStatus == '1' && canPrint(scope.row)"
              type="primary">
              分包打印
            </el-button>
            <el-button size="small" @click="viewPrintTasks(scope.row)">
              查看任务
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="childrenTableUDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 调拨分包打印对话框 -->
    <el-dialog title="调拨分包打印" v-model="allocatePrintDialogVisible" width="40%">
      <el-form :model="allocatePrintForm" label-width="120px">
        <el-form-item label="物料编码">
          <el-input v-model="allocatePrintForm.materialCode" readonly />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="allocatePrintForm.materialName" readonly />
        </el-form-item>
        <el-form-item label="调拨数量">
          <el-input v-model="allocatePrintForm.allocateOrderQty" readonly />
        </el-form-item>
        <el-form-item label="出库数量">
          <el-input v-model="allocatePrintForm.outSum" readonly />
        </el-form-item>
        <el-form-item label="已分包数量" prop="printedQty">
          <el-input v-model="allocatePrintForm.printedQty" readonly />
        </el-form-item>
        <el-form-item label="分包数量" prop="splitPackageCount">
          <el-input-number v-model="allocatePrintForm.splitPackageCount" :min="1" :max="allocateOrderQty" placeholder="请输入分包数量" @change="onAllocateSplitPackageCountChange" />
        </el-form-item>

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

        <!-- 平均分包模式显示分包预览 -->
        <el-form-item v-if="allocatePrintForm.splitPackageCount > 1 && allocatePackageMode === 'average'" label="分包预览">
          <div class="package-preview-container">
            <div class="package-preview-item" v-for="(qty, index) in allocateAveragePackageList" :key="index">
              <span class="package-label">第{{index + 1}}包：</span>
              <span class="package-qty">{{qty}}个</span>
            </div>
            <div class="total-qty-info">
              <span :class="{'error-text': allocateAverageTotal !== allocateOrderQty}">总计：{{allocateAverageTotal}} / {{allocateOrderQty}}</span>
              <span v-if="allocateAverageTotal !== allocateOrderQty" class="error-text"> - 必须分配完所有调拨数量</span>
            </div>
          </div>
        </el-form-item>

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

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

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%">
      <el-card shadow="never">
        <el-form :model="dialogForm" :inline="true" label-width="120px" :disabled="isView">
<!--          <el-form-item label="物料大类" prop="materialCategoryId">-->

<!--            <el-select-->
<!--              v-model="dialogForm.materialCategoryId"-->
<!--              placeholder="选择物料大类"-->
<!--              @change="setMaterialList"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in mategoryOptions"-->
<!--                :label="item.materialCategoryName"-->
<!--                :value="item.materialCategoryId"-->
<!--                :key="item.materialCategoryId"-->
<!--              />-->
<!--            </el-select>
          </el-form-item>-->
          <el-form-item label="出库仓库" prop="planWarehouseId">
            <el-select v-model="dialogForm.planWarehouseId" placeholder="请选择所属仓库" @change="setMaterialList">
              <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 label="入库仓库" prop="targetWarehouseId">
            <el-select v-model="dialogForm.targetWarehouseId" placeholder="请选择所属仓库">
              <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 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="inMethod">
            <el-select v-model="dialogForm.inMethod" placeholder="请选择入库方式">
              <el-option
                v-for="item in wms_allocate_way"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="调拨原因" prop="allocateReason">
            <el-input v-model="dialogForm.allocateReason" placeholder="请输入调拨原因" clearable />
          </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">新增</el-button>
          </el-col>
        </el-row>
        <el-table :data="dialogtable" style="width: 100%">
          <el-table-column label="字段1" prop="date" v-if="false">
            <template #default="scope">
              <el-select
                v-model="scope.row.date"
                placeholder="Select"
              >
                <el-option
                  v-for="i in material_mategories"
                  :label="i.materialName"
                  :value="i.materialId"
                  :key="i.materialId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料编码" prop="materialCode">
            <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-input
                v-model="scope.row.materialName"
                placeholder="物料名称"
                :disabled="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="批次码" prop="batchCode">
            <template #default="scope">
              <el-input
                v-model="scope.row.batchCode"
                placeholder="批次码"
                :disabled="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="库位编码" prop="locationCode">
            <template #default="scope">
              <el-input
                v-model="scope.row.locationCode"
                placeholder="库位编码"
                :disabled="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="库存数量" prop="inventoryQty">
            <template #default="scope">
              <el-input
                v-model="scope.row.inventoryQty"
                placeholder="库存数量"
                :disabled="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="调拨数量" prop="allocateOrderQty">
            <template #default="scope">
              <el-input
                v-model="scope.row.allocateOrderQty"
                style="width: 240px"
                placeholder="输入调拨数量"
                type="number"
                @blur="validateRowAllocateQty(scope.row)"
                :class="{ 'error-input': Number(scope.row.allocateOrderQty) > Number(scope.row.inventoryQty) }"
              />
              <span v-if="Number(scope.row.allocateOrderQty) > Number(scope.row.inventoryQty)" style="color: red; font-size: 12px;">
                超出库存数量
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="danger"
              @click="tableUDelete(scope.row)"
            >
              删除
            </el-button>
          </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="id" prop="planWarehouseId"v-if="false">
          <el-input v-model="parentTableInfoForm.aoId"></el-input>
        </el-form-item>
<!--        <el-form-item label="物料大类" prop="materialCategoryId">-->
<!--          <el-select-->
<!--            v-model="parentTableInfoForm.materialCategoryId"-->
<!--            placeholder="选择物料大类"-->
<!--            :disabled="updateDialog"-->
<!--            @change="setMaterialList"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="i in material_mategoryId"-->
<!--              :label="i.label"-->
<!--              :value="i.value"-->
<!--              :key="i.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="出库仓库" prop="planWarehouseId">
          <el-select v-model="parentTableInfoForm.planWarehouseId" placeholder="请选择所属仓库" :disabled="updateDialog">
            <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 label="入库仓库" prop="targetWarehouseId" >
          <el-select v-model="parentTableInfoForm.targetWarehouseId" placeholder="请选择所属仓库" :disabled="updateDialog">
            <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 label="审核人" prop="auditBy">
          <el-select v-model="parentTableInfoForm.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>
      <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="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="materialCategoryId">
          <el-select
            v-model="childrenTableInfoForm.materialCategoryId"
            placeholder="选择物料大类"
            @change="setMaterialList"
          >
            <el-option
              v-for="i in material_mategoryId"
              :label="i.label"
              :value="i.value"
              :key="i.value"
            />
          </el-select>
        </el-form-item>-->
        <el-form-item label="出库仓库" prop="planWarehouseId">
          <el-select v-model="childrenTableInfoForm.planWarehouseId" placeholder="请选择所属仓库">
            <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 label="入库仓库" prop="targetWarehouseId">
          <el-select v-model="childrenTableInfoForm.targetWarehouseId" placeholder="请选择所属仓库">
            <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 label="审核人" prop="auditBy">
          <el-select v-model="childrenTableInfoForm.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>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="childrenTableInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="childrenTableInfoSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加库存信息对话框 -->
    <el-dialog title="选择库存信息" v-model="materialOpen" width='1200px' append-to-body>
      <SelectInventoryInWMS
        @selection="handleInventorySelection"
        ref="inventorySelectRef"
        v-if="materialOpen"
        :materialCategoryId="dialogForm.materialCategoryId"
        :warehouseId="dialogForm.planWarehouseId"
      ></SelectInventoryInWMS>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInventoryForm">确 定</el-button>
        <el-button @click="materialOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分包打印对话框 -->
    <el-dialog title="调拨分包打印" v-model="printDialogVisible" width="600px" append-to-body>
      <el-form :model="printForm" label-width="120px">
        <el-form-item label="物料编码">
          <el-input v-model="printForm.materialCode" readonly />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="printForm.materialName" readonly />
        </el-form-item>
        <el-form-item label="调拨数量">
          <el-input v-model="printForm.allocateOrderQty" readonly />
        </el-form-item>
        <el-form-item label="打印模式" required>
          <el-radio-group v-model="printForm.printMode" @change="onPrintModeChange">
            <el-radio value="single">单包打印</el-radio>
            <el-radio value="package">分包打印</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分包数量" v-if="printForm.printMode === 'package'">
          <el-input-number v-model="printForm.splitPackageCount" :min="2" :max="100" @change="onSplitCountChange" />
        </el-form-item>
        <el-form-item label="打印份数" v-if="printForm.printMode === 'single'">
          <el-input-number v-model="printForm.printCopies" :min="1" :max="10" />
        </el-form-item>
        <el-form-item label="每包数量" v-if="printForm.printMode === 'package' && printForm.splitPackageCount > 1">
          <div v-for="(qty, index) in printForm.packageQtyList" :key="index" style="margin-bottom: 10px">
            <span style="width: 80px; display: inline-block">第{{index + 1}}包：</span>
            <el-input-number v-model="printForm.packageQtyList[index]" :min="1" :max="printForm.allocateOrderQty" @change="validatePackageTotal" style="width: 150px" />
          </div>
          <div style="margin-top: 10px; color: #909399">
            总计：{{ packageTotal }} / {{ printForm.allocateOrderQty }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="printDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePrintSubmit" :disabled="!isValidPackage">确定打印</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 任务查看对话框 -->
    <el-dialog title="调拨任务列表" v-model="taskDialogVisible" width="1000px" append-to-body>
      <el-table :data="taskList" style="width: 100%">
        <el-table-column label="批次码" align="center" prop="batchCode" />
        <el-table-column label="每包数量" align="center" prop="materialQty" />
        <el-table-column label="条码数量" align="center" prop="apportionQty" />
<!--        <el-table-column label="入库状态" align="center" prop="inboundStatus">
          <template #default="scope">
            <el-tag :type="scope.row.inboundStatus === '0' ? 'warning' : scope.row.inboundStatus === '1' ? 'success' : 'info'">
              {{ scope.row.inboundStatus === '0' ? '待入库' : scope.row.inboundStatus === '1' ? '已入库' : '入库中' }}
            </el-tag>
          </template>
        </el-table-column>-->
<!--        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>-->
<!--        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleTaskPrint(scope.row)"
              :disabled="scope.row.inboundStatus !== '0'">
              打印
            </el-button>
            <el-button size="small" type="warning" @click="handleTaskEdit(scope.row)"
              :disabled="scope.row.inboundStatus !== '0'">
              编辑
            </el-button>
          </template>
        </el-table-column>-->
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="taskDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑任务对话框 -->
    <el-dialog title="编辑调拨任务" v-model="editTaskDialogVisible" width="500px" append-to-body>
      <el-form :model="editTaskForm" label-width="120px">
        <el-form-item label="批次码" required>
          <el-input v-model="editTaskForm.batchCode" placeholder="请输入批次码" />
        </el-form-item>
        <el-form-item label="每包数量" required>
          <el-input-number v-model="editTaskForm.materialQty" :min="1" :max="10000" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editTaskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTaskUpdate">确定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Linkage" lang="ts">
import {
  allocateOrderDetailList,
  allocateOrderlList,
  allocateOrder,
  viewAllocateOrder,
  addAllocateOrder,
  addAllocateOrderDetail,
  getMaterialList,
  viewAllocateOrderDetail,
  delAllocateOrderDetail,
  allocateOrderUpdate,
  allocatePackagePrint,
  queryTasksByDetailId,
  validatePrintable,
  triggerPrint,
  recreateAllocateTasks,
  updateTaskBarcode,
  deleteTasksByDetailId,
  approveAllocateOrder
} from '@/api/wms/linkage'

import MaterialSelectInWMS from "@/views/wms/baseMaterialInfo/addMaterialInWMS.vue";
import SelectInventoryInWMS from "@/views/wms/inventory/selectInventoryInWMS.vue";
import {AllocateOrderForm} from '@/api/wms/allocateOrder/types';
import {AllocateOrderDetailForm} from '@/api/wms/allocateOrderDetail/types';

import {reactive} 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 { getBaseMaterialCategoryListInWMS } from '@/api/wms/baseMaterialCategory';


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


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 showSearch = ref(true)
const columns = ref([])
const updateDialog = ref(false)
const dialogTitle = ref('添加')
const dialogForm = ref<AllocateOrderForm>({})
const parentTableInfoForm = ref<AllocateOrderForm>({})
const parentTableApproveForm = ref<any>({
  auditStatus: '',
  auditComments: ''
})
const childrenTableInfoForm = ref<AllocateOrderForm>({})

const queryForm = ref({
  allocateOrderCode: '',
  pageNum: 1,
  pageSize: 10
})
const parentTableRef = ref()
const parentTableData = ref([])
const ids = ref([])
const childrenTableData = ref([])
const dialogtable = ref<AllocateOrderDetailForm[]>([])

const userList = ref([]);
const materialList = ref([]);
const parentTableLoad = ref(false)
const childrenTableLoad = ref(false)
const isView = ref(false)
const partntTableSelectCell = ref<any>({})

// 打印相关变量
const printDialogVisible = ref(false)
const printForm = ref({
  aoDId: null,
  allocateCode: '',
  materialCode: '',
  materialName: '',
  allocateOrderQty: 0,
  printMode: 'single', // single: 单包打印, package: 分包打印
  splitPackageCount: 2,
  printCopies: 1,
  packageQtyList: []
})


// 调拨分包打印相关变量
const allocatePrintDialogVisible = ref(false)
const taskDialogVisible = ref(false)
const editTaskDialogVisible = ref(false)
const taskList = ref([])
const currentTasksMap = ref(new Map()) // 存储各个调拨明细的任务列表
const allocatePrintForm = ref({
  aoDId: null,
  allocateCode: '',
  materialCode: '',
  materialName: '',
  allocateOrderQty: 0,
  outSum: 0,
  printedQty: 0,
  splitPackageCount: 1,
  printCopies: 1,
  packageQtyList: []
})
const editTaskForm = ref({
  allocateTaskId: null,
  batchCode: '',
  materialQty: 1
})

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

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

// 调拨数量（用于分包计算）
const allocateOrderQty = computed(() => {
  return Number(allocatePrintForm.value.allocateOrderQty) || 0
})

// 获取仓库
let baseStoreList = ref([]);
getBaseWarehouseList(null).then(e => {
  baseStoreList.value = e.data
})

//获取物料大类下拉框
let mategoryOptions = ref([]);
let material_mategoryId = ref([]); // 兼容原有的物料大类下拉框
const getMaterialCategorySelect = async () => {
  const res = await getBaseMaterialCategoryListInWMS(null);
  mategoryOptions.value = res.data;
  // 转换为兼容格式
  material_mategoryId.value = res.data.map(item => ({
    label: item.materialCategoryName,
    value: item.materialCategoryId
  }));
};

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

  await getMaterialCategorySelect();

  parentTableLoad.value = true
  await allocateOrderlList(queryForm.value).then(async (e) => {
    parentTableLoad.value = false
    parentTableData.value = e.rows
    parentTableTotal.value = e.total
    if (e.rows.length > 0) {
      parentTableRef.value.setCurrentRow(e.rows[0])
      await getChildrenTable({allocateCode: e.rows[0].allocateOrderCode})
    } else {
      childrenTableData.value = []
    }
  })
}

// 获取子表格数据
const getChildrenTable = async (form) => {
  childrenTableLoad.value = true
  await allocateOrderDetailList(form).then(async e => {
    childrenTableLoad.value = false
    childrenTableData.value = e.rows
    // 加载所有调拨明细的任务列表
    await loadAllTasks()
  })
}

getParentTable()

// 查询
const query = async () => {
  ids.value = []
  parentTableRef.value?.clearSelection()
  await getParentTable()
}
const reset = () => {
  queryForm.value = {
    allocateOrderCode: '',
    pageNum: 1,
    pageSize: 10
  }
  getParentTable();
}

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

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

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

}

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

// 添加子表格行
const addDialogTableCell = () => {
  dialogtable.value.push({})
}

// 新增提交
const dialogSubmit = () => {
  // 验证所有调拨数量
  let hasError = false;
  for (let i = 0; i < dialogtable.value.length; i++) {
    const row = dialogtable.value[i];
    if (!row.materialId) {
      ElMessage({
        type: 'error',
        message: `第${i + 1}行请选择库存信息`
      });
      hasError = true;
      continue;
    }
    if (!row.allocateOrderQty || row.allocateOrderQty <= 0) {
      ElMessage({
        type: 'error',
        message: `第${i + 1}行调拨数量必须大于0`
      });
      hasError = true;
      continue;
    }
    if (Number(row.allocateOrderQty) > Number(row.inventoryQty)) {
      ElMessage({
        type: 'error',
        message: `第${i + 1}行调拨数量(${row.allocateOrderQty})不能超过库存数量(${row.inventoryQty})`
      });
      hasError = true;
    }
  }

  if (hasError) {
    return;
  }

  addAllocateOrder(dialogForm.value).then(e => {
    addAllocateOrderDetail(dialogtable.value.map(item => {
        return {...item, allocateCode: e.msg,}
      }
      )
    ).then(v => {
      dialogVisible.value = false
      getParentTable()
    })

  })
}

/**
 * 调拨工单审批
 */
const parentTableApproveSubmit = () =>{
  approveAllocateOrder(parentTableApproveForm.value).then(e=>{
    ElMessage({
      type: 'success',
      message: '审批完成',
    })
    parentTableApproveVisible.value = false
    getParentTable()
  })
}

const parentTableInfoSubmit = () =>{
  allocateOrderUpdate(parentTableInfoForm.value).then(e=>{
    ElMessage({
      type: 'success',
      message: '修改完成',
    })
    parentTableInfoVisible.value = false
    getParentTable()
  })
}

const childrenTableInfoSubmit = () =>{
  // TODO: 实现子表格修改提交逻辑
  ElMessage({
    type: 'success',
    message: '修改完成',
  })
  childrenTableInfoVisible.value = false
}

// 子表格修改
const childrenTableUpdate = async (e) => {
  childrenTableInfoForm.value = (await viewAllocateOrderDetail(e.aoDId)).data
  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 delAllocateOrderDetail(e.aoDId).then(async (e) => {
        ElMessage({
          type: 'success',
          message: '删除完成',
        })
        await getChildrenTable({allocateCode: partntTableSelectCell.value.allocateOrderCode})
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消',
      })
    })
}


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

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

/** 处理从库存选择组件接收到的选择 */
const handleInventorySelection = (row) => {
  console.log('库存选择数据:', row);
  console.log('库存数量类型:', typeof row?.inventoryQty, '值:', row?.inventoryQty);
  selectedInventory.value = row;
};

/** 验证调拨数量是否超过库存数量 */
const validateAllocateQty = (allocateQty, inventoryQty) => {
  if (allocateQty > inventoryQty) {
    ElMessage({
      type: 'error',
      message: `调拨数量(${allocateQty})不能超过库存数量(${inventoryQty})`
    });
    return false;
  }
  return true;
};

/** 行级数量验证 */
const validateRowAllocateQty = (row) => {
  if (row.allocateOrderQty && row.inventoryQty) {
    const allocateQty = Number(row.allocateOrderQty);
    const inventoryQty = Number(row.inventoryQty);

    console.log(`验证数量: 调拨数量=${allocateQty}, 库存数量=${inventoryQty}`);

    if (allocateQty > inventoryQty) {
      ElMessage({
        type: 'warning',
        message: `第${dialogtable.value.indexOf(row) + 1}行调拨数量(${allocateQty})不能超过库存数量(${inventoryQty})`
      });
    }
  }
};

/** 提交库存信息按钮 */
const submitInventoryForm = () => {
  if (!selectedInventory.value) {
    // 如果没有选中行，则尝试从表格中获取
    selectedInventory.value = inventorySelectRef.value?.tableRef?.store?.states?.currentRow?.value;
  }

  if (!selectedInventory.value) {
    ElMessage({
      type: 'warning',
      message: '请选择库存信息'
    });
    return;
  }

  console.log('提交库存信息:', selectedInventory.value);
  console.log('库存数量:', selectedInventory.value.inventoryQty, '类型:', typeof selectedInventory.value.inventoryQty);

  if (selectType.value === 'material') {
    // 只更新当前正在编辑的行
    if (currentRowIndex.value >= 0 && dialogtable.value[currentRowIndex.value]) {
      dialogtable.value[currentRowIndex.value].materialId = selectedInventory.value.materialId;
      dialogtable.value[currentRowIndex.value].materialName = selectedInventory.value.materialName;
      dialogtable.value[currentRowIndex.value].materialCode = selectedInventory.value.materialCode;
      dialogtable.value[currentRowIndex.value].batchCode = selectedInventory.value.batchCode;
      dialogtable.value[currentRowIndex.value].locationCode = selectedInventory.value.locationCode;
      dialogtable.value[currentRowIndex.value].storeId = selectedInventory.value.storeId;
      // 确保库存数量为数字类型
      dialogtable.value[currentRowIndex.value].inventoryQty = Number(selectedInventory.value.inventoryQty);

      console.log('赋值后的行数据:', dialogtable.value[currentRowIndex.value]);
      console.log('赋值后的库存数量:', dialogtable.value[currentRowIndex.value].inventoryQty, '类型:', typeof dialogtable.value[currentRowIndex.value].inventoryQty);

      // 初始化调拨数量为0，由用户手动输入
      if (!dialogtable.value[currentRowIndex.value].allocateOrderQty) {
        dialogtable.value[currentRowIndex.value].allocateOrderQty = 0;
      }
    }
  }

  // 重置选中的库存信息和关闭对话框
  selectedInventory.value = null;
  materialOpen.value = false;
};

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

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

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

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

/** 判断调拨明细是否可以打印 */
const isPrintable = (row) => {
  // 可以根据业务规则添加更多条件
  return row.allocateOrderQty && row.allocateOrderQty > 0;
}

/** 判断是否存在任务 */
const hasExistingTasks = (row) => {
  const tasks = currentTasksMap.value.get(row.aoDId);
  return tasks && tasks.length > 0;
}

/** 加载调拨明细的任务列表 */
const loadTasksForDetail = async (aoDId) => {
  try {
    const result = await queryTasksByDetailId(aoDId);
    currentTasksMap.value.set(aoDId, result.data || []);
    return result.data || [];
  } catch (error) {
    console.error('查询任务错误:', error);
    return [];
  }
}

/** 初始化加载所有调拨明细的任务 */
const loadAllTasks = async () => {
  for (const detail of childrenTableData.value) {
    await loadTasksForDetail(detail.aoDId);
  }
}

/** 打印按钮点击事件 */
const childrenTablePrint = async (row) => {
  try {
    // Web端覆盖模式：直接进行打印，如果有现有任务会自动覆盖
    const hasExisting = hasExistingTasks(row);

    if (hasExisting) {
      // 检查是否满足重新打印条件：出库数量等于调拨数量
      if (Number(row.outSum) !== Number(row.allocateOrderQty)) {
        ElMessage.error(`只有出库数量等于调拨数量时才能重新打印，当前出库数量：${row.outSum}，调拨数量：${row.allocateOrderQty}`);
        return;
      }

      // 确认是否要覆盖现有任务
      await ElMessageBox.confirm(
        '该调拨明细已有打印任务，确定要重新打印并覆盖现有任务吗？',
        '确认覆盖',
        {
          confirmButtonText: '确定覆盖',
          cancelButtonText: '取消',
          type: 'warning',
        }
      );
    }
    // 调用分包打印接口（后端会自动处理覆盖逻辑）
    await allocatePackagePrint({
      allocateCode: row.allocateCode,
      aoDId: row.aoDId,
      splitPackageCount: 1,
      printCopies: 1
    });

    ElMessage.success(hasExisting ? '重新打印成功' : '创建任务成功');

    // 刷新任务列表和子表数据
    await loadTasksForDetail(row.aoDId);
    if (partntTableSelectCell.value?.allocateOrderCode) {
      await getChildrenTable({allocateCode: partntTableSelectCell.value.allocateOrderCode});
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('打印任务错误:', error);
      ElMessage.error('操作失败：' + ((error as any).response?.data?.msg || (error as any).message || '未知错误'));
    }
  }
}

/** 打印模式变化事件 */
const onPrintModeChange = () => {
  if (printForm.value.printMode === 'package') {
    onSplitCountChange();
  } else {
    printForm.value.packageQtyList = [];
  }
}

/** 分包数量变化事件 */
const onSplitCountChange = () => {
  const count = printForm.value.splitPackageCount;
  const avgQty = Math.floor(printForm.value.allocateOrderQty / count);
  const remainder = printForm.value.allocateOrderQty % count;

  printForm.value.packageQtyList = [];
  for (let i = 0; i < count; i++) {
    // 将余数分配给前几包
    const qty = i < remainder ? avgQty + 1 : avgQty;
    printForm.value.packageQtyList.push(qty);
  }
}

/** 验证分包总数 */
const validatePackageTotal = () => {
  // 将触发计算属性重新计算
  console.log('当前分包总计:', packageTotal.value);
}

/** 计算属性：分包总数 */
const packageTotal = computed(() => {
  return printForm.value.packageQtyList.reduce((sum, qty) => sum + (Number(qty) || 0), 0);
})

/** 计算属性：验证分包是否有效 */
const isValidPackage = computed(() => {
  if (printForm.value.printMode === 'single') {
    return printForm.value.printCopies > 0;
  } else {
    return packageTotal.value === printForm.value.allocateOrderQty &&
           printForm.value.packageQtyList.every(qty => Number(qty) > 0);
  }
})

/** 重新创建任务 */
const recreateTasks = async (row) => {
  try {
    // 初始化打印表单
    printForm.value = {
      aoDId: row.aoDId,
      allocateCode: row.allocateCode,
      materialCode: row.materialCode,
      materialName: row.materialName || '',
      allocateOrderQty: Number(row.allocateOrderQty),
      printMode: 'single',
      splitPackageCount: 2,
      printCopies: 1,
      packageQtyList: []
    };

    printDialogVisible.value = true;
  } catch (error) {
    console.error('重新创建错误:', error);
    ElMessage.error('重新创建失败');
  }
}

/** 删除所有任务 */
const deleteAllTasks = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该调拨明细的所有任务吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    await deleteTasksByDetailId(row.aoDId);
    ElMessage.success('删除成功');

    // 更新任务列表
    await loadTasksForDetail(row.aoDId);
    // 刷新子表数据
    if (partntTableSelectCell.value.allocateOrderCode) {
      await getChildrenTable({allocateCode: partntTableSelectCell.value.allocateOrderCode});
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除任务错误:', error);
      ElMessage.error('删除任务失败：' + ((error as any).response?.data?.msg || (error as any).message || '未知错误'));
    }
  }
}


const handlePrintSubmit = async () => {
  try {
    if (!isValidPackage.value) {
      ElMessage.error('请正确设置打印参数');
      return;
    }

    // 判断是创建新任务还是重新创建
    const hasExisting = hasExistingTasks({ aoDId: printForm.value.aoDId });

    const params = {
      aoDId: printForm.value.aoDId,
      splitPackageCount: printForm.value.printMode === 'package' ? printForm.value.splitPackageCount : 1,
      packageQtyList: printForm.value.printMode === 'package' ? printForm.value.packageQtyList : null
    };

    if (hasExisting) {
      // 重新创建任务
      await recreateAllocateTasks(params);
      ElMessage.success('重新创建任务成功');
    } else {
      // 创建新任务
      const createParams = {
        ...params,
        allocateCode: printForm.value.allocateCode,
        printCopies: printForm.value.printMode === 'single' ? printForm.value.printCopies : 1
      };
      await allocatePackagePrint(createParams);
      ElMessage.success('创建任务成功');
    }

    printDialogVisible.value = false;

    // 刷新任务列表和子表数据
    await loadTasksForDetail(printForm.value.aoDId);
    if (partntTableSelectCell.value.allocateOrderCode) {
      await getChildrenTable({allocateCode: partntTableSelectCell.value.allocateOrderCode});
    }
  } catch (error) {
    console.error('操作错误:', error);
    ElMessage.error('操作失败：' + ((error as any).response?.data?.msg || (error as any).message || '未知错误'));
  }
}

const canReprint = (row) => {
  // outSum是double类型，allocateOrderQty是BigDecimal类型，需要进行数值比较
  return Number(row.outSum) === Number(row.allocateOrderQty);
}

const canDelete = (row) => {
  // outSum是double类型，allocateOrderQty是BigDecimal类型，需要进行数值比较
  return Number(row.outSum) === Number(row.allocateOrderQty);
}

/** 判断是否可以打印 */
const canPrint = (row) => {
  // 只有出库数量等于调拨数量时才能打印
  return Number(row.outSum) === Number(row.allocateOrderQty);
}

/** 调拨分包打印按钮点击事件 */
const handleAllocatePrint = (row) => {
  // 检查打印条件
  if (!canPrint(row)) {
    ElMessage.error(`只有出库数量等于调拨数量时才能打印，当前出库数量：${row.outSum}，调拨数量：${row.allocateOrderQty}`);
    return;
  }

  // 初始化打印表单
  allocatePrintForm.value = {
    aoDId: row.aoDId,
    allocateCode: row.allocateCode,
    materialCode: row.materialCode,
    materialName: row.materialName || '',
    allocateOrderQty: Number(row.allocateOrderQty),
    outSum: Number(row.outSum),
    printedQty: Number(row.printedQty || 0),
    splitPackageCount: 1,
    printCopies: 1,
    packageQtyList: []
  };

  allocatePrintDialogVisible.value = true;
}

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

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

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

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

/** 计算平均分包数量 */
const calculateAllocateAveragePackage = (count) => {
  const totalQty = allocateOrderQty.value  // 使用调拨数量
  if (totalQty > 0 && count > 0) {
    const avgQty = Math.floor(totalQty / count)
    const remainder = totalQty % count

    allocateAveragePackageList.value = []
    for (let i = 0; i < count; i++) {
      // 前面的包分配 avgQty + 1（如果有余数），后面的包分配 avgQty
      allocateAveragePackageList.value[i] = avgQty + (i < remainder ? 1 : 0)
    }
  }
}

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

/** 验证总数量是否超出限制 */
const validateAllocateTotalQty = () => {
  const total = allocateTotalPackageQty.value
  const totalQty = allocateOrderQty.value

  if (total > totalQty) {
    ElMessage.warning(`每包数量总计不能超过调拨数量 ${totalQty}`)
  }

  // 分包数量大于1时，必须分配完所有调拨数量
  if (allocatePrintForm.value.splitPackageCount > 1 && total !== totalQty) {
    ElMessage.warning(`分包数量大于1时，每包数量总计必须等于调拨数量 ${totalQty}`)
  }
}

/** 计算属性：验证分包是否有效 */
const isValidAllocatePackage = computed(() => {
  if (allocatePrintForm.value.splitPackageCount === 1) {
    return allocatePrintForm.value.printCopies > 0;
  } else {
    return allocateAverageTotal.value === allocateOrderQty.value &&
           allocateAveragePackageList.value.every(qty => Number(qty) > 0);
  }
})

/** 提交调拨分包打印 */
const submitAllocatePrintForm = async () => {
  try {
    if (!isValidAllocatePackage.value) {
      ElMessage.error('请正确设置打印参数');
      return;
    }

    const params = {
      aoDId: allocatePrintForm.value.aoDId,
      allocateCode: allocatePrintForm.value.allocateCode,
      splitPackageCount: allocatePrintForm.value.splitPackageCount,
      printCopies: allocatePrintForm.value.printCopies || 1,
      packageQtyList: allocatePrintForm.value.splitPackageCount > 1
        ? (allocatePackageMode.value === 'average' ? allocateAveragePackageList.value : allocatePackageQtyList.value)
        : null
    };

    await allocatePackagePrint(params);
    ElMessage.success('分包打印成功');
    allocatePrintDialogVisible.value = false;

    // 刷新子表数据
    if (partntTableSelectCell.value?.allocateOrderCode) {
      await getChildrenTable({allocateCode: partntTableSelectCell.value.allocateOrderCode});
    }
  } catch (error) {
    console.error('分包打印错误:', error);
    ElMessage.error('分包打印失败：' + ((error as any).response?.data?.msg || (error as any).message || '未知错误'));
  }
}

/** 查看任务按钮点击事件 */
const viewPrintTasks = async (row) => {
  try {
    const result = await queryTasksByDetailId(row.aoDId);
    taskList.value = result.data || [];
    taskDialogVisible.value = true;
  } catch (error) {
    console.error('查询任务错误:', error);
    ElMessage.error('查询任务失败');
  }
}

/** 任务打印按钮点击 */
const handleTaskPrint = async (task) => {
  try {
    await triggerPrint(task.allocateTaskId);
    ElMessage.success('打印成功');
  } catch (error) {
    console.error('打印错误:', error);
    ElMessage.error('打印失败：' + ((error as any).response?.data?.msg || (error as any).message || '未知错误'));
  }
}

/** 任务编辑按钮点击 */
const handleTaskEdit = (task) => {
  editTaskForm.value = {
    allocateTaskId: task.allocateTaskId,
    batchCode: task.batchCode,
    materialQty: task.materialQty
  };
  editTaskDialogVisible.value = true;
}

/** 任务更新 */
const handleTaskUpdate = async () => {
  try {
    if (!editTaskForm.value.batchCode) {
      ElMessage.error('请输入批次码');
      return;
    }
    if (!editTaskForm.value.materialQty || editTaskForm.value.materialQty <= 0) {
      ElMessage.error('请输入正确的数量');
      return;
    }

    await updateTaskBarcode(editTaskForm.value);
    ElMessage.success('修改成功');
    editTaskDialogVisible.value = false;

    // 刷新任务列表
    const currentDetailId = taskList.value[0]?.aoDId;
    if (currentDetailId) {
      const result = await queryTasksByDetailId(currentDetailId);
      taskList.value = result.data || [];
    }
  } catch (error) {
    console.error('修改任务错误:', error);
    ElMessage.error('修改失败：' + ((error as any).response?.data?.msg || (error as any).message || '未知错误'));
  }
}

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

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

.error-input .el-input__wrapper {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

.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>
