package com.xunhong.erp.turbo.biz.infrastructure.gateway;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xunhong.erp.turbo.api.biz.dto.cmd.*;
import com.xunhong.erp.turbo.api.biz.dto.common.*;
import com.xunhong.erp.turbo.api.biz.dto.enums.*;
import com.xunhong.erp.turbo.api.biz.dto.qry.*;
import com.xunhong.erp.turbo.api.biz.exception.BizErrorCode;
import com.xunhong.erp.turbo.api.biz.exception.BizException;
import com.xunhong.erp.turbo.biz.domain.entity.Order;
import com.xunhong.erp.turbo.biz.domain.gateway.OrderGateway;
import com.xunhong.erp.turbo.biz.infrastructure.convert.*;
import com.xunhong.erp.turbo.biz.infrastructure.entity.*;
import com.xunhong.erp.turbo.biz.infrastructure.mapper.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author shenyifei
 */
@Repository
@RequiredArgsConstructor
public class OrderGatewayImpl implements OrderGateway {
	private final OrderMapper orderMapper;
	private final OrderConvert orderConvert;

	private final OrderVehicleMapper orderVehicleMapper;
	private final OrderVehicleConvert orderVehicleConvert;

	private final OrderSupplierMapper orderSupplierMapper;

	private final OrderCostMapper orderCostMapper;

	private final OrderCostItemMapper orderCostItemMapper;
	private final OrderCostItemConvert orderCostItemConvert;

	private final OrderPackageMapper orderPackageMapper;
	private final OrderPackageConvert orderPackageConvert;

	private final OrderDealerMapper orderDealerMapper;
	private final OrderDealerConvert orderDealerConvert;

	private final OrderCompanyMapper orderCompanyMapper;
	private final OrderCompanyConvert orderCompanyConvert;

	private final OrderRebateMapper orderRebateMapper;

	private final OrderShipMapper orderShipMapper;
	private final OrderShipConvert orderShipConvert;
	private final OrderShipItemMapper orderShipItemMapper;
	private final OrderShipItemConvert orderShipItemConvert;

	private final SupplierMapper supplierMapper;
	private final SupplierConvert supplierConvert;

	private final DealerMapper dealerMapper;

	@Override
	@Transactional
	public Order save(OrderCreateCmd orderCreateCmd) {
		Order order = saveStep1(orderConvert.toOrderStep1Cmd(orderCreateCmd));
		orderCreateCmd.setOrderId(order.getOrderId());
		saveStep2(orderConvert.toOrderStep2Cmd(orderCreateCmd));
		saveStep3(orderConvert.toOrderStep3Cmd(orderCreateCmd));
		return order;
	}

	@Override
	public IPage<Order> page(OrderPageQry orderPageQry) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.like(StrUtil.isNotBlank(orderPageQry.getOrderSn()), OrderDO::getOrderSn, orderPageQry.getOrderSn());
		queryWrapper.eq(Objects.nonNull(orderPageQry.getState()), OrderDO::getState, orderPageQry.getState());
		queryWrapper.eq(Objects.nonNull(orderPageQry.getAuditState()), OrderDO::getAuditState, orderPageQry.getAuditState());
		queryWrapper.eq(Objects.nonNull(orderPageQry.getCreatedBy()), OrderDO::getCreatedBy, orderPageQry.getCreatedBy());
		queryWrapper.eq(Objects.nonNull(orderPageQry.getType()), OrderDO::getType, orderPageQry.getType());

		queryWrapper.orderByDesc(OrderDO::getCreatedAt);

		IPage<OrderDO> page = new Page<>(orderPageQry.getPageIndex(), orderPageQry.getPageSize());
		page = orderMapper.selectPage(page, queryWrapper, orderPageQry);

		List<Long> orderIdList = page.getRecords().stream().map(OrderDO::getOrderId).toList();
		if (CollUtil.isNotEmpty(orderIdList)) {
			List<OrderVehicleDO> orderVehicleDOList = orderVehicleMapper.selectList(Wrappers.lambdaQuery(OrderVehicleDO.class).in(OrderVehicleDO::getOrderId, orderIdList));
			Map<Long, OrderVehicleDO> orderVehicleDOMap = orderVehicleDOList.stream().collect(Collectors.toMap(OrderVehicleDO::getOrderId, Function.identity()));

			List<OrderSupplierDO> orderSupplierDOList = orderSupplierMapper.selectList(Wrappers.lambdaQuery(OrderSupplierDO.class).in(OrderSupplierDO::getOrderId, orderIdList));

			page.getRecords().forEach(orderDO -> {
				orderDO.setOrderVehicleDO(orderVehicleDOMap.get(orderDO.getOrderId()));
				orderDO.setOrderSupplierDOList(orderSupplierDOList.stream().filter(orderSupplierDO -> orderSupplierDO.getOrderId().equals(orderDO.getOrderId())).toList());
			});
		}

		return page.convert(orderConvert::toOrder);
	}

	@Override
	public List<Order> list(OrderListQry orderListQry) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.like(StrUtil.isNotBlank(orderListQry.getOrderSn()), OrderDO::getOrderSn, orderListQry.getOrderSn());
		queryWrapper.eq(Objects.nonNull(orderListQry.getState()), OrderDO::getState, orderListQry.getState());
		queryWrapper.eq(Objects.nonNull(orderListQry.getAuditState()), OrderDO::getAuditState, orderListQry.getAuditState());
		queryWrapper.eq(Objects.nonNull(orderListQry.getCreatedBy()), OrderDO::getCreatedBy, orderListQry.getCreatedBy());
		queryWrapper.eq(Objects.nonNull(orderListQry.getType()), OrderDO::getType, orderListQry.getType());
		queryWrapper.select(OrderDO::getOrderId, OrderDO::getOrderSn, OrderDO::getState, OrderDO::getAuditState, OrderDO::getType);

		queryWrapper.orderByDesc(OrderDO::getCreatedAt);
		List<OrderDO> orderDOList = orderMapper.selectList(queryWrapper);
		return orderDOList.stream().map(orderConvert::toOrder).toList();
	}

	@Override
	@Transactional
	public Order update(OrderUpdateCmd orderUpdateCmd) {
		return save(orderUpdateCmd);
	}

	@Override
	public Order show(OrderShowQry orderShowQry) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getOrderId, orderShowQry.getOrderId());
		queryWrapper.eq(Objects.nonNull(orderShowQry.getType()), OrderDO::getType, orderShowQry.getType());

		queryWrapper.last("limit 1");

		OrderDO orderDO = orderMapper.selectOne(queryWrapper);

		if (Objects.nonNull(orderDO)) {
			LambdaQueryWrapper<OrderVehicleDO> queryWrapper2 = Wrappers.lambdaQuery(OrderVehicleDO.class);
			queryWrapper2.eq(OrderVehicleDO::getOrderId, orderDO.getOrderId());
			OrderVehicleDO orderVehicleDO = orderVehicleMapper.selectOne(queryWrapper2);
			orderDO.setOrderVehicleDO(orderVehicleDO);

			LambdaQueryWrapper<OrderDealerDO> queryWrapper3 = Wrappers.lambdaQuery(OrderDealerDO.class);
			queryWrapper3.eq(OrderDealerDO::getOrderId, orderDO.getOrderId());
			OrderDealerDO orderDealerDO = orderDealerMapper.selectOne(queryWrapper3);

			orderDO.setOrderDealerDO(orderDealerDO);

			// 查询公司信息
			LambdaQueryWrapper<OrderCompanyDO> companyQueryWrapper = Wrappers.lambdaQuery(OrderCompanyDO.class);
			companyQueryWrapper.eq(OrderCompanyDO::getOrderId, orderDO.getOrderId());
			OrderCompanyDO orderCompanyDO = orderCompanyMapper.selectOne(companyQueryWrapper);
			orderDO.setOrderCompanyDO(orderCompanyDO);

			// 查询返点信息
			LambdaQueryWrapper<OrderRebateDO> rebateQueryWrapper = Wrappers.lambdaQuery(OrderRebateDO.class);
			rebateQueryWrapper.eq(OrderRebateDO::getOrderId, orderDO.getOrderId());
			OrderRebateDO orderRebateDO = orderRebateMapper.selectOne(rebateQueryWrapper);
			orderDO.setOrderRebateDO(orderRebateDO);

			List<OrderSupplierDO> orderSupplierDOList = orderSupplierMapper.selectList(Wrappers.lambdaQuery(OrderSupplierDO.class).eq(OrderSupplierDO::getOrderId, orderDO.getOrderId()));
			List<Long> orderSupplierIdList = orderSupplierDOList.stream().map(OrderSupplierDO::getOrderSupplierId).toList();

			LambdaQueryWrapper<OrderPackageDO> queryWrapper1 = Wrappers.lambdaQuery(OrderPackageDO.class);
			queryWrapper1.eq(OrderPackageDO::getOrderId, orderDO.getOrderId());
			List<OrderPackageDO> orderPackageDOList = orderPackageMapper.selectList(queryWrapper1);

			orderDO.setOrderPackageDOList(orderPackageDOList.stream().filter(orderPackageDO -> Objects.isNull(orderPackageDO.getOrderSupplierId())).toList());

			if (CollUtil.isNotEmpty(orderSupplierIdList)) {
				orderSupplierDOList.forEach(orderSupplierDO -> {
					orderSupplierDO.setOrderPackageDOList(orderPackageDOList.stream().filter(orderPackageDO -> orderSupplierDO.getOrderSupplierId().equals(orderPackageDO.getOrderSupplierId())).toList());
				});
			}

			orderDO.setOrderSupplierDOList(orderSupplierDOList);

			LambdaQueryWrapper<OrderCostDO> queryWrapper4 = Wrappers.lambdaQuery(OrderCostDO.class);
			queryWrapper4.eq(OrderCostDO::getOrderId, orderDO.getOrderId());
			List<OrderCostDO> orderCostDOList = orderCostMapper.selectList(queryWrapper4);
			orderDO.setOrderCostDOList(orderCostDOList);

			LambdaQueryWrapper<OrderCostItemDO> queryWrapper5 = Wrappers.lambdaQuery(OrderCostItemDO.class);
			queryWrapper5.eq(OrderCostItemDO::getOrderId, orderDO.getOrderId());
			List<OrderCostItemDO> orderCostItemDOList = orderCostItemMapper.selectList(queryWrapper5);
			orderDO.setOrderCostItemDOList(orderCostItemDOList);

			LambdaQueryWrapper<OrderShipDO> queryWrapper6 = Wrappers.lambdaQuery(OrderShipDO.class);
			queryWrapper6.eq(OrderShipDO::getOrderId, orderDO.getOrderId());
			queryWrapper6.eq(Objects.nonNull(orderShowQry.getOrderShipId()), OrderShipDO::getOrderShipId, orderShowQry.getOrderShipId());
			List<OrderShipDO> orderShipDOList = orderShipMapper.selectList(queryWrapper6);

			LambdaQueryWrapper<OrderShipItemDO> queryWrapper7 = Wrappers.lambdaQuery(OrderShipItemDO.class);
			queryWrapper7.eq(OrderShipItemDO::getOrderId, orderDO.getOrderId());
			List<OrderShipItemDO> orderShipItemDOList = orderShipItemMapper.selectList(queryWrapper7);

			if (CollUtil.isNotEmpty(orderShipDOList)) {
				orderShipDOList.forEach(orderShipDO -> {
					orderShipDO.setOrderShipItemDOList(orderShipItemDOList.stream().filter(orderShipItemDO -> orderShipItemDO.getOrderShipId().equals(orderShipDO.getOrderShipId())).toList());
				});
			}
			orderDO.setOrderShipDOList(orderShipDOList);


		}

		return orderConvert.toOrder(orderDO);
	}

	@Override
	public void destroy(OrderDestroyCmd orderDestroyCmd) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getOrderId, orderDestroyCmd.getOrderId());
		queryWrapper.last("limit 1");

		OrderDO orderDO = orderMapper.selectOne(queryWrapper);
		orderDO.deleteById();
	}

	@Override
	public void approve(OrderApproveCmd orderApproveCmd) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getOrderId, orderApproveCmd.getOrderId());
		queryWrapper.eq(OrderDO::getState, OrderStateEnum.AUDITING);
		queryWrapper.last("limit 1");

		OrderDO orderDO = orderMapper.selectOne(queryWrapper);

		if (Objects.isNull(orderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_ORDER_NOT_WAITING_AUDIT);
		}
		orderDO.setPricingMethod(orderApproveCmd.getPricingMethod());
		if (!orderApproveCmd.getDraft()) {
			orderDO.setAuditState(OrderAuditStateEnum.PENDING_BOSS_APPROVAL);
		}

		orderMapper.updateById(orderDO);

		// 更新车辆信息
		OrderVehicle orderVehicle = orderApproveCmd.getOrderVehicle();
		OrderVehicleDO orderVehicleDO = orderVehicleConvert.toOrderVehicleDO(orderVehicle);
		orderVehicleDO.setVehicleId(orderVehicle.getVehicleId());
		orderVehicleDO.setOrderId(orderDO.getOrderId());
		orderVehicleMapper.updateById(orderVehicleDO);

		// 更新经销商信息
		OrderDealer orderDealer = orderApproveCmd.getOrderDealer();
		orderDealer.setOrderId(orderDO.getOrderId());
		OrderDealerDO orderDealerDO = orderDealerConvert.toOrderDealerDO(orderDealer);
		// 先尝试更新，如果不存在则插入
		if (orderDealerDO.getOrderDealerId() != null) {
			orderDealerMapper.updateById(orderDealerDO);
		} else {
			LambdaQueryWrapper<OrderDealerDO> dealerQueryWrapper = Wrappers.lambdaQuery(OrderDealerDO.class);
			dealerQueryWrapper.eq(OrderDealerDO::getOrderId, orderDO.getOrderId());
			OrderDealerDO existingDealer = orderDealerMapper.selectOne(dealerQueryWrapper);
			if (existingDealer != null) {
				orderDealerDO.setOrderDealerId(existingDealer.getOrderDealerId());
				orderDealerMapper.updateById(orderDealerDO);
			} else {
				orderDealerMapper.insert(orderDealerDO);
			}
		}

		OrderCompany orderCompany = orderApproveCmd.getOrderCompany();
		if (Objects.nonNull(orderCompany)) {
			orderCompany.setOrderId(orderDO.getOrderId());
			OrderCompanyDO orderCompanyDO = orderCompanyConvert.toOrderCompanyDO(orderCompany);
			// 先尝试更新，如果不存在则插入
			if (orderCompanyDO.getOrderCompanyId() != null) {
				orderCompanyMapper.updateById(orderCompanyDO);
			} else {
				LambdaQueryWrapper<OrderCompanyDO> companyQueryWrapper = Wrappers.lambdaQuery(OrderCompanyDO.class);
				companyQueryWrapper.eq(OrderCompanyDO::getOrderId, orderDO.getOrderId());
				OrderCompanyDO existingCompany = orderCompanyMapper.selectOne(companyQueryWrapper);
				if (existingCompany != null) {
					orderCompanyDO.setOrderCompanyId(existingCompany.getOrderCompanyId());
					orderCompanyMapper.updateById(orderCompanyDO);
				} else {
					orderCompanyMapper.insert(orderCompanyDO);
				}
			}
		}

		// 更新供应商信息（直接更新，因为不存在条数更新）
		orderApproveCmd.getOrderSupplierList().forEach(orderSupplier -> {
			orderSupplier.setOrderId(orderDO.getOrderId());
			OrderSupplierDO orderSupplierDO = orderConvert.toOrderSupplierDO(orderSupplier);
			orderSupplierDO.setOrderSupplierId(orderSupplier.getOrderSupplierId());

			// 直接更新包材信息（因为包材信息条数也不会变）
			if (orderSupplier.getOrderPackageList() != null && !orderSupplier.getOrderPackageList().isEmpty()) {
				orderSupplier.getOrderPackageList().forEach(orderPackage -> {
					orderPackage.setOrderSupplierId(orderSupplierDO.getOrderSupplierId());
					OrderPackageDO orderPackageDO = orderPackageConvert.toOrderPackageDO(orderPackage);
					orderPackageDO.setOrderPackageId(orderPackage.getOrderPackageId());
					orderPackageMapper.updateById(orderPackageDO);
				});
			}

			// 更新供应商信息
			orderSupplierMapper.updateById(orderSupplierDO);
		});

		OrderRebate orderRebate = orderApproveCmd.getOrderRebate();
		if (Objects.nonNull(orderRebate)) {
			orderRebate.setOrderId(orderDO.getOrderId());
			OrderRebateDO orderRebateDO = orderConvert.toOrderRebateDO(orderRebate);
			// 先尝试更新，如果不存在则插入
			if (orderRebateDO.getOrderRebateId() != null) {
				orderRebateMapper.updateById(orderRebateDO);
			} else {
				LambdaQueryWrapper<OrderRebateDO> rebateQueryWrapper = Wrappers.lambdaQuery(OrderRebateDO.class);
				rebateQueryWrapper.eq(OrderRebateDO::getOrderId, orderDO.getOrderId());
				OrderRebateDO existingRebate = orderRebateMapper.selectOne(rebateQueryWrapper);
				if (existingRebate != null) {
					orderRebateDO.setOrderRebateId(existingRebate.getOrderRebateId());
					orderRebateMapper.updateById(orderRebateDO);
				} else {
					orderRebateMapper.insert(orderRebateDO);
				}
			}
		}

		saveOrderCostItem(orderDO.getOrderId(), orderApproveCmd.getOrderCostItemList().stream().toList());
		saveOrderCost(orderDO.getOrderId(), orderApproveCmd.getOrderCostList().stream().peek(orderCost -> {
			if (orderCost.getBelong().equals(CostBelongEnum.PRODUCTION_TYPE)) {
				orderCost.setPrincipal(orderDO.getOriginPrincipal());
			}

			if (orderCost.getBelong().equals(CostBelongEnum.DRIVER_TYPE)) {
				orderCost.setPrincipal(orderVehicleDO.getDriver());
			}

			if (orderCost.getBelong().equals(CostBelongEnum.WORKER_TYPE)) {
				orderCost.setPrincipal(orderDO.getForeman());
			}
		}).toList());
		saveOrderShip(orderDO.getOrderId(), orderApproveCmd.getOrderShipList().stream().toList(), orderApproveCmd);
	}

	/**
	 * 保存订单发货信息
	 */
	private void saveOrderShip(Long orderId, List<OrderShip> orderShipList, OrderApproveCmd orderApproveCmd) {
		if (CollUtil.isEmpty(orderShipList)) {
			return;
		}

		// 获取现有的发货单列表
		LambdaQueryWrapper<OrderShipDO> shipQueryWrapper = Wrappers.lambdaQuery(OrderShipDO.class);
		shipQueryWrapper.eq(OrderShipDO::getOrderId, orderId);
		List<OrderShipDO> existingShips = orderShipMapper.selectList(shipQueryWrapper);

		// 将现有发货单映射到 orderShipId 字典中便于查找
		Map<Long, OrderShipDO> existingShipMap = existingShips.stream()
			.filter(ship -> ship.getOrderShipId() != null)
			.collect(Collectors.toMap(OrderShipDO::getOrderShipId, Function.identity()));

		// 收集需要更新和新增的发货单
		List<OrderShipDO> shipsToInsert = new ArrayList<>();
		List<OrderShipDO> shipsToUpdate = new ArrayList<>();

		for (OrderShip updatedShip : orderShipList) {
			updatedShip.setOrderId(orderId);
			OrderShipDO orderShipDO = orderConvert.toOrderShipDO(updatedShip);
			orderShipDO.setCreatedBy(orderApproveCmd.getCreatedBy());
			orderShipDO.setCreatedByName(orderApproveCmd.getCreatedByName());
			if (orderApproveCmd.getDraft()) {
				orderShipDO.setState(OrderShipStateEnum.DRAFT);
			} else {
				orderShipDO.setState(OrderShipStateEnum.WAIT_SHIPMENT);
			}

			if (existingShipMap.containsKey(updatedShip.getOrderShipId())) {
				// 更新已存在的发货单
				orderShipDO.setOrderShipId(updatedShip.getOrderShipId());
				shipsToUpdate.add(orderShipDO);
				// 从现有映射中移除，剩下的就是需要删除的
				existingShipMap.remove(updatedShip.getOrderShipId());
			} else {
				// 新增发货单
				orderShipDO.setOrderShipId(null);
				// 生成发货单编号
				if (StrUtil.isBlank(orderShipDO.getOrderSn())) {
					orderShipDO.setOrderSn("FH" + generateOrderShipSn());
				}
				shipsToInsert.add(orderShipDO);
			}

			// 处理发货单明细
			if (updatedShip.getOrderShipItemList() != null && !updatedShip.getOrderShipItemList().isEmpty()) {
				// 如果是更新操作，直接处理明细
				if (existingShipMap.containsKey(updatedShip.getOrderShipId())) {
					saveOrderShipItems(orderShipDO, updatedShip.getOrderShipItemList());
				} else {
					// 如果是新增操作，先转换明细，等插入主表后再处理
					List<OrderShipItemDO> itemDOList = updatedShip.getOrderShipItemList().stream()
						.map(item -> {
							OrderShipItemDO itemDO = orderShipItemConvert.toOrderShipItemDO(item);
							itemDO.setOrderShipId(null); // 稍后设置
							itemDO.setOrderShipItemId(null);
							return itemDO;
						})
						.collect(Collectors.toList());
					orderShipDO.setOrderShipItemDOList(itemDOList);
				}
			}
		}

		// 删除不再需要的发货单
		existingShipMap.values().forEach(ship -> {
			// 先删除发货单明细
			LambdaQueryWrapper<OrderShipItemDO> itemDeleteWrapper = Wrappers.lambdaQuery(OrderShipItemDO.class);
			itemDeleteWrapper.eq(OrderShipItemDO::getOrderShipId, ship.getOrderShipId());
			orderShipItemMapper.delete(itemDeleteWrapper);
			// 再删除发货单
			ship.deleteById();
		});

		// 执行更新操作
		shipsToUpdate.forEach(orderShipMapper::updateById);

		// 执行插入操作
		shipsToInsert.forEach(ship -> {
			orderShipMapper.insert(ship);
			// 插入后需要更新明细的 orderShipId
			if (ship.getOrderShipItemDOList() != null) {
				ship.getOrderShipItemDOList().forEach(item -> item.setOrderShipId(ship.getOrderShipId()));
				ship.getOrderShipItemDOList().forEach(orderShipItemMapper::insert);
			}
		});
	}

	/**
	 * 保存发货单明细
	 * 根据 orderShipId 和 unitPrice 两个字段判断是否新增、更新或删除
	 */
	private void saveOrderShipItems(OrderShipDO orderShipDO, List<OrderShipItem> orderShipItemList) {
		if (CollUtil.isEmpty(orderShipItemList)) {
			return;
		}

		// 获取现有的发货单明细列表
		LambdaQueryWrapper<OrderShipItemDO> itemQueryWrapper = Wrappers.lambdaQuery(OrderShipItemDO.class);
		itemQueryWrapper.eq(OrderShipItemDO::getOrderShipId, orderShipDO.getOrderShipId());
		List<OrderShipItemDO> existingItems = orderShipItemMapper.selectList(itemQueryWrapper);

		// 将现有明细映射到 unitPrice 字典中便于查找
		// 使用 BigDecimal 的 compareTo 作为比较器，确保精确匹配
		Map<BigDecimal, OrderShipItemDO> existingItemMap = existingItems.stream()
			.filter(item -> item.getUnitPrice() != null)
			.collect(Collectors.toMap(
				OrderShipItemDO::getUnitPrice,
				Function.identity(),
				(existing, replacement) -> existing // 如果有重复的unitPrice，保留第一个
			));

		// 收集需要更新和新增的明细
		List<OrderShipItemDO> itemsToInsert = new ArrayList<>();
		List<OrderShipItemDO> itemsToUpdate = new ArrayList<>();

		for (OrderShipItem updatedItem : orderShipItemList) {
			if (updatedItem.getUnitPrice() == null) {
				continue; // 跳过单价为空的记录
			}

			// 查找是否存在相同 unitPrice 的记录
			OrderShipItemDO existingItem = existingItemMap.entrySet().stream()
				.filter(entry -> entry.getKey().compareTo(updatedItem.getUnitPrice()) == 0)
				.map(Map.Entry::getValue)
				.findFirst()
				.orElse(null);

			OrderShipItemDO itemDO = orderShipItemConvert.toOrderShipItemDO(updatedItem);
			itemDO.setOrderShipId(orderShipDO.getOrderShipId());

			if (existingItem != null) {
				// 更新已存在的明细（基于 unitPrice 匹配）
				itemDO.setOrderShipItemId(existingItem.getOrderShipItemId());
				itemsToUpdate.add(itemDO);
				// 从现有映射中移除，剩下的就是需要删除的
				existingItemMap.remove(existingItem.getUnitPrice());
			} else {
				itemDO.setOrderShipItemId(null);
				// 新增明细
				itemsToInsert.add(itemDO);
			}
		}

		// 删除不再需要的明细（数据库中存在但新列表中没有的 unitPrice）
		existingItemMap.values().forEach(item -> orderShipItemMapper.deleteById(item.getOrderShipItemId()));

		// 执行更新操作
		itemsToUpdate.forEach(orderShipItemMapper::updateById);

		// 执行插入操作
		itemsToInsert.forEach(orderShipItemMapper::insert);
	}

	@Override
	public void submitReview(OrderSubmitReviewCmd orderSubmitReviewCmd) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getOrderId, orderSubmitReviewCmd.getOrderId());
		queryWrapper.eq(OrderDO::getState, OrderStateEnum.DRAFT);
		queryWrapper.last("limit 1");

		OrderDO orderDO = orderMapper.selectOne(queryWrapper);

		if (Objects.isNull(orderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_ORDER_NOT_DRAFT);
		}

		orderDO.setState(OrderStateEnum.AUDITING);
		orderDO.setAuditState(OrderAuditStateEnum.PENDING_QUOTE_APPROVAL);

		orderMapper.updateById(orderDO);
	}

	@Override
	public void withdrawReview(OrderWithdrawReviewCmd orderWithdrawReviewCmd) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getOrderId, orderWithdrawReviewCmd.getOrderId());
		queryWrapper.eq(OrderDO::getState, OrderStateEnum.AUDITING);
		queryWrapper.eq(OrderDO::getAuditState, OrderAuditStateEnum.PENDING_QUOTE_APPROVAL);
		queryWrapper.last("limit 1");

		OrderDO orderDO = orderMapper.selectOne(queryWrapper);

		if (Objects.isNull(orderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_ORDER_NOT_WAITING_FOR_WITHDRAW);
		}

		orderDO.setState(OrderStateEnum.DRAFT);
		orderDO.setAuditState(OrderAuditStateEnum.NONE);
		orderMapper.updateById(orderDO);
	}

	@Override
	public void rejectApprove(OrderRejectApproveCmd orderRejectApproveCmd) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getOrderId, orderRejectApproveCmd.getOrderId());
		queryWrapper.eq(OrderDO::getState, OrderStateEnum.AUDITING);
		queryWrapper.eq(OrderDO::getAuditState, OrderAuditStateEnum.PENDING_QUOTE_APPROVAL);
		queryWrapper.last("limit 1");

		OrderDO orderDO = orderMapper.selectOne(queryWrapper);

		if (Objects.isNull(orderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_ORDER_NOT_WAITING_AUDIT);
		}

		orderDO.setState(OrderStateEnum.DRAFT);
		orderDO.setAuditState(OrderAuditStateEnum.QUOTE_REJECTED);

		orderMapper.updateById(orderDO);

		// 发货单改成（草稿）
		LambdaUpdateWrapper<OrderShipDO> updateWrapper = Wrappers.lambdaUpdate(OrderShipDO.class);
		updateWrapper.eq(OrderShipDO::getOrderId, orderDO.getOrderId());
		updateWrapper.set(OrderShipDO::getState, OrderShipStateEnum.DRAFT);
		orderShipMapper.update(null, updateWrapper);
	}

	@Override
	public void finalApprove(OrderFinalApproveCmd orderFinalApproveCmd) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getOrderId, orderFinalApproveCmd.getOrderId());
		queryWrapper.eq(OrderDO::getState, OrderStateEnum.AUDITING);
		queryWrapper.eq(OrderDO::getAuditState, OrderAuditStateEnum.PENDING_BOSS_APPROVAL);
		queryWrapper.last("limit 1");

		OrderDO orderDO = orderMapper.selectOne(queryWrapper);

		if (Objects.isNull(orderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_ORDER_NOT_WAITING_FOR_FINAL_APPROVE);
		}

		// 检查是否满足发货条件，如果满足则设置为待发货，否则保持待老板审核
		orderDO.setState(OrderStateEnum.COMPLETED);
		orderDO.setAuditState(OrderAuditStateEnum.BOSS_APPROVED);

		orderMapper.updateById(orderDO);

		// 发货单改成已发货（待回款）
		LambdaUpdateWrapper<OrderShipDO> updateWrapper = Wrappers.lambdaUpdate(OrderShipDO.class);
		updateWrapper.eq(OrderShipDO::getOrderId, orderDO.getOrderId());
		updateWrapper.set(OrderShipDO::getState, OrderShipStateEnum.WAIT_PAYMENT);
		orderShipMapper.update(null, updateWrapper);
	}

	/**
	 * 生成发货单编号
	 *
	 * @return 发货单编号
	 */
	private String generateOrderShipSn() {
		// 生成类似 SO20251105001 格式的编号
		return java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.BASIC_ISO_DATE)
			+ String.format("%03d", System.currentTimeMillis() % 1000);
	}

	@Override
	public void rejectFinal(OrderRejectFinalCmd orderRejectFinalCmd) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getOrderId, orderRejectFinalCmd.getOrderId());
		queryWrapper.eq(OrderDO::getState, OrderStateEnum.AUDITING);
		queryWrapper.eq(OrderDO::getAuditState, OrderAuditStateEnum.PENDING_BOSS_APPROVAL);
		queryWrapper.last("limit 1");

		OrderDO orderDO = orderMapper.selectOne(queryWrapper);

		if (Objects.isNull(orderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_ORDER_NOT_WAITING_FOR_REJECT_FINAL);
		}

		orderDO.setAuditState(OrderAuditStateEnum.BOSS_REJECTED);
		orderMapper.updateById(orderDO);
	}

	@Override
	public Long countBy(OrderCountQry orderCountQry) {
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getCreatedBy, orderCountQry.getCreatedBy());
		queryWrapper.eq(OrderDO::getState, orderCountQry.getState());
		return orderMapper.selectCount(queryWrapper);
	}

	@Override
	@Transactional
	public Order saveStep1(OrderStep1Cmd orderStep1Cmd) {
		OrderDO orderDO;

		// 如果订单ID为空，则创建新订单
		if (orderStep1Cmd.getOrderId() == null) {
			orderDO = orderConvert.toOrderDO(orderStep1Cmd);
			orderDO.setState(OrderStateEnum.DRAFT);
			orderDO.setOrderSn("CG" + generateOrderShipSn());
			orderDO.setType(orderStep1Cmd.getType());
			orderMapper.insert(orderDO);
		} else {
			// 否则更新现有订单
			LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
			queryWrapper.eq(OrderDO::getOrderId, orderStep1Cmd.getOrderId());
			queryWrapper.select(OrderDO::getOrderId, OrderDO::getActive);
			queryWrapper.last("limit 1");
			orderDO = orderMapper.selectOne(queryWrapper);
			orderDO.setActive(orderStep1Cmd.getActive());
			orderDO.setState(OrderStateEnum.DRAFT);
			orderDO.setType(orderStep1Cmd.getType());
			orderMapper.updateById(orderDO);
		}

		// 保存或更新车辆信息
		OrderVehicle orderVehicle = orderStep1Cmd.getOrderVehicle();
		orderVehicle.setOrderId(orderDO.getOrderId());
		OrderVehicleDO orderVehicleDO = orderVehicleConvert.toOrderVehicleDO(orderVehicle);

		if (orderVehicle.getVehicleId() != null) {
			orderVehicleMapper.updateById(orderVehicleDO);
		} else {
			// 检查是否已存在车辆信息
			LambdaQueryWrapper<OrderVehicleDO> vehicleQueryWrapper = Wrappers.lambdaQuery(OrderVehicleDO.class);
			vehicleQueryWrapper.eq(OrderVehicleDO::getOrderId, orderDO.getOrderId());
			OrderVehicleDO existingVehicle = orderVehicleMapper.selectOne(vehicleQueryWrapper);

			if (existingVehicle != null) {
				orderVehicleDO.setVehicleId(existingVehicle.getVehicleId());
				orderVehicleMapper.updateById(orderVehicleDO);
			} else {
				orderVehicleMapper.insert(orderVehicleDO);
			}
		}

		// 保存或更新经销商信息
		OrderDealer orderDealer = orderStep1Cmd.getOrderDealer();
		orderDealer.setOrderId(orderDO.getOrderId());
		OrderDealerDO orderDealerDO = orderDealerConvert.toOrderDealerDO(orderDealer);

		if (orderDealer.getOrderDealerId() != null) {
			orderDealerMapper.updateById(orderDealerDO);
		} else {
			// 检查是否已存在经销商信息
			LambdaQueryWrapper<OrderDealerDO> dealerQueryWrapper = Wrappers.lambdaQuery(OrderDealerDO.class);
			dealerQueryWrapper.eq(OrderDealerDO::getOrderId, orderDO.getOrderId());
			OrderDealerDO existingDealer = orderDealerMapper.selectOne(dealerQueryWrapper);

			if (existingDealer != null) {
				orderDealerDO.setOrderDealerId(existingDealer.getOrderDealerId());
				orderDealerMapper.updateById(orderDealerDO);
			} else {
				orderDealerMapper.insert(orderDealerDO);
			}
		}

		return orderConvert.toOrder(orderDO);
	}

	@Override
	@Transactional
	public void saveStep2(OrderStep2Cmd orderStep2Cmd) {
		Long orderId = orderStep2Cmd.getOrderId();

		// 否则更新现有订单
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getOrderId, orderId);
		queryWrapper.select(OrderDO::getOrderId, OrderDO::getActive);
		queryWrapper.last("limit 1");
		OrderDO orderDO = orderMapper.selectOne(queryWrapper);
		orderDO.setActive(orderStep2Cmd.getActive());
		orderDO.setState(OrderStateEnum.DRAFT);
		orderDO.setType(orderStep2Cmd.getType());

		orderMapper.updateById(orderDO);

		// 更新供应商信息（精细化处理）
		// 获取现有的供应商列表
		LambdaQueryWrapper<OrderSupplierDO> supplierQueryWrapper = Wrappers.lambdaQuery(OrderSupplierDO.class);
		supplierQueryWrapper.eq(OrderSupplierDO::getOrderId, orderId);
		List<OrderSupplierDO> existingSuppliers = orderSupplierMapper.selectList(supplierQueryWrapper);

		// 获取更新的供应商列表
		List<OrderSupplier> updatedSuppliers = orderStep2Cmd.getOrderSupplierList();

		// 将现有供应商映射到ID字典中便于查找
		Map<Long, OrderSupplierDO> existingOrderSupplierMap = existingSuppliers.stream()
			.collect(Collectors.toMap(OrderSupplierDO::getSupplierId, Function.identity()));

		// 收集需要更新和新增的供应商
		List<OrderSupplierDO> suppliersToInsert = new ArrayList<>();
		List<OrderSupplierDO> suppliersToUpdate = new ArrayList<>();

		for (OrderSupplier updatedSupplier : updatedSuppliers) {
			// 检查供应商ID是否为空，如果为空则创建新的供应商
			if (Objects.isNull(updatedSupplier.getSupplierId())) {
				// 根据姓名查询
				LambdaQueryWrapper<SupplierDO> queryWrapper1 = Wrappers.lambdaQuery(SupplierDO.class);
				queryWrapper1.eq(SupplierDO::getName, updatedSupplier.getName());
				SupplierDO supplierDO = supplierMapper.selectOne(queryWrapper1);

				if (Objects.isNull(supplierDO)) {
					supplierDO = supplierConvert.toSupplierDO(updatedSupplier);
					supplierDO.setStatus(Boolean.TRUE);
					supplierDO.setCreatedBy(orderStep2Cmd.getCreatedBy());
					supplierDO.setCreatedByName(orderStep2Cmd.getCreatedByName());
					supplierMapper.insert(supplierDO);
				}

				updatedSupplier.setSupplierId(supplierDO.getSupplierId());
			}

			updatedSupplier.setOrderId(orderId);
			OrderSupplierDO orderSupplierDO = orderConvert.toOrderSupplierDO(updatedSupplier);

			if (updatedSupplier.getSupplierId() != null && existingOrderSupplierMap.containsKey(updatedSupplier.getSupplierId())) {
				// 更新已存在的供应商
				orderSupplierDO.setSupplierId(updatedSupplier.getSupplierId());

				Long orderSupplierId = existingOrderSupplierMap.get(updatedSupplier.getSupplierId()).getOrderSupplierId();
				orderSupplierDO.setOrderSupplierId(orderSupplierId);
				updatedSupplier.setOrderSupplierId(orderSupplierId);

				suppliersToUpdate.add(orderSupplierDO);
				// 从现有映射中移除，剩下的就是需要删除的
				existingOrderSupplierMap.remove(updatedSupplier.getSupplierId());
			} else {
				// 新增供应商
				suppliersToInsert.add(orderSupplierDO);
				updatedSupplier.setOrderSupplierId(orderSupplierDO.getOrderSupplierId());
			}
		}

		// 删除不再需要的供应商
		existingOrderSupplierMap.values().forEach(supplier -> supplier.deleteById());

		// 执行更新操作
		suppliersToUpdate.forEach(orderSupplierMapper::updateById);

		// 执行插入操作
		suppliersToInsert.forEach(orderSupplierMapper::insert);

		// 处理包材信息（对更新和新增的供应商）
		List<OrderSupplierDO> allAffectedSuppliers = new ArrayList<>();
		allAffectedSuppliers.addAll(suppliersToUpdate);
		allAffectedSuppliers.addAll(suppliersToInsert);

		for (OrderSupplierDO supplierDO : allAffectedSuppliers) {
			// 第三步处理包材
			if (orderStep2Cmd.getActive() == 4) {
				// 查找对应的更新数据
				OrderSupplier updatedSupplier = updatedSuppliers.stream()
					.filter(s -> (s.getOrderSupplierId() != null && s.getOrderSupplierId().equals(supplierDO.getOrderSupplierId()))
						|| (s.getOrderSupplierId() == null && supplierDO.getOrderSupplierId() != null
						&& s.getSupplierId().equals(supplierDO.getSupplierId())))
					.findFirst()
					.orElse(null);

				if (updatedSupplier != null && updatedSupplier.getOrderPackageList() != null && !updatedSupplier.getOrderPackageList().isEmpty()) {
					// 获取现有的包材信息
					LambdaQueryWrapper<OrderPackageDO> packageQueryWrapper = Wrappers.lambdaQuery(OrderPackageDO.class);
					packageQueryWrapper.eq(OrderPackageDO::getOrderSupplierId, supplierDO.getOrderSupplierId());
					List<OrderPackageDO> existingPackages = orderPackageMapper.selectList(packageQueryWrapper);

					// 将现有包材映射到(orderId, orderSupplierId, boxProductId, boxType)组合字典中便于查找
					Map<String, OrderPackageDO> existingPackageMap = existingPackages.stream()
						.collect(Collectors.toMap(
							p -> p.getOrderId() + "_" + p.getOrderSupplierId() + "_" + p.getBoxProductId() + "_" + p.getBoxType().getType(),
							Function.identity()
						));

					// 收集需要更新和新增的包材
					List<OrderPackageDO> packagesToInsert = new ArrayList<>();
					List<OrderPackageDO> packagesToUpdate = new ArrayList<>();

					for (OrderPackage orderPackage : updatedSupplier.getOrderPackageList()) {
						orderPackage.setOrderSupplierId(supplierDO.getOrderSupplierId());
						orderPackage.setOrderId(orderId);
						OrderPackageDO orderPackageDO = orderPackageConvert.toOrderPackageDO(orderPackage);

						// 构建唯一键
						String uniqueKey = orderId + "_" + supplierDO.getOrderSupplierId() + "_" + orderPackage.getBoxProductId() + "_" + orderPackage.getBoxType().getType();

						if (existingPackageMap.containsKey(uniqueKey)) {
							// 更新已存在的包材
							orderPackageDO.setOrderPackageId(existingPackageMap.get(uniqueKey).getOrderPackageId());
							packagesToUpdate.add(orderPackageDO);
							// 从现有映射中移除，剩下的就是需要删除的
							existingPackageMap.remove(uniqueKey);
						} else {
							// 新增包材
							packagesToInsert.add(orderPackageDO);
						}
					}

					// 删除不再需要的包材
					existingPackageMap.values().forEach(packageDO -> packageDO.deleteById());

					// 执行更新操作
					packagesToUpdate.forEach(orderPackageMapper::updateById);

					// 执行插入操作
					packagesToInsert.forEach(orderPackageMapper::insert);
				} else if (updatedSupplier != null) {
					// 如果更新的数据中包材列表为空，则删除所有包材信息
					LambdaQueryWrapper<OrderPackageDO> packageDeleteWrapper = Wrappers.lambdaQuery(OrderPackageDO.class);
					packageDeleteWrapper.eq(OrderPackageDO::getOrderSupplierId, supplierDO.getOrderSupplierId());
					orderPackageMapper.delete(packageDeleteWrapper);
				}
			}

			if (LoadingModeEnum.FRAME_WITH_NET.equals(supplierDO.getLoadingMode())) {
				// 如果是搭架子+网垫，则删除所有包材信息
				LambdaQueryWrapper<OrderPackageDO> packageDeleteWrapper = Wrappers.lambdaQuery(OrderPackageDO.class);
				packageDeleteWrapper.eq(OrderPackageDO::getOrderSupplierId, supplierDO.getOrderSupplierId());
				orderPackageMapper.delete(packageDeleteWrapper);
			}
		}
	}

	@Override
	@Transactional
	public void saveStep3(OrderStep3Cmd orderStep3Cmd) {
		Long orderId = orderStep3Cmd.getOrderId();

		// 否则更新现有订单
		LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class);
		queryWrapper.eq(OrderDO::getOrderId, orderId);
		queryWrapper.select(OrderDO::getOrderId, OrderDO::getActive);
		queryWrapper.last("limit 1");
		OrderDO orderDO = orderMapper.selectOne(queryWrapper);
		orderDO.setActive(orderStep3Cmd.getActive());
		orderDO.setForeman(orderStep3Cmd.getForeman());
		orderDO.setType(orderStep3Cmd.getType());
		orderDO.setState(OrderStateEnum.DRAFT);
		orderMapper.updateById(orderDO);

		saveOrderCostItem(orderId, orderStep3Cmd.getOrderCostItemList().stream().toList());
		saveOrderCost(orderDO.getOrderId(), orderStep3Cmd.getOrderCostList().stream().toList());

		// 空箱费
		if (orderStep3Cmd.getOrderPackageList() != null) {
			// 获取现有的包材信息
			LambdaQueryWrapper<OrderPackageDO> packageQueryWrapper = Wrappers.lambdaQuery(OrderPackageDO.class);
			packageQueryWrapper.isNull(OrderPackageDO::getOrderSupplierId);
			packageQueryWrapper.eq(OrderPackageDO::getOrderId, orderId);
			List<OrderPackageDO> existingPackages = orderPackageMapper.selectList(packageQueryWrapper);

			// 将现有包材映射到boxProductId字典中便于查找
			Map<Long, OrderPackageDO> existingPackageMap = existingPackages.stream()
				.collect(Collectors.toMap(OrderPackageDO::getBoxProductId, Function.identity()));

			// 收集需要更新和新增的包材
			List<OrderPackageDO> packagesToInsert = new ArrayList<>();
			List<OrderPackageDO> packagesToUpdate = new ArrayList<>();

			for (OrderPackage orderPackage : orderStep3Cmd.getOrderPackageList()) {
				orderPackage.setOrderSupplierId(null);
				orderPackage.setOrderId(orderId);
				OrderPackageDO orderPackageDO = orderPackageConvert.toOrderPackageDO(orderPackage);

				if (existingPackageMap.containsKey(orderPackage.getBoxProductId())) {
					// 更新已存在的包材
					orderPackageDO.setOrderPackageId(existingPackageMap.get(orderPackage.getBoxProductId()).getOrderPackageId());
					packagesToUpdate.add(orderPackageDO);
					// 从现有映射中移除，剩下的就是需要删除的
					existingPackageMap.remove(orderPackage.getBoxProductId());
				} else {
					// 新增包材
					packagesToInsert.add(orderPackageDO);
				}
			}

			// 删除不再需要的包材
			existingPackageMap.values().forEach(packageDO -> packageDO.deleteById());

			// 执行更新操作
			packagesToUpdate.forEach(orderPackageMapper::updateById);

			// 执行插入操作
			packagesToInsert.forEach(orderPackageMapper::insert);
		}
	}

	@Override
	public String getLastVehicleNo(LastVehicleNoQry lastVehicleNoQry) {
		LambdaQueryWrapper<OrderVehicleDO> queryWrapper = Wrappers.lambdaQuery(OrderVehicleDO.class);
		queryWrapper.eq(Objects.nonNull(lastVehicleNoQry.getDealerId()), OrderVehicleDO::getDealerId, lastVehicleNoQry.getDealerId());
		queryWrapper.isNotNull(OrderVehicleDO::getVehicleNo);
		queryWrapper.orderByDesc(OrderVehicleDO::getCreatedAt);
		queryWrapper.last("limit 1");

		OrderVehicleDO orderVehicleDO = orderVehicleMapper.selectOne(queryWrapper);

		if (Objects.nonNull(orderVehicleDO)) {
			return orderVehicleDO.getVehicleNo();
		}

		DealerDO dealerDO = dealerMapper.selectById(lastVehicleNoQry.getDealerId());

		Boolean enableInitialTrainNo = dealerDO.getSetting().getEnableInitialTrainNo();
		if (enableInitialTrainNo.equals(Boolean.TRUE)) {
			return dealerDO.getSetting().getInitialTrainNo().toString();
		} else {
			return "0";
		}
	}

	/**
	 * 更新费用信息（精细化处理）
	 * 获取现有的费用列表
	 *
	 * @param orderId       采购单Id
	 * @param orderCostList 更新的费用列表
	 */
	private void saveOrderCost(Long orderId, List<OrderCost> orderCostList) {
		// 更新费用信息（精细化处理）
		// 获取现有的费用列表
		LambdaQueryWrapper<OrderCostDO> costQueryWrapper = Wrappers.lambdaQuery(OrderCostDO.class);
		costQueryWrapper.eq(OrderCostDO::getOrderId, orderId);
		List<OrderCostDO> existingCosts = orderCostMapper.selectList(costQueryWrapper);

		// 将现有费用映射到itemId字典中便于查找
		Map<Long, OrderCostDO> existingCostMap = existingCosts.stream()
			.collect(Collectors.toMap(OrderCostDO::getCostId, Function.identity()));

		// 收集需要更新和新增的费用
		List<OrderCostDO> costsToInsert = new ArrayList<>();
		List<OrderCostDO> costsToUpdate = new ArrayList<>();

		for (OrderCost updatedCost : orderCostList) {
			updatedCost.setOrderId(orderId);
			OrderCostDO costDO = orderConvert.toOrderCostDO(updatedCost);

			if (existingCostMap.containsKey(updatedCost.getCostId())) {
				// 更新已存在的费用
				costDO.setOrderCostId(existingCostMap.get(updatedCost.getCostId()).getOrderCostId());
				costsToUpdate.add(costDO);
				// 从现有映射中移除，剩下的就是需要删除的
				existingCostMap.remove(updatedCost.getCostId());
			} else {
				// 新增费用
				costsToInsert.add(costDO);
			}
		}

		// 删除不再需要的费用
		existingCostMap.values().forEach(cost -> cost.deleteById());

		// 执行更新操作
		costsToUpdate.forEach(orderCostMapper::updateById);

		// 执行插入操作
		costsToInsert.forEach(orderCostMapper::insert);
	}

	/**
	 * 更新费用信息（精细化处理）
	 * 获取现有的费用列表
	 *
	 * @param orderId           采购单Id
	 * @param orderCostItemList 更新的费用列表
	 */
	private void saveOrderCostItem(Long orderId, List<OrderCostItem> orderCostItemList) {
		// 更新费用信息（精细化处理）
		// 获取现有的费用列表
		LambdaQueryWrapper<OrderCostItemDO> costQueryWrapper = Wrappers.lambdaQuery(OrderCostItemDO.class);
		costQueryWrapper.eq(OrderCostItemDO::getOrderId, orderId);
		List<OrderCostItemDO> existingCosts = orderCostItemMapper.selectList(costQueryWrapper);

		// 将现有费用映射到itemId字典中便于查找
		Map<Long, OrderCostItemDO> existingCostMap = existingCosts.stream()
			.collect(Collectors.toMap(OrderCostItemDO::getCostItemId, Function.identity()));

		// 收集需要更新和新增的费用
		List<OrderCostItemDO> costsToInsert = new ArrayList<>();
		List<OrderCostItemDO> costsToUpdate = new ArrayList<>();

		for (OrderCostItem updatedCostItem : orderCostItemList) {
			updatedCostItem.setOrderId(orderId);
			OrderCostItemDO costDO = orderCostItemConvert.toOrderCostItemDO(updatedCostItem);

			if (existingCostMap.containsKey(updatedCostItem.getCostItemId())) {
				// 更新已存在的费用
				costDO.setOrderCostItemId(existingCostMap.get(updatedCostItem.getCostItemId()).getOrderCostItemId());
				costsToUpdate.add(costDO);
				// 从现有映射中移除，剩下的就是需要删除的
				existingCostMap.remove(updatedCostItem.getCostItemId());
			} else {
				// 新增费用
				costsToInsert.add(costDO);
			}
		}

		// 删除不再需要的费用
		existingCostMap.values().forEach(cost -> cost.deleteById());

		// 执行更新操作
		costsToUpdate.forEach(orderCostItemMapper::updateById);

		// 执行插入操作
		costsToInsert.forEach(orderCostItemMapper::insert);
	}
}

