<template>
  <div class="app-container">
    <!-- 页面标题和操作按钮 -->
    <PageTitle>
      <template #buttons>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['inventory:orders:add']"
        >新增</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="medium"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:orders:edit']"
        >修改</el-button>
         <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="medium"
          @click="handleImport"
          v-hasPermi="['inventory:orders:add']"
        >导入</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="medium"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:orders:remove']"
        >删除</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:orders:export']"
        >导出</el-button>
      </template>
    </PageTitle>

    <!-- 页面容器 -->
    <div class="page-container">
      <!-- 搜索区域 -->
      <page-wrapper-search 
        :model="queryParams" 
        ref="queryForm" 
        size="small" 
        @search="handleQuery"
        @reset="resetQuery"
      >
        <el-form-item label="出库单号" prop="orderId">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入出库单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="系统编号" prop="systemNo">
          <el-input
            v-model="queryParams.systemNo"
            placeholder="请输入系统编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="出库类型" prop="orderTypeId">
          <el-input
            v-model="queryParams.orderTypeId"
            placeholder="请输入出库类型"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- 新增：订单类型查询项 -->
        <el-form-item label="订单类型" prop="orderType">
          <el-select 
            v-model="queryParams.orderType" 
            placeholder="请选择订单类型" 
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.outbound_order_type"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="批次ID" prop="batchCode">
          <el-input
            v-model="queryParams.batchCode"
            placeholder="请输入批次ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="货主" prop="ownerId">
          <el-input
            v-model="queryOwnerName"
            placeholder="请选择货主"
            readonly
            @focus="openOwnerSelector('query')"
            @click="openOwnerSelector('query')"
            :suffix-icon="''"
            clearable
          >
            <template v-if="queryOwnerName" #suffix>
              <i
                class="el-icon-circle-close el-input__icon"
                style="cursor: pointer;"
                @click.stop="clearQueryOwner"
              ></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select 
            v-model="queryParams.orderStatus" 
            placeholder="请选择订单状态" 
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.outbound_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出库日期" prop="inboundDate">
          <el-date-picker
            clearable
            v-model="queryParams.inboundDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择出库日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="目的地" prop="destination">
          <el-input
            v-model="queryParams.destination"
            placeholder="请输入目的地"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-input
            v-model="queryWarehouseName"
            placeholder="请选择仓库"
            readonly
            @focus="openWarehouseSelector('query')"
            @click="openWarehouseSelector('query')"
            :suffix-icon="''"
            clearable
          >
            <template v-if="queryWarehouseName" #suffix>
              <i
                class="el-icon-circle-close el-input__icon"
                style="cursor: pointer;"
                @click.stop="clearQueryWarehouse"
              ></i>
            </template>
          </el-input>
        </el-form-item>
      </page-wrapper-search>

      <!-- 表格容器 -->
      <div class="table-container">
        <el-table
          ref="mainTable"
          v-loading="loading"
          :data="ordersList"
          height="100%"
          @selection-change="handleSelectionChange"
          :key="tableKey"
        >
          <el-table-column type="selection" width="55" align="center" fixed />
          <el-table-column label="出库单号" align="center" prop="orderId" width="150" fixed/>
          <el-table-column label="系统编号" align="center" prop="systemNo" width="150" />
          <el-table-column label="出库类型" align="center" prop="orderTypeId" width="120">
            <template slot-scope="scope">
              <dict-tag v-if="dict.type.outbound_order_type" :options="dict.type.outbound_order_type" :value="scope.row.orderTypeId"/>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <!-- 新增：订单类型列 -->
          <el-table-column label="订单类型" align="center" prop="orderType" width="120">
            <template slot-scope="scope">
              <dict-tag v-if="dict.type.order_type" :options="dict.type.order_type" :value="scope.row.orderType"/>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="批次ID" align="center" prop="batchCode" width="120" />
          <el-table-column label="仓库" align="center" prop="warehouseName" width="120">
            <template slot-scope="scope">
              {{ scope.row.warehouseName || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="货主" align="center" prop="ownerName" width="120">
            <template slot-scope="scope">
              {{ scope.row.ownerName || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center" prop="orderStatus" width="150">
            <template slot-scope="scope">
              <dict-tag v-if="dict.type.outbound_order_status" :options="dict.type.outbound_order_status" :value="scope.row.orderStatus"/>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="出库日期" align="center" prop="inboundDate" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.inboundDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="目的地" align="center" prop="destination" width="150" />
          <el-table-column label="备注" align="center" prop="remark" width="150" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220" fixed="right">
            <template slot-scope="scope">
              <!-- 详细查看按钮 - 独立触发 -->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                v-if="scope.row.orderStatus === 2"
                @click="handleViewDetail(scope.row)"
              >详细</el-button>
              <!-- 修改按钮 - 独立触发 -->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-else
                @click="handleEditDetail(scope.row)"
                v-hasPermi="['inventory:orders:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-send"
                v-if="scope.row.orderStatus===1"
                @click="handleShip(scope.row)"
                v-hasPermi="['inventory:orders:edit']"
              >出货</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['inventory:orders:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加/修改/查看出库单主弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 主表单区域 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库单号" prop="orderId">
              <el-input v-model="form.orderId" placeholder="请输入出库单号" :disabled="isViewDetail || formDisabled.orderId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统编号" prop="systemNo">
              <el-input v-model="form.systemNo" placeholder="请输入系统编号" :disabled="isViewDetail || formDisabled.systemNo" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库类型" prop="orderTypeId">
              <el-select v-model="form.orderTypeId" placeholder="请选择入库类型" :disabled="isViewDetail || formDisabled.orderTypeId" style="width: 100%">
                <el-option 
                  v-for="item in dict.type.outbound_order_type" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                >
                  <span style="margin-left: 8px;">{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 新增：订单类型表单项 -->
          <el-col :span="12">
            <el-form-item label="订单类型" prop="orderType">
              <el-select v-model="form.orderType" placeholder="请选择订单类型" :disabled="isViewDetail || formDisabled.orderType" style="width: 100%">
                <el-option 
                  v-for="item in dict.type.order_type" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="Number(item.value)"
                >
                  <span style="margin-left: 8px;">{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="批次ID" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次ID" :disabled="isViewDetail || formDisabled.batchCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-input
                v-model="form.warehouseName"
                placeholder="请选择仓库"
                readonly
                @focus="!isViewDetail && !formDisabled.warehouseId && openWarehouseSelector('form')"
                @click="!isViewDetail && !formDisabled.warehouseId && openWarehouseSelector('form')"
                :suffix-icon="''"
                :disabled="isViewDetail || formDisabled.warehouseId"
              >
                <template v-if="form.warehouseName" #suffix>
                  <i
                    class="el-icon-circle-close el-input__icon"
                    style="cursor: pointer;"
                    @click.stop="clearFormWarehouse"
                    v-if="!isViewDetail && !formDisabled.warehouseId"
                  ></i>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货主" prop="ownerId">
              <el-input
                v-model="form.ownerName"
                placeholder="请选择货主"
                readonly
                @focus="!isViewDetail && !formDisabled.ownerId && openOwnerSelector('form')"
                @click="!isViewDetail && !formDisabled.ownerId && openOwnerSelector('form')"
                :suffix-icon="''"
                :disabled="isViewDetail || formDisabled.ownerId"
              >
                <template v-if="form.ownerName" #suffix>
                  <i
                    class="el-icon-circle-close el-input__icon"
                    style="cursor: pointer;"
                    @click.stop="clearFormOwner"
                    v-if="!isViewDetail && !formDisabled.ownerId"
                  ></i>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库日期" prop="inboundDate">
              <el-date-picker
                clearable
                v-model="form.inboundDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择出库日期"
                :disabled="isViewDetail"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目的地" prop="destination">
              <el-input v-model="form.destination" placeholder="请输入目的地" :disabled="isViewDetail" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="isViewDetail" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 明细表格区域（按物料分组展示） -->
        <el-divider content-position="center">入库单明细信息</el-divider>

        <!-- 物料分组操作区 - 仅编辑模式显示 -->
        <el-row :gutter="10" class="mb8" v-if="!isViewDetail">
          <el-col :span="2">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="openDetailDialog()">添加</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTableItem">删除</el-button>
          </el-col>
        </el-row>

        <!-- 【修改1】新增materialName展示 -->
        <div v-for="(group, materialId) in outboundOrderItemsGroup" :key="materialId" class="material-group mb10">
          <div class="group-header" style="background: #f5f7fa; padding: 8px 12px; border-radius: 4px; margin-bottom: 8px;">
            <!-- 【修改2】展示物料名称（优先取分组的materialName，无则用getMaterialName方法） -->
            <span style="font-weight: 600; margin-right: 16px;">物料：{{ group.materialName }}</span>
            <span style="color: #666;">明细数量：{{ group.items.length }} 条 </span>
            <!-- 仅编辑模式显示分组操作按钮 -->
            <el-button
              type="text"
              size="mini"
              icon="el-icon-edit"
              style="float: right; margin-right: 8px;"
              @click="editGroupDetail(materialId)"
              v-if="!isViewDetail"
            >编辑</el-button>
          </div>

          <el-table
            :data="group.items"
            :row-class-name="(params) => rowInboundOrderItemsIndex(params, group.items)"
            @selection-change="handleInboundOrderItemsSelectionChange"
            ref="inboundOrderItems"
            style="width: 100%;"
            :row-key="item => item.inventoryId"
            :disabled="isViewDetail"
          >
            <!-- 仅编辑模式显示选择列 -->
            <el-table-column type="selection" width="50" align="center" v-if="!isViewDetail" />
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column label="物料名称" prop="materialName" width="180">
              <template slot-scope="scope">
                {{ scope.row.materialName || '-' }}
              </template>
            </el-table-column>
            <!-- <el-table-column label="仓库编号" prop="warehouseId" width="150" /> -->
            <el-table-column label="库位编号" prop="locationName" width="150" />
            <el-table-column label="批次编号" prop="batchCode" width="150" />
    
            <el-table-column label="计划数量" prop="plannedQuantity" width="150"></el-table-column>
            <el-table-column label="实际数量" prop="actualQuantity" width="150"></el-table-column>
            <el-table-column label="约数" prop="divisor" width="150"></el-table-column>
            <el-table-column label="标签颜色" prop="labelColor" width="150">
              <template slot-scope="scope">
                <dict-tag v-if="dict.type.label_color" :options="dict.type.label_color" :value="scope.row.labelColor"/>
              </template>
            </el-table-column>
            <el-table-column label="单价(元)" prop="unitPrice" width="150" />
            <el-table-column label="凭证号" prop="voucherNumber" width="150" />
            <el-table-column label="发货方" prop="shippedBy" width="150" />
            <el-table-column label="备注" prop="remark" width="150" />
          </el-table>
        </div>

        <!-- 无明细提示 -->
        <div v-if="Object.keys(outboundOrderItemsGroup).length === 0" class="empty-tip" style="text-align: center; padding: 20px; color: #999;">
          暂无明细数据{{ isViewDetail ? '' : '，请点击添加按钮添加' }}
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- 仅编辑/新增模式显示确定按钮 -->
        <el-button type="primary" @click="submitForm" v-if="!isViewDetail">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 明细项添加/编辑子组件弹窗 -->
    <OutboundOrderFormWithItems
      :title="detailDialogTitle"
      :open="detailDialogOpen"
      :init-form="currentDetailItem"
      :init-details="getInitDetails()"
      :orders-id = "form.id"
      :group-data="currentGroupData"
      :outbound-order-id="form.orderId || form.outboundOrderId"
      :materialdicts="materialdicts"
      @submit="handleDetailSubmit"
      @close="detailDialogOpen = false"
      @update:open="detailDialogOpen = $event"
    />

    <!-- 货主选择组件 -->
    <OwnerSelector
      v-model="ownerSelectorVisible"
      @selected="handleOwnerSelected"
    />
    <!-- 仓库选择组件 -->
    <WarehouseSelector
      v-model="warehouseSelectorVisible"
      @selected="handleWarehouseSelected"
    />
    <!-- 库位选择组件 -->
    <LocationSelector
      v-model="locationSelectorVisible"
      :warehousesId="currentEditRowWarehousesId"
      @selected="handleLocationSelected"
    />

       <import-excel
          ref="import"
          title="导入"
          import-url="/inventory/orders/import"
          template-url="/inventory/orders/importTemplate"
          template-name="入库单导入模板"
          @success="getList"
          :show-trdc-checkbox="true"
          @orderTypeChange="handleOrderTypeChange"
          :orderTypeRequired="true"
      />
  </div>
</template>

<script>
import { listOrders, getOrders, delOrders, addOrders, updateOrders, ship } from "@/api/inventory/orders"
import { getMaterialsdicts } from "@/api/inventory/materials"

import OutboundOrderFormWithItems from './OutboundOrderFormWithItems.vue'
import WarehouseSelector from "@/views/compononents/WarehouseSelector.vue"
import LocationSelector from "@/views/compononents/LocationSelector.vue"
import OwnerSelector from "@/views/compononents/OwnerSelector.vue"
import PageTitle from "@/components/PageTitle"

import ImportExcel from "@/components/ImportExcel/index"
export default {
  name: "Orders",
  dicts: ['outbound_order_type', 'inbound_order_type', 'outbound_order_status', 'label_color','order_type'],
  components: {
    OutboundOrderFormWithItems,
    WarehouseSelector,
    LocationSelector,
    OwnerSelector,
    PageTitle,
    ImportExcel
  },
  data() {
    return {
      materialdicts:[],
      // 添加tableKey解决tableId渲染问题
      tableKey: 1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库单主表格数据
      ordersList: [],
      // 主弹窗标题
      title: "",
      // 主弹窗是否显示
      open: false,
      // 是否为详细查看模式
      isViewDetail: false,
      // 明细列表（按物料ID分组）{ materialId: { items: [], materialName: '' } }
      outboundOrderItemsGroup: {},
      // 选中的明细行
      selectedInboundOrderItems: [],
      // 明细子弹窗相关
      detailDialogOpen: false,
      detailDialogTitle: "新增明细项",
      currentDetailItem: {
        inventoryId: '',
        materialUuids: '',
        materialId: '',
        materialName: '', // 【修改4】新增materialName字段
        batchCode: '',
        warehouseId: '',
        warehouseName: '',
        locationId: '',
        locationName: '',
        plannedQuantity: 0,
        actualQuantity: 0,
        divisor: 1,
        labelColor: 0,
        unitPrice: 0.00,
        amount: 0.00,
        voucherNumber: '',
        itemStatus: 1,
        shippedAt: '',
        shippedBy: '',
        isUsed: 1,
        sortNo: 0,
        remark: ''
      },
      // 当前操作的物料分组数据
      currentGroupData: {},
      // 当前操作的物料ID
      currentMaterialId: '',
      isEditDetail: false,
      // 字段禁用状态（编辑时控制）
      formDisabled: {
        orderId: false,
        systemNo: false,
        orderTypeId: false,
        orderType: false, // 新增：订单类型禁用控制
        batchCode: false,
        warehouseId: false,
        ownerId: false,
        outboundOrderId: false
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        systemNo: null,
        orderTypeId: null,
        orderType: null, // 新增：订单类型查询参数
        batchCode: null,
        warehouseId: null,
        ownerId: null,
        orderStatus: null,
        inboundDate: null,
        destination: null,
        totalPlannedQuantity: null,
        totalActualQuantity: null,
        totalPackages: null,
        isUsed: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      },
      // 表单参数
      form: {
        totalAmount: 0.00,
        warehouseName: '',
        ownerName: '',
        ownerId: '', // 【新增】补充货主ID字段
        warehouseId: '', // 【新增】补充仓库ID字段
        orderType: null, // 新增：订单类型表单字段
      },
      // 表单校验规则
      rules: {
        orderId: [{ required: true, message: '请输入出库单号', trigger: 'blur' }],
        warehouseId: [{ required: true, message: '请选择仓库', trigger: 'blur' }],
        ownerId: [{ required: true, message: '请选择货主', trigger: 'blur' }],
        inboundDate: [{ required: true, message: '请选择出库日期', trigger: 'change' }],
        orderType: [{ required: true, message: '请选择订单类型', trigger: 'change' }], // 新增：订单类型校验
      },
      // 货主/仓库选择相关
      ownerSelectorVisible: false,
      warehouseSelectorVisible: false,
      locationSelectorVisible: false,
      ownerSelectTarget: '',
      warehouseSelectTarget: '',
      queryOwnerName: '',
      queryWarehouseName: '',
      currentEditRow: null,
      currentEditRowWarehousesId: null
    }
  },
  created() {
    // 延迟加载避免初始化渲染问题
    this.$nextTick(() => {
      this.getList()
    })
    
  },
  methods: {
     handleOrderTypeChange(selection) {
      this.form.orderTypeId = selection
    },
       /** 打开导入弹窗 */
    handleImport() {
      this.$refs.import.show()
    },
    // 仓库选择回调
    handleWarehouseSelected(warehouse) {
      if (!warehouse) return
      if (this.warehouseSelectTarget === 'query') {
        this.queryParams.warehouseId = warehouse.warehouseId || warehouse.id
        this.queryWarehouseName = warehouse.warehousesName || warehouse.name
        this.handleQuery()
      } else {
        this.form.warehouseId = warehouse.warehouseId || warehouse.id
        this.form.warehouseName = warehouse.warehousesName || warehouse.name
        
        // 更新明细中的默认仓库
        if (this.currentDetailItem) {
          this.currentDetailItem.warehouseId = warehouse.warehouseId || warehouse.id
          this.currentDetailItem.warehouseName = warehouse.warehousesName || warehouse.name
        }
      }
      this.warehouseSelectorVisible = false
    },
    // 库位选择回调
    handleLocationSelected(location) {
      if (!location || !this.currentEditRow) return
      this.currentEditRow.locationId = location.locationId || location.id
      this.currentEditRow.locationName = location.locationName || location.locationCode
      this.currentEditRow = null
      this.currentEditRowWarehousesId = null
      this.locationSelectorVisible = false
    },
    // 打开货主选择器
    openOwnerSelector(target = 'form') {
      this.ownerSelectTarget = target
      this.ownerSelectorVisible = true
    },
    // 货主选择回调（核心缺失方法）
handleOwnerSelected(owner) {
  if (!owner) return
  if (this.ownerSelectTarget === 'query') {
    this.queryParams.ownerId = owner.ownerId || owner.id
    this.queryOwnerName = owner.ownerName || owner.name
    this.handleQuery()
  } else {
    this.form.ownerId = owner.ownerId || owner.id
    this.form.ownerName = owner.ownerName || owner.name
    
    // 更新明细中的默认货主（可选）
    if (this.currentDetailItem) {
      this.currentDetailItem.ownerId = owner.ownerId || owner.id
      this.currentDetailItem.ownerName = owner.ownerName || owner.name
    }
  }
  this.ownerSelectorVisible = false
},
    // 打开仓库选择器
    openWarehouseSelector(target = 'form') {
      this.warehouseSelectTarget = target
      this.warehouseSelectorVisible = true
    },
    // 打开库位选择器
    openLocationSelector(row) {
      if (this.isViewDetail) return
      if (!row.warehouseId) {
        this.$message.warning("请先选择仓库")
        return
      }
      this.currentEditRow = row
      this.currentEditRowWarehousesId = row.warehouseId
      this.locationSelectorVisible = true
    },
    // 清空查询货主
    clearQueryOwner() {
      this.queryOwnerName = ''
      this.queryParams.ownerId = null
      this.handleQuery()
    },
    // 清空查询仓库
    clearQueryWarehouse() {
      this.queryWarehouseName = ''
      this.queryParams.warehouseId = null
      this.handleQuery()
    },
    // 清空表单货主
    clearFormOwner() {
      this.form.ownerName = ''
      this.form.ownerId = null
    },
    // 清空表单仓库
    clearFormWarehouse() {
      this.form.warehouseName = ''
      this.form.warehouseId = null
    },
    // 清空库位选择
    clearLocation(row) {
      row.locationId = null
      row.locationName = null
      row.locationCode = null
    },
    // 计算单条明细金额（实际数量 * 单价）
    calcItemAmount(row) {
      const actualQty = Number(row.actualQuantity) || 0
      const unitPrice = Number(row.unitPrice) || 0
      row.amount = actualQty * unitPrice
      // 重新计算分组和总金额
      this.calcTotalQuantity()
    },
    // 计算分组金额
    calcGroupAmount(items) {
      return items.reduce((sum, item) => sum + (Number(item.amount) || 0), 0).toFixed(2)
    },
    // 核心出货方法
    async handleShip(row) {
      try {
        // 调用ship接口提交数据到后端
        await ship({
          ...row,
          orderId: row.orderId, // 用户填写的出货单号
          outboundOrderId: row.id // 主表ID作为outboundOrderId
        })

        // 提示成功并刷新列表
        this.$modal.msgSuccess("出货操作成功，数据已提交到后端")
        this.getList()
      } catch (error) {
        // 错误处理
        this.$modal.msgError(error.msg || "出货操作失败")
      }
    },
    // 修复：获取要传递给子组件的初始化明细数据（按物料分组）
    getInitDetails() {
      // 编辑场景：传递当前物料分组的所有明细（确保子组件反显）
      if (this.isEditDetail && this.currentMaterialId) {
        const group = this.outboundOrderItemsGroup[this.currentMaterialId] || {};
        // 修复：深拷贝避免原数据被修改
        const initDetails = JSON.parse(JSON.stringify(group.items || []));
        console.log('传递给子组件的初始化明细：', initDetails);
        return initDetails;
      }
      // 新增场景：传递空数组
      return [];
    },
    // 整组编辑方法
    editGroupDetail(materialId) {
      if (!this.outboundOrderItemsGroup[materialId]) return

      this.isEditDetail = true
      this.detailDialogTitle = `编辑物料${materialId}整组明细`
      this.currentMaterialId = materialId
      // 传递整组数据到子组件
      this.currentGroupData = { ...this.outboundOrderItemsGroup[materialId] }
      // 初始化表单为分组第一条数据
      this.currentDetailItem = this.currentGroupData.items.length > 0
        ? {
            ...this.currentGroupData.items[0],
            materialName: this.currentGroupData.items[0].materialName || '', // 【修改5】传递物料名称
            plannedQuantity: Number(this.currentGroupData.items[0].plannedQuantity) || 0,
            actualQuantity: Number(this.currentGroupData.items[0].actualQuantity) || 0,
            divisor: Number(this.currentGroupData.items[0].divisor) || 1,
            labelColor: Number(this.currentGroupData.items[0].labelColor) || 0,
            unitPrice: Number(this.currentGroupData.items[0].unitPrice) || 0.00,
            amount: Number(this.currentGroupData.items[0].amount) || 0.00,
            itemStatus: Number(this.currentGroupData.items[0].itemStatus) || 1,
            warehouseName: this.currentGroupData.items[0].warehouseName || '',
            locationName: this.currentGroupData.items[0].locationName || ''
          }
        : {
            inventoryId: '',
            materialUuids: '',
            materialId: materialId,
            materialName: this.outboundOrderItemsGroup[materialId]?.materialName || '', // 【修改6】默认填充分组的物料名称
            batchCode: '',
            warehouseId: this.form.warehouseId || '',
            warehouseName: this.form.warehouseName || '',
            locationId: '',
            locationName: '',
            plannedQuantity: 0,
            actualQuantity: 0,
            divisor: 1,
            labelColor: 0,
            unitPrice: 0.00,
            amount: 0.00,
            voucherNumber: '',
            itemStatus: 1,
            shippedAt: '',
            shippedBy: '',
            isUsed: 1,
            sortNo: 0,
            remark: ''
          }
      this.$nextTick(() => {
        this.detailDialogOpen = true
      })
    },
    // 打开明细子弹窗（新增）- 支持指定物料ID
    openDetailDialog(materialId = '') {
      this.isEditDetail = false
      this.detailDialogTitle = materialId ? `新增${materialId}物料明细` : "新增明细项"
      this.currentMaterialId = materialId
      // 清空分组数据（新增时不传整组）
      this.currentGroupData = {}
      this.currentDetailItem = {
        inventoryId: '',
        materialUuids: '',
        materialId: materialId || '',
        materialName: '', // 【修改7】初始化物料名称
        batchCode: '',
        warehouseId: this.form.warehouseId || '',
        warehouseName: this.form.warehouseName || '',
        locationId: '',
        locationName: '',
        plannedQuantity: 0,
        actualQuantity: 0,
        divisor: 1,
        labelColor: 0,
        unitPrice: 0.00,
        amount: 0.00,
        voucherNumber: '',
        itemStatus: 1,
        shippedAt: '',
        shippedBy: '',
        isUsed: 1,
        sortNo: 0,
        remark: ''
      }
      this.$nextTick(() => {
        this.detailDialogOpen = true
      })
    },
    // 编辑明细项
    editDetailItem(row) {
      this.isEditDetail = true
      this.detailDialogTitle = `编辑物料${row.materialId}明细`
      this.currentMaterialId = row.materialId
      // 传递当前行所在分组的完整数据
      this.currentGroupData = this.outboundOrderItemsGroup[row.materialId] || {}
      this.currentDetailItem = JSON.parse(JSON.stringify({
        ...row,
        inventoryId: row.inventoryId || '',
        materialUuids: row.materialId || '',
        materialName: row.materialName || '', // 【修改8】赋值物料名称
        divisor: Number(row.divisor) || 1,
        itemStatus: Number(row.itemStatus) || 1,
        labelColor: Number(row.labelColor) || 0,
        plannedQuantity: Number(row.plannedQuantity) || 0,
        actualQuantity: Number(row.actualQuantity) || 0,
        unitPrice: Number(row.unitPrice) || 0.00,
        amount: Number(row.amount) || 0.00,
        warehouseName: row.warehouseName || '',
        locationName: row.locationName || '',
        remark: row.remark || ''
      }))
      this.$nextTick(() => {
        this.detailDialogOpen = true
      })
    },
handleDetailSubmit(details) {
  // 确保是数组格式
  const detailList = Array.isArray(details) ? details : [details];
  if (detailList.length === 0) {
    this.$message.warning("请填写明细数据");
    return;
  }

  const materialId = this.currentMaterialId || detailList[0]?.materialId;
  if (!materialId) {
    this.$message.warning("物料ID不能为空");
    return;
  }

  // 初始化物料分组
  if (!this.outboundOrderItemsGroup[materialId]) {
    this.outboundOrderItemsGroup[materialId] = {
      materialId: materialId,
      materialName: detailList[0]?.materialName || '', // 【修改9】初始化分组的物料名称
      items: []
    };
  }
  const group = this.outboundOrderItemsGroup[materialId];

  if (this.isEditDetail) {
    // 修复：编辑模式 - 全量替换分组数据（而非追加）
    const newDetails = detailList.map((item, idx) => {
      const amount = (Number(item.actualQuantity) || 0) * (Number(item.unitPrice) || 0);
      return {
        ...item,
        index: idx + 1,
        orderId: null, // 明细的orderId设为空
        outboundOrderId: this.form.id, // 使用主表ID作为outboundOrderId
        materialId: materialId,
        materialName: item.materialName || group.materialName || '', // 【修改10】保留物料名称
        inventoryId: item.inventoryId || '',
        itemStatus: Number(item.itemStatus) || 1,
        labelColor: Number(item.labelColor) || 0,
        divisor: Number(item.divisor) || 1,
        shippedAt: this.form.inboundDate,
        plannedQuantity: Number(item.plannedQuantity) || 0,
        actualQuantity: Number(item.actualQuantity) || 0,
        unitPrice: Number(item.unitPrice) || 0.00,
        amount: amount,
        isUsed: 1,
        sortNo: 0,
        remark: item.remark || '',
        warehouseName: item.warehouseName || this.form.warehouseName || '',
        locationName: item.locationName || '',
        batchCode: item.batchId || '' // 新增：将子组件的batchId赋值给batchCode
      };
    });

    // 全量替换分组数据
    group.items = newDetails;
    // 更新分组的物料名称（取第一条的物料名称）
    group.materialName = newDetails[0]?.materialName || group.materialName;
    this.$message.success(`成功编辑${materialId}物料组，共${newDetails.length}条明细`);
  } else {
    // 新增模式：按库存ID去重后追加
    const existingInventoryIds = new Set(group.items.map(item => item.inventoryId));
    const newDetails = detailList
      .filter(item => item.inventoryId && !existingInventoryIds.has(item.inventoryId))
      .map((item, idx) => {
        const newIndex = group.items.length + idx + 1;
        const amount = (Number(item.actualQuantity) || 0) * (Number(item.unitPrice) || 0);
        return {
          ...item,
          index: newIndex,
          orderId: null, // 明细的orderId设为空
          outboundOrderId: this.form.id || null, // 使用主表ID作为outboundOrderId
          materialId: materialId,
          materialName: item.materialName || '', // 【修改11】保留物料名称
          inventoryId: item.inventoryId || '',
          itemStatus: Number(item.itemStatus) || 1,
          labelColor: Number(item.labelColor) || 0,
          divisor: Number(item.divisor) || 1,
          plannedQuantity: Number(item.plannedQuantity) || 0,
          actualQuantity: Number(item.actualQuantity) || 0,
          unitPrice: Number(item.unitPrice) || 0.00,
          amount: amount,
          isUsed: 1,
          sortNo: 0,
          remark: item.remark || '',
          warehouseName: item.warehouseName || this.form.warehouseName || '',
          locationName: item.locationName || '',
          batchCode: item.batchId || '' // 新增：将子组件的batchId赋值给batchCode
        };
      });

    if (newDetails.length === 0) {
      this.$message.warning("该库存明细已存在，无法重复添加");
      this.detailDialogOpen = false;
      return;
    }

    group.items = [...group.items, ...newDetails];
    // 更新分组的物料名称（如果为空，取第一条的物料名称）
    if (!group.materialName) {
      group.materialName = newDetails[0]?.materialName || '';
    }
    this.$message.success(`成功新增${newDetails.length}条明细`);
  }

  // 重新计算总数和总金额
  this.calcTotalQuantity();
  this.detailDialogOpen = false;
  // 强制更新视图
  this.$forceUpdate();
},
    // 计算主表总数量和总金额
    calcTotalQuantity() {
      let totalPlanned = 0
      let totalActual = 0
      let totalPackages = 0
      let totalAmount = 0.00

      // 遍历所有物料分组计算总数
      Object.values(this.outboundOrderItemsGroup).forEach(group => {
        group.items.forEach(item => {
          const plannedQty = item.plannedQuantity !== null ? Number(item.plannedQuantity) : 0
          const actualQty = item.actualQuantity !== null ? Number(item.actualQuantity) : 0
          const divisor = item.divisor !== null ? Number(item.divisor) : 1
          const amount = item.amount !== null ? Number(item.amount) : 0

          totalPlanned += plannedQty
          totalActual += actualQty
          totalPackages += Math.ceil(actualQty / divisor)
          totalAmount += amount
        })
      })

      this.form.totalPlannedQuantity = totalPlanned
      this.form.totalActualQuantity = totalActual
      this.form.totalPackages = totalPackages
      this.form.totalAmount = totalAmount
    },
    // 生成明细表格行序号（适配分组）
    rowInboundOrderItemsIndex({ row, rowIndex }, groupItems) {
      if (row.index === undefined || row.index === null) {
        row.index = rowIndex + 1
      }
    },
    // 明细表格选择事件
    handleInboundOrderItemsSelectionChange(val) {
      this.selectedInboundOrderItems = val
    },
    // 删除选中的明细行（按分组删除）
    deleteTableItem() {
      if (this.selectedInboundOrderItems.length === 0) {
        this.$message.warning('请选择要删除的明细行')
        return
      }

      this.$modal.confirm('是否确认删除选中的明细行？').then(() => {
        // 遍历选中行，从对应物料分组中删除
        this.selectedInboundOrderItems.forEach(deleteItem => {
          const materialId = deleteItem.materialId
          if (this.outboundOrderItemsGroup[materialId]) {
            this.outboundOrderItemsGroup[materialId].items = this.outboundOrderItemsGroup[materialId].items.filter(
              item => item.inventoryId !== deleteItem.inventoryId
            )
            // 如果分组下无数据，删除该分组
            if (this.outboundOrderItemsGroup[materialId].items.length === 0) {
              delete this.outboundOrderItemsGroup[materialId]
            }
          }
        })

        this.calcTotalQuantity()
        this.$message.success('明细行删除成功')
        // 清空选中状态
        this.selectedInboundOrderItems = []
        // 刷新表格
        this.tableKey += 1
      })
    },
    /** 查询出库单主列表 */
    getList() {
      this.loading = true
      // 修改点1：查询时，将前端的orderId映射到后端的outboundOrderId参数
      const queryParams = {
        ...this.queryParams,
        outboundOrderId: this.queryParams.orderId // 映射查询参数
      }
      listOrders(queryParams).then(response => {
        // 修改点2：将后端返回的outboundOrderId映射为前端的orderId显示
        this.ordersList = (response.rows || []).map(item => ({
          ...item,
          // 注意：这里orderId显示的是后端的outboundOrderId（即用户填写的出货单号）
          orderId: item.outboundOrderId || item.orderId,
          warehouseName: item.warehouseName,
          ownerName: item.ownerName
        }))
        this.total = response.total || 0
        this.loading = false
        this.tableKey += 1
      }).catch(() => {
        this.loading = false
        this.ordersList = []
        this.total = 0
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null, // 用户填写的出货单号
        outboundOrderId: null, // 主表ID，由后端生成
        systemNo: null,
        orderTypeId: null,
        orderType: null, // 新增：订单类型重置
        batchCode: null,
        warehouseId: null,
        warehouseName: '',
        ownerId: null,
        ownerName: '',
        orderStatus: null,
        inboundDate: null,
        destination: null,
        totalPlannedQuantity: null,
        totalActualQuantity: null,
        totalPackages: null,
        totalAmount: 0.00,
        remark: null,
        isUsed: null,
        sortNo: null,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null
      }
      // 重置禁用状态
      this.formDisabled = {
        orderId: false,
        systemNo: false,
        orderTypeId: false,
        orderType: false, // 新增：订单类型禁用重置
        batchCode: false,
        warehouseId: false,
        ownerId: false,
        outboundOrderId: false
      }
      // 重置查看/编辑状态
      this.isViewDetail = false
      // 清空分组明细
      this.outboundOrderItemsGroup = {}
      this.selectedInboundOrderItems = []
      this.currentMaterialId = ''
      this.currentGroupData = {}
      // 清空查询条件中的货主/仓库
      this.queryOwnerName = ''
      this.queryWarehouseName = ''
      // 检查ref存在性
      if (this.$refs.form) {
        this.resetForm("form")
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 检查ref存在性
      if (this.$refs.queryForm) {
          this.queryParams= {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        systemNo: null,
        orderTypeId: null,
        orderType: null, // 新增：订单类型重置
        batchCode: null,
        warehouseId: null,
        ownerId: null,
        orderStatus: null,
        inboundDate: null,
        destination: null,
        totalPlannedQuantity: null,
        totalActualQuantity: null,
        totalPackages: null,
        isUsed: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      }
    }
      
      this.queryOwnerName = ''
      this.queryWarehouseName = ''
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 新增时启用所有字段
      this.formDisabled = {
        orderId: false,
        systemNo: false,
        orderTypeId: false,
        orderType: false, // 新增：订单类型启用
        batchCode: false,
        warehouseId: false,
        ownerId: false,
        outboundOrderId: false
      }
      this.open = true
      this.title = "添加出库单"
    },
    /** 详细查看操作 */
    handleViewDetail(row) {
      this.reset()
      // 详细查看模式：所有字段禁用
      this.isViewDetail = true
      const id = row.id
      getOrders(id).then(response => {
        // 修改点3：查看时，将后端返回的outboundOrderId作为orderId显示
        this.form = {
          ...response.data,
          // outboundOrderId是后端的主键ID，orderId是用户填写的出货单号
          orderId: response.data.outboundOrderId || response.data.orderId,
          warehouseName: response.data.warehouseName || response.data.warehouseId,
          ownerName: response.data.ownerName || response.data.ownerId,
          totalAmount: 0.00,
          ownerId: response.data.ownerId || '', // 【新增】赋值货主ID
          warehouseId: response.data.warehouseId || '', // 【新增】赋值仓库ID
          orderType: response.data.orderType || null, // 新增：订单类型回显
        }
        if (response.data && response.data.outboundOrderItemsList && Array.isArray(response.data.outboundOrderItemsList)) {
          // 按物料ID分组 + 库存ID去重
          const groupMap = {}
          response.data.outboundOrderItemsList.forEach(item => {
            if (!item.inventoryId) return
            const materialId = item.materialId || '未知物料'
            if (!groupMap[materialId]) {
              groupMap[materialId] = {
                materialId: materialId,
                materialName: item.materialName || '', // 【修改12】存储分组的物料名称
                items: []
              }
            }
            // 库存ID去重
            const exists = groupMap[materialId].items.some(i => i.inventoryId === item.inventoryId)
            if (!exists) {
              // 计算金额
              const amount = (Number(item.actualQuantity) || 0) * (Number(item.unitPrice) || 0)
              groupMap[materialId].items.push({
                ...item,
                index: groupMap[materialId].items.length + 1,
                inventoryId: item.inventoryId || '',
                materialName: item.materialName || '', // 【修改13】赋值物料名称
                divisor: item.divisor !== null ? Number(item.divisor) : 1,
                itemStatus: item.itemStatus !== null ? Number(item.itemStatus) : 1,
                labelColor: item.labelColor !== null ? Number(item.labelColor) : 0,
                plannedQuantity: item.plannedQuantity !== null ? Number(item.plannedQuantity) : 0,
                actualQuantity: item.actualQuantity !== null ? Number(item.actualQuantity) : 0,
                unitPrice: item.unitPrice !== null ? Number(item.unitPrice) : 0.00,
                amount: amount,
                isUsed: item.isUsed !== null ? Number(item.isUsed) : 1,
                sortNo: item.sortNo !== null ? Number(item.sortNo) : 0,
                materialUuids: item.materialId || '',
                warehouseId: item.warehouseId || '',
                warehouseName: item.warehouseName || item.warehouseId,
                locationId: item.locationId || '',
                locationName: item.locationName || item.locationCode,
                voucherNumber: item.voucherNumber || '',
                shippedAt: item.shippedAt || '',
                shippedBy: item.shippedBy || '',
                remark: item.remark || '',
                // 修改点4：明细的orderId设为空，使用outboundOrderId
                orderId: null, // 明细的orderId设为空
                outboundOrderId: response.data.id // 使用主表ID作为outboundOrderId
              })
            }
          })
          this.outboundOrderItemsGroup = groupMap
          this.calcTotalQuantity()
        }
        this.open = true
        this.title = "查看出库单"
      })
    },
    /** 编辑修改操作 */
    handleEditDetail(row) {
      this.reset()
      // 编辑时禁用核心字段
      this.formDisabled = {
        orderId: true, // 编辑时禁用出货单号修改
        systemNo: true,
        orderTypeId: true,
        orderType: true, // 新增：订单类型禁用
        batchCode: true,
        warehouseId: true,
        ownerId: true,
        outboundOrderId: true
      }
      const id = row.id || this.ids
      getOrders(id).then(response => {
        // 修改点5：编辑时，将后端返回的outboundOrderId作为orderId显示
        this.form = {
          ...response.data,
          orderId: response.data.outboundOrderId || response.data.orderId, // 显示用户填写的出货单号
          warehouseName: response.data.warehouseName || response.data.warehouseId,
          ownerName: response.data.ownerName || response.data.ownerId,
          totalAmount: 0.00,
          ownerId: response.data.ownerId || '', // 【新增】赋值货主ID
          warehouseId: response.data.warehouseId || '', // 【新增】赋值仓库ID
          orderType: response.data.orderType || null, // 新增：订单类型回显
        }
        console.log("this.form",this.form)
        if (response.data && response.data.outboundOrderItemsList && Array.isArray(response.data.outboundOrderItemsList)) {
          // 按物料ID分组 + 库存ID去重
          const groupMap = {}
          response.data.outboundOrderItemsList.forEach(item => {
            if (!item.inventoryId) return
            const materialId = item.materialId || '未知物料'
            if (!groupMap[materialId]) {
              groupMap[materialId] = {
                materialId: materialId,
                materialName: item.materialName || '', // 【修改14】存储分组的物料名称
                items: []
              }
            }
            // 库存ID去重
            const exists = groupMap[materialId].items.some(i => i.inventoryId === item.inventoryId)
            if (!exists) {
              // 计算金额
              const amount = (Number(item.actualQuantity) || 0) * (Number(item.unitPrice) || 0)
              groupMap[materialId].items.push({
                ...item,
                index: groupMap[materialId].items.length + 1,
                inventoryId: item.inventoryId || '',
                materialName: item.materialName || '', // 【修改15】赋值物料名称
                divisor: item.divisor !== null ? Number(item.divisor) : 1,
                itemStatus: item.itemStatus !== null ? Number(item.itemStatus) : 1,
                labelColor: item.labelColor !== null ? Number(item.labelColor) : 0,
                plannedQuantity: item.plannedQuantity !== null ? Number(item.plannedQuantity) : 0,
                actualQuantity: item.actualQuantity !== null ? Number(item.actualQuantity) : 0,
                unitPrice: item.unitPrice !== null ? Number(item.unitPrice) : 0.00,
                amount: amount,
                isUsed: item.isUsed !== null ? Number(item.isUsed) : 1,
                sortNo: item.sortNo !== null ? Number(item.sortNo) : 0,
                materialUuids: item.materialId || '',
                warehouseId: item.warehouseId || '',
                warehouseName: item.warehouseName || item.warehouseId,
                locationId: item.locationId || '',
                locationName: item.locationName || item.locationCode,
                voucherNumber: item.voucherNumber || '',
                shippedAt: item.shippedAt || '',
                shippedBy: item.shippedBy || '',
                remark: item.remark || '',
                // 修改点6：明细的orderId设为空
                orderId: null, // 明细的orderId设为空
                outboundOrderId: response.data.id // 使用主表ID作为outboundOrderId
              })
            }
          })
          this.outboundOrderItemsGroup = groupMap
          this.calcTotalQuantity()
        }
        this.open = true
        this.title = "修改出库单"
      })
    },
    /** 批量修改按钮兼容 */
    handleUpdate() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条数据进行修改")
        return
      }
      this.handleEditDetail({ id: this.ids[0] })
    },
    /** 修复：提交按钮（按分组整理数据提交） */
    submitForm() {
      // 检查表单ref存在性
      if (!this.$refs.form) {
        this.$message.error('表单初始化失败，请重试')
        return
      }

      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          // 检查是否有明细数据
          const hasDetails = Object.values(this.outboundOrderItemsGroup).some(group => group.items.length > 0)
          if (!hasDetails) {
            this.$message.warning('请至少添加一条明细数据')
            return
          }

          // 扁平化分组数据用于提交
          const outboundOrderItemsList = []
          Object.values(this.outboundOrderItemsGroup).forEach(group => {
            outboundOrderItemsList.push(...group.items)
          })

          // 修复：去重逻辑优化（保留最新数据）
          const uniqueDetailsMap = new Map()
          outboundOrderItemsList.forEach(item => {
            if (item.inventoryId) {
              uniqueDetailsMap.set(item.inventoryId, item)
            }
          })
          const uniqueDetails = Array.from(uniqueDetailsMap.values())

          // 修改点7：构造提交数据，适配新的字段映射规则
          const submitData = {
            ...this.form,
            outboundOrderId: this.form.id, 
            orderId: this.form.orderId, 
            orderType: this.form.orderType, // 新增：提交订单类型
            outboundOrderItemsList: uniqueDetails.map(item => {
              const { index, materialUuids, warehouseName, locationName, ...rest } = item
              return {
                ...rest,
                orderId: null,
                outboundOrderId: this.form.id || null, 
                materialName: item.materialName || '', // 【修改16】提交物料名称
                inventoryId: rest.inventoryId || '',
                materialId: rest.materialId || '',
                batchCode: rest.batchCode || '',
                warehouseId: rest.warehouseId || this.form.warehouseId || '',
                locationId: rest.locationId || '',
                plannedQuantity: Number(rest.plannedQuantity) || 0,
                actualQuantity: Number(rest.actualQuantity) || 0,
                divisor: Number(rest.divisor) || 1,
                labelColor: Number(rest.labelColor) || 0,
                unitPrice: Number(rest.unitPrice) || 0.00,
                amount: Number(rest.amount) || 0.00,
                voucherNumber: rest.voucherNumber || '',
                itemStatus: Number(rest.itemStatus) || 1,
                shippedAt: rest.shippedAt || this.form.inboundDate || '',
                shippedBy: rest.shippedBy || '',
                remark: rest.remark || '',
                isUsed: 1,
                sortNo: Number(rest.sortNo) || 0
              };
            })
          }

          // 调试：打印最终提交的数据
          console.log('最终提交的数据：', submitData)

          try {
            if (this.form.id != null) {
              await updateOrders(submitData)
              this.$modal.msgSuccess("修改成功")
            } else {
              await addOrders(submitData)
              this.$modal.msgSuccess("新增成功")
            }
            this.open = false
            this.getList()
          } catch (error) {
            if (error !== 'cancel') {
              const errorMsg = error?.response?.data?.msg || '库存被修改请重新确认'
              this.$modal.msgError(errorMsg)
            }
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const orderNo = row.orderId || ids
      this.$modal.confirm('是否确认删除出库单编号为"' + orderNo + '"的数据项？').then(async () => {
        await delOrders(ids)
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      // 适配导出参数，将orderId映射到outboundOrderId
      const exportParams = {
        ...this.queryParams,
        outboundOrderId: this.queryParams.orderId, // 映射导出参数
        orderType: this.queryParams.orderType, // 新增：导出订单类型参数
      }
      this.download('inventory/orders/export', exportParams, `orders_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
/* 页面容器样式 */
.page-container {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  margin-top: 16px;
}

/* 表格容器样式 */
.table-container {
  margin-top: 16px;
  height: calc(100vh - 280px);
}

/* 弹窗内表单滚动优化 */
.el-dialog__body {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

/* 自定义滚动条 */
.el-dialog__body::-webkit-scrollbar {
  width: 6px;
}

.el-dialog__body::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}

/* 明细表格样式优化 */
.el-table {
  --el-table-row-hover-bg-color: #f8f9fa;
}

/* 空数据提示样式 */
.empty-tip {
  color: #999;
  font-size: 14px;
}

/* 物料分组样式 */
.material-group {
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  padding: 10px;
}

.group-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.mb10 {
  margin-bottom: 10px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>