<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <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="批次ID" prop="batchCode">
        <el-input
          v-model="queryParams.batchCode"
          placeholder="请输入批次ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货主ID" prop="ownerId">
        <el-input
          v-model="queryParams.ownerId"
          placeholder="请输入货主ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.inbound_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="请选择出库日期">
        </el-date-picker>
      </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>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['inventory:orders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:orders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['inventory:orders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 主表格 -->
    <el-table 
      ref="mainTable"
      v-loading="loading" 
      :data="ordersList" 
      @selection-change="handleSelectionChange"
      :key="tableKey"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出库单号" align="center" prop="orderId" width="150" />
      <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.inbound_order_type" :options="dict.type.inbound_order_type" :value="scope.row.orderTypeId"/>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="批次ID" align="center" prop="batchCode" width="120" />
      <el-table-column label="仓库ID" align="center" prop="warehouseId" width="100" />
      <el-table-column label="货主ID" align="center" prop="ownerId" width="100" />
      <el-table-column label="订单状态" align="center" prop="orderStatus" width="150">
        <template slot-scope="scope">
          <dict-tag v-if="dict.type.inbound_order_status" :options="dict.type.inbound_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="totalPlannedQuantity" width="100" />
      <el-table-column label="实际量" align="center" prop="totalActualQuantity" width="100" />
      <el-table-column label="总件数" align="center" prop="totalPackages" width="100" />
      <el-table-column label="备注" align="center" prop="remark" width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['inventory:orders:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-send"
            @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>
    
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加/修改出库单主弹窗 -->
    <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="请输入出库单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统编号" prop="systemNo">
              <el-input v-model="form.systemNo" placeholder="请输入系统编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库类型" prop="orderTypeId">
              <el-input v-model="form.orderTypeId" placeholder="请输入入库类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次ID" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库ID" prop="warehouseId">
              <el-input v-model="form.warehouseId" placeholder="请输入仓库ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货主ID" prop="ownerId">
              <el-input v-model="form.ownerId" placeholder="请输入货主ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <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="请选择出库日期">
              </el-date-picker>
            </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="请输入目的地" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划量" prop="totalPlannedQuantity">
              <el-input v-model.number="form.totalPlannedQuantity" placeholder="请输入计划量" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="实际量" prop="totalActualQuantity">
              <el-input v-model.number="form.totalActualQuantity" placeholder="请输入实际量" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总件数" prop="totalPackages">
              <el-input v-model.number="form.totalPackages" placeholder="请输入总件数" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 明细表格区域 -->
        <el-divider content-position="center">入库单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="openDetailDialog">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTableItem">删除</el-button>
          </el-col>
        </el-row>
        <el-table 
          :data="outboundOrderItemsList" 
          :row-class-name="rowInboundOrderItemsIndex" 
          @selection-change="handleInboundOrderItemsSelectionChange" 
          ref="inboundOrderItems"
          border
          style="width: 100%;"
          v-if="outboundOrderItemsList.length > 0"
          :row-key="item => item.inventoryId" 
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column prop="inventoryId" label="库存ID" width="100" />
          <el-table-column label="货物ID" prop="materialId" width="150" />
          <el-table-column label="批次ID" prop="batchCode" width="150" />
          <el-table-column label="仓库ID" prop="warehouseId" width="150" />
          <el-table-column label="库位ID" prop="locationId" width="150" />
          <el-table-column label="计划数量" prop="plannedQuantity" width="150" />
          <el-table-column label="实际数量" prop="actualQuantity" width="150" />
          <el-table-column label="约数" prop="divisor" width="150" />
          <el-table-column label="标签颜色" prop="labelColor" width="150">
            <template slot-scope="scope">
              {{ getLabelColorText(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="itemStatus" width="150">
            <template slot-scope="scope">
              <dict-tag v-if="dict.type.inbound_order_item_status" :options="dict.type.inbound_order_item_status" :value="scope.row.itemStatus"/>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="发货时间" prop="shippedAt" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.shippedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="发货方" prop="shippedBy" width="150" />
          <el-table-column label="备注" prop="remark" width="150" />
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="editDetailItem(scope.row)"
              >编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="empty-tip" style="text-align: center; padding: 20px; color: #999;">
          暂无明细数据，请点击添加按钮添加
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 明细项添加/编辑子组件弹窗 -->
    <OutboundOrderFormWithItems
      :title="detailDialogTitle"
      :open="detailDialogOpen"
      :init-form="currentDetailItem"
      @submit="handleDetailSubmit"
      @update:open="detailDialogOpen = $event" 
    />
    
  </div>
</template>

<script>
import { listOrders, getOrders, delOrders, addOrders, updateOrders, ship } from "@/api/inventory/orders"
import OutboundOrderFormWithItems from './OutboundOrderFormWithItems.vue'

export default {
  name: "Orders",
  dicts: ['inbound_order_status', 'inbound_order_type', 'inbound_order_item_status'],
  components: {
    OutboundOrderFormWithItems
  },
  data() {
    return {
      // 添加tableKey解决tableId渲染问题
      tableKey: 1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库单主表格数据
      ordersList: [],
      // 主弹窗标题
      title: "",
      // 主弹窗是否显示
      open: false,
      // 明细列表
      outboundOrderItemsList: [],
      // 选中的明细行
      selectedInboundOrderItems: [],
      // 明细子弹窗相关
      detailDialogOpen: false,
      detailDialogTitle: "新增明细项",
      currentDetailItem: {
        inventoryId: '',
        materialUuids: '',
        materialId: '',
        batchCode: '',
        warehouseId: '',
        locationId: '',
        plannedQuantity: '',
        actualQuantity: '',
        divisor: '',
        labelColor: '',
        unitPrice: '',
        voucherNumber: '',
        itemStatus: 1,
        shippedAt: '',
        shippedBy: '',
        isUsed: 1,
        sortNo: 0,
        remark: ''
      },
      isEditDetail: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        systemNo: null,
        orderTypeId: 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: {},
      // 表单校验规则
      rules: {
        orderId: [{ required: true, message: '请输入出库单号', trigger: 'blur' }],
        warehouseId: [{ required: true, message: '请输入仓库ID', trigger: 'blur' }],
        inboundDate: [{ required: true, message: '请选择出库日期', trigger: 'change' }]
      }
    }
  },
  created() {
    // 延迟加载避免初始化渲染问题
    this.$nextTick(() => {
      this.getList()
    })
  },
  methods: {
    // 核心出货方法
    async handleShip(row) {
      try {
        // 调用ship接口提交数据到后端
        await ship(row)
        
        // 提示成功并刷新列表
        this.$modal.msgSuccess("出货操作成功，数据已提交到后端")
        this.getList()
      } catch (error) {
        // 错误处理
        this.$modal.msgError(error.msg || "出货操作失败")
      }
    },
    // 标签颜色值转文本
    getLabelColorText(value) {
      const colorMap = {
        '1': '红色',
        '2': '蓝色',
        '3': '绿色',
        '4': '黄色'
      }
      return colorMap[value] || '-'
    },
    // 打开明细子弹窗（新增）
    openDetailDialog() {
      this.isEditDetail = false
      this.detailDialogTitle = "新增明细项"
      this.currentDetailItem = {
        inventoryId: '',
        materialUuids: '',
        materialId: '',
        batchCode: '',
        warehouseId: this.form.warehouseId || '',
        locationId: '',
        plannedQuantity: '',
        actualQuantity: '',
        divisor: '',
        labelColor: '',
        unitPrice: '',
        voucherNumber: '',
        itemStatus: 1,
        shippedAt: '',
        shippedBy: '',
        isUsed: 1,
        sortNo: 0,
        remark: ''
      }
      this.detailDialogOpen = true
    },
    // 编辑明细项
    editDetailItem(row) {
      this.isEditDetail = true
      this.detailDialogTitle = "编辑明细项"
      this.currentDetailItem = { 
        ...row,
        inventoryId: row.inventoryId || '',
        materialUuids: row.materialId || '',
        divisor: row.divisor || 0,
        itemStatus: row.itemStatus || 1,
        labelColor: row.labelColor || 0,
        plannedQuantity: row.plannedQuantity || 0,
        actualQuantity: row.actualQuantity || 0,
        remark: row.remark || ''
      }
      this.detailDialogOpen = true
    },
    // 接收子组件提交的明细数据（核心修复：新增去重逻辑）
    handleDetailSubmit(details) {
      const detailList = Array.isArray(details) ? details : [details]
      
      if (this.isEditDetail) {
        // 编辑模式
        const editIndex = this.outboundOrderItemsList.findIndex(item => item.index === this.currentDetailItem.index)
        if (editIndex > -1) {
          this.outboundOrderItemsList.splice(editIndex, 1, {
            ...detailList[0],
            index: this.currentDetailItem.index,
            orderId: this.form.id || this.form.orderId,
            inventoryId: detailList[0].inventoryId || '',
            itemStatus: Number(detailList[0].itemStatus) || 1,
            labelColor: Number(detailList[0].labelColor) || 0,
            divisor: Number(detailList[0].divisor) || 0,
            plannedQuantity: Number(detailList[0].plannedQuantity) || 0,
            actualQuantity: Number(detailList[0].actualQuantity) || 0,
            isUsed: 1,
            sortNo: 0,
            remark: detailList[0].remark || ''
          })
        }
        this.$message.success("编辑明细成功")
      } else {
        // 新增模式：按库存ID去重，避免重复添加
        const existingInventoryIds = new Set(this.outboundOrderItemsList.map(item => item.inventoryId))
        // 过滤已存在的库存ID
        const newDetails = detailList
          .filter(item => item.inventoryId && !existingInventoryIds.has(item.inventoryId))
          .map((item, idx) => {
            const newIndex = this.outboundOrderItemsList.length + idx + 1
            return { 
              ...item, 
              index: newIndex,
              orderId: this.form.id || this.form.orderId,
              inventoryId: item.inventoryId || '',
              itemStatus: Number(item.itemStatus) || 1,
              labelColor: Number(item.labelColor) || 0,
              divisor: Number(item.divisor) || 0,
              plannedQuantity: Number(item.plannedQuantity) || 0,
              actualQuantity: Number(item.actualQuantity) || 0,
              isUsed: 1,
              sortNo: 0,
              remark: item.remark || ''
            }
          })
        
        // 无新数据则提示
        if (newDetails.length === 0) {
          this.$message.warning("该库存明细已存在，无法重复添加")
          this.detailDialogOpen = false
          return
        }

        this.outboundOrderItemsList = [...this.outboundOrderItemsList, ...newDetails]
        this.calcTotalQuantity()
        this.$message.success(`成功新增${newDetails.length}条明细`)
      }
      
      this.detailDialogOpen = false
      // 更新tableKey触发重新渲染
      this.tableKey += 1
    },
    // 计算主表总数量
    calcTotalQuantity() {
      const totalPlanned = this.outboundOrderItemsList.reduce((sum, item) => {
        const qty = item.plannedQuantity !== null ? Number(item.plannedQuantity) : 0
        return sum + qty
      }, 0)
      const totalActual = this.outboundOrderItemsList.reduce((sum, item) => {
        const qty = item.actualQuantity !== null ? Number(item.actualQuantity) : 0
        return sum + qty
      }, 0)
      const totalPackages = this.outboundOrderItemsList.reduce((sum, item) => {
        const divisor = item.divisor !== null ? Number(item.divisor) : 1
        const actualQty = item.actualQuantity !== null ? Number(item.actualQuantity) : 0
        return sum + Math.ceil(actualQty / divisor)
      }, 0)
      
      this.form.totalPlannedQuantity = totalPlanned
      this.form.totalActualQuantity = totalActual
      this.form.totalPackages = totalPackages
    },
    // 生成明细表格行序号
    rowInboundOrderItemsIndex({ row, rowIndex }) {
      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
      }
      const selectedIndexes = this.selectedInboundOrderItems.map(item => 
        this.outboundOrderItemsList.findIndex(row => row.index === item.index)
      )
      selectedIndexes.sort((a, b) => b - a).forEach(index => {
        this.outboundOrderItemsList.splice(index, 1)
      })
      // 重新排序序号
      this.outboundOrderItemsList.forEach((row, index) => {
        row.index = index + 1
      })
      this.calcTotalQuantity()
      this.$message.success('明细行删除成功')
    },
    /** 查询出库单主列表 */
    getList() {
      this.loading = true
      listOrders(this.queryParams).then(response => {
        this.ordersList = response.rows || []
        this.total = response.total || 0
        this.loading = false
        // 更新tableKey解决渲染问题
        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,
        systemNo: null,
        orderTypeId: null,
        batchCode: null,
        warehouseId: null,
        ownerId: null,
        orderStatus: null,
        inboundDate: null,
        destination: null,
        totalPlannedQuantity: null,
        totalActualQuantity: null,
        totalPackages: null,
        remark: null,
        isUsed: null,
        sortNo: null,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null
      }
      this.outboundOrderItemsList = []
      this.selectedInboundOrderItems = []
      // 检查ref存在性
      if (this.$refs.form) {
        this.resetForm("form")
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 检查ref存在性
      if (this.$refs.queryForm) {
        this.resetForm("queryForm")
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加出库单"
    },
    /** 修改按钮操作（修复：加载明细时去重） */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getOrders(id).then(response => {
        this.form = response.data || {}
        if (response.data && response.data.outboundOrderItemsList && Array.isArray(response.data.outboundOrderItemsList)) {
          // 按库存ID去重
          const uniqueItemsMap = new Map()
          response.data.outboundOrderItemsList.forEach(item => {
            if (item.inventoryId && !uniqueItemsMap.has(item.inventoryId)) {
              uniqueItemsMap.set(item.inventoryId, item)
            }
          })
          const uniqueItems = Array.from(uniqueItemsMap.values())
          
          this.outboundOrderItemsList = uniqueItems.map((item, index) => ({
            ...item,
            index: index + 1,
            inventoryId: item.inventoryId || '',
            divisor: item.divisor !== null ? Number(item.divisor) : 0,
            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,
            isUsed: item.isUsed !== null ? Number(item.isUsed) : 1,
            sortNo: item.sortNo !== null ? Number(item.sortNo) : 0,
            materialUuids: item.materialId || '',
            warehouseId: item.warehouseId || '',
            locationId: item.locationId || '',
            voucherNumber: item.voucherNumber || '',
            shippedAt: item.shippedAt || '',
            shippedBy: item.shippedBy || '',
            remark: item.remark || '',
            orderId: response.data.id
          }))
          this.calcTotalQuantity()
        }
        this.open = true
        this.title = "修改出库单"
      })
    },
    /** 提交按钮（修复：提交前最后去重） */
    submitForm() {
      // 检查表单ref存在性
      if (!this.$refs.form) {
        this.$message.error('表单初始化失败，请重试')
        return
      }
      
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (this.outboundOrderItemsList.length === 0) {
            this.$message.warning('请至少添加一条明细数据')
            return
          }
          // 提交前按库存ID去重
          const uniqueDetailsMap = new Map()
          this.outboundOrderItemsList.forEach(item => {
            if (item.inventoryId && !uniqueDetailsMap.has(item.inventoryId)) {
              uniqueDetailsMap.set(item.inventoryId, item)
            }
          })
          const uniqueDetails = Array.from(uniqueDetailsMap.values())
          
          const submitData = {
            ...this.form,
            outboundOrderItemsList: uniqueDetails.map(item => {
              const { index, materialUuids, ...rest } = item
              return {
                ...rest,
                orderId: this.form.id || this.form.orderId,
                inventoryId: rest.inventoryId || '',
                materialId: rest.materialId || '',
                batchCode: rest.batchCode || '',
                warehouseId: rest.warehouseId || '',
                locationId: rest.locationId || '',
                plannedQuantity: Number(rest.plannedQuantity) || 0,
                actualQuantity: Number(rest.actualQuantity) || 0,
                divisor: Number(rest.divisor) || 0,
                labelColor: Number(rest.labelColor) || 0,
                voucherNumber: rest.voucherNumber || '',
                itemStatus: Number(rest.itemStatus) || 1,
                shippedAt: rest.shippedAt || '',
                shippedBy: rest.shippedBy || '',
                remark: rest.remark || '',
                isUsed: 1,
                sortNo: Number(rest.sortNo) || 0
              }
            })
          }
          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') { // 排除用户点击取消的情况
      // 优先用后端返回的msg，没有则显示默认文案
      const errorMsg = error?.response?.data?.msg || '库存被修改请重新确认';
      this.$modal.msgError(errorMsg); // 核心弹窗代码（若依风格错误弹窗）
    }
  }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除出库单编号为"' + ids + '"的数据项？').then(async () => {
        await delOrders(ids)
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})  
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
/* 弹窗内表单滚动优化 */
.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;
}
</style>