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.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.CostItemCostTypeEnum;
import com.xunhong.erp.turbo.api.biz.dto.enums.PurchaseOrderStateEnum;
import com.xunhong.erp.turbo.api.biz.dto.qry.*;
import com.xunhong.erp.turbo.biz.domain.entity.PurchaseOrder;
import com.xunhong.erp.turbo.biz.domain.gateway.PurchaseOrderGateway;
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.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author shenyifei
 */
@Repository
@RequiredArgsConstructor
public class PurchaseOrderGatewayImpl implements PurchaseOrderGateway {
	private final PurchaseOrderMapper purchaseOrderMapper;
	private final PurchaseOrderConvert purchaseOrderConvert;

	private final OrderVehicleMapper orderVehicleMapper;
	private final OrderVehicleConvert orderVehicleConvert;

	private final OrderSupplierMapper orderSupplierMapper;
	private final OrderSupplierConvert orderSupplierConvert;

	private final OrderCostMapper orderCostMapper;
	private final OrderCostConvert orderCostConvert;

	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 OrderRebateConvert orderRebateConvert;

	private final ShipOrderMapper shipOrderMapper;
	private final ShipOrderItemMapper shipOrderItemMapper;
	private final ShipOrderPackageMapper shipOrderPackageMapper;

	private final SupplierMapper supplierMapper;
	private final SupplierConvert supplierConvert;

	@Override
	@Transactional
	public PurchaseOrder save(PurchaseOrderCreateCmd purchaseOrderCreateCmd) {
		PurchaseOrder purchaseOrder = saveStep1(purchaseOrderConvert.toPurchaseOrderStep1Cmd(purchaseOrderCreateCmd));
		purchaseOrderCreateCmd.setOrderId(purchaseOrder.getOrderId());
		saveStep2(purchaseOrderConvert.toPurchaseOrderStep2Cmd(purchaseOrderCreateCmd));
		saveStep3(purchaseOrderConvert.toPurchaseOrderStep3Cmd(purchaseOrderCreateCmd));
		return purchaseOrder;
	}

	@Override
	public IPage<PurchaseOrder> page(PurchaseOrderPageQry purchaseOrderPageQry) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.like(StrUtil.isNotBlank(purchaseOrderPageQry.getOrderSn()), PurchaseOrderDO::getOrderSn, purchaseOrderPageQry.getOrderSn());
		queryWrapper.eq(Objects.nonNull(purchaseOrderPageQry.getState()), PurchaseOrderDO::getState, purchaseOrderPageQry.getState());
		queryWrapper.eq(Objects.nonNull(purchaseOrderPageQry.getCreatedBy()), PurchaseOrderDO::getCreatedBy, purchaseOrderPageQry.getCreatedBy());

		String vehicleNo = purchaseOrderPageQry.getVehicleNo();
		if (StrUtil.isNotBlank(vehicleNo)) {
			LambdaQueryWrapper<OrderVehicleDO> queryWrapper1 = Wrappers.lambdaQuery(OrderVehicleDO.class);
			queryWrapper1.like(OrderVehicleDO::getVehicleNo, vehicleNo);
			List<OrderVehicleDO> orderVehicleDOList = orderVehicleMapper.selectList(queryWrapper1);
			if (CollUtil.isNotEmpty(orderVehicleDOList)) {
				queryWrapper.in(PurchaseOrderDO::getOrderId, orderVehicleDOList.stream().map(OrderVehicleDO::getOrderId).toList());
			} else {
				// 如果没有匹配的订单，则添加一个永远不成立的条件
				queryWrapper.eq(PurchaseOrderDO::getOrderId, -1L);
			}
		}

		if (Objects.nonNull(purchaseOrderPageQry.getDealerId())) {
			LambdaQueryWrapper<OrderDealerDO> queryWrapper1 = Wrappers.lambdaQuery(OrderDealerDO.class);
			queryWrapper1.eq(Objects.nonNull(purchaseOrderPageQry.getDealerId()), OrderDealerDO::getDealerId, purchaseOrderPageQry.getDealerId());
			List<OrderDealerDO> orderDealerDOList = orderDealerMapper.selectList(queryWrapper1);

			if (CollUtil.isNotEmpty(orderDealerDOList)) {
				queryWrapper.in(PurchaseOrderDO::getOrderId, orderDealerDOList.stream().map(OrderDealerDO::getOrderId).toList());
			} else {
				// 如果没有匹配的订单，则添加一个永远不成立条件
				queryWrapper.eq(PurchaseOrderDO::getOrderId, -1L);
			}
		}

		queryWrapper.orderByDesc(PurchaseOrderDO::getCreatedAt);

		IPage<PurchaseOrderDO> page = new Page<>(purchaseOrderPageQry.getPageIndex(), purchaseOrderPageQry.getPageSize());
		page = purchaseOrderMapper.selectPage(page, queryWrapper);

		List<Long> orderIdList = page.getRecords().stream().map(PurchaseOrderDO::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(purchaseOrderDO -> {
				purchaseOrderDO.setOrderVehicleDO(orderVehicleDOMap.get(purchaseOrderDO.getOrderId()));
				purchaseOrderDO.setOrderSupplierDOList(orderSupplierDOList.stream().filter(orderSupplierDO -> orderSupplierDO.getOrderId().equals(purchaseOrderDO.getOrderId())).toList());
			});
		}

		return page.convert(purchaseOrderConvert::toPurchaseOrder);
	}

	@Override
	public List<PurchaseOrder> list(PurchaseOrderListQry purchaseOrderListQry) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		List<PurchaseOrderDO> purchaseOrderDOList = purchaseOrderMapper.selectList(queryWrapper);
		return purchaseOrderDOList.stream().map(purchaseOrderConvert::toPurchaseOrder).toList();
	}

	@Override
	@Transactional
	public PurchaseOrder update(PurchaseOrderUpdateCmd purchaseOrderUpdateCmd) {
		return save(purchaseOrderUpdateCmd);
	}

	@Override
	public PurchaseOrder show(PurchaseOrderShowQry purchaseOrderShowQry) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getOrderId, purchaseOrderShowQry.getOrderId());
		queryWrapper.last("limit 1");

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);

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

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

			purchaseOrderDO.setOrderDealerDO(orderDealerDO);

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

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

			List<OrderSupplierDO> orderSupplierDOList = orderSupplierMapper.selectList(Wrappers.lambdaQuery(OrderSupplierDO.class).eq(OrderSupplierDO::getOrderId, purchaseOrderDO.getOrderId()));
			List<Long> orderSupplierIdList = orderSupplierDOList.stream().map(OrderSupplierDO::getOrderSupplierId).toList();
			if (CollUtil.isNotEmpty(orderSupplierIdList)) {
				LambdaQueryWrapper<OrderPackageDO> queryWrapper1 = Wrappers.lambdaQuery(OrderPackageDO.class);
				queryWrapper1.in(OrderPackageDO::getOrderSupplierId, orderSupplierIdList);
				List<OrderPackageDO> orderPackageDOList = orderPackageMapper.selectList(queryWrapper1);

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

			}
			purchaseOrderDO.setOrderSupplierDOList(orderSupplierDOList);

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

		return purchaseOrderConvert.toPurchaseOrder(purchaseOrderDO);
	}

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

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);
		purchaseOrderDO.deleteById();
	}

	@Override
	@Transactional
	public void approve(PurchaseOrderApproveCmd purchaseOrderApproveCmd) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getOrderId, purchaseOrderApproveCmd.getOrderId());
		queryWrapper.last("limit 1");

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);
		purchaseOrderDO.setPricingMethod(purchaseOrderApproveCmd.getPricingMethod());

		if (!purchaseOrderApproveCmd.getDraft()) {
			purchaseOrderDO.setState(PurchaseOrderStateEnum.WAITING_BOSS_APPROVE);
		}

		purchaseOrderMapper.updateById(purchaseOrderDO);

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

		// 更新经销商信息
		OrderDealer orderDealer = purchaseOrderApproveCmd.getOrderDealer();
		orderDealer.setOrderId(purchaseOrderDO.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, purchaseOrderDO.getOrderId());
			OrderDealerDO existingDealer = orderDealerMapper.selectOne(dealerQueryWrapper);
			if (existingDealer != null) {
				orderDealerDO.setOrderDealerId(existingDealer.getOrderDealerId());
				orderDealerMapper.updateById(orderDealerDO);
			} else {
				orderDealerMapper.insert(orderDealerDO);
			}
		}

		OrderCompany orderCompany = purchaseOrderApproveCmd.getOrderCompany();
		if (Objects.nonNull(orderCompany)) {
			orderCompany.setOrderId(purchaseOrderDO.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, purchaseOrderDO.getOrderId());
				OrderCompanyDO existingCompany = orderCompanyMapper.selectOne(companyQueryWrapper);
				if (existingCompany != null) {
					orderCompanyDO.setOrderCompanyId(existingCompany.getOrderCompanyId());
					orderCompanyMapper.updateById(orderCompanyDO);
				} else {
					orderCompanyMapper.insert(orderCompanyDO);
				}
			}
		}

		// 更新供应商信息（直接更新，因为不存在条数更新）
		purchaseOrderApproveCmd.getOrderSupplierList().forEach(orderSupplier -> {
			orderSupplier.setOrderId(purchaseOrderDO.getOrderId());
			OrderSupplierDO orderSupplierDO = orderSupplierConvert.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 = purchaseOrderApproveCmd.getOrderRebate();
		if (Objects.nonNull(orderRebate)) {
			orderRebate.setOrderId(purchaseOrderDO.getOrderId());
			OrderRebateDO orderRebateDO = orderRebateConvert.toOrderRebateDO(orderRebate);
			// 先尝试更新，如果不存在则插入
			if (orderRebateDO.getOrderRebateId() != null) {
				orderRebateMapper.updateById(orderRebateDO);
			} else {
				LambdaQueryWrapper<OrderRebateDO> rebateQueryWrapper = Wrappers.lambdaQuery(OrderRebateDO.class);
				rebateQueryWrapper.eq(OrderRebateDO::getOrderId, purchaseOrderDO.getOrderId());
				OrderRebateDO existingRebate = orderRebateMapper.selectOne(rebateQueryWrapper);
				if (existingRebate != null) {
					orderRebateDO.setOrderRebateId(existingRebate.getOrderRebateId());
					orderRebateMapper.updateById(orderRebateDO);
				} else {
					orderRebateMapper.insert(orderRebateDO);
				}
			}
		}


		// 更新费用信息（精细化处理）
		// 获取现有的费用列表
		LambdaQueryWrapper<OrderCostDO> costQueryWrapper = Wrappers.lambdaQuery(OrderCostDO.class);
		costQueryWrapper.eq(OrderCostDO::getOrderId, purchaseOrderDO.getOrderId());
		List<OrderCostDO> existingCosts = orderCostMapper.selectList(costQueryWrapper);

		// 获取更新的费用列表
		List<OrderCost> updatedCosts = purchaseOrderApproveCmd.getOrderCostList();

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

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

		for (OrderCost updatedCost : updatedCosts) {
			updatedCost.setOrderId(purchaseOrderDO.getOrderId());
			OrderCostDO costDO = orderCostConvert.toOrderCostDO(updatedCost);

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

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

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

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

	@Override
	@Transactional
	public void submitReview(PurchaseOrderSubmitReviewCmd purchaseOrderSubmitReviewCmd) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getOrderId, purchaseOrderSubmitReviewCmd.getOrderId());
		queryWrapper.last("limit 1");

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);
		purchaseOrderDO.setState(PurchaseOrderStateEnum.WAITING_AUDIT);
		purchaseOrderMapper.updateById(purchaseOrderDO);
	}

	@Override
	@Transactional
	public void withdrawReview(PurchaseOrderWithdrawReviewCmd purchaseOrderWithdrawReviewCmd) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getOrderId, purchaseOrderWithdrawReviewCmd.getOrderId());
		queryWrapper.last("limit 1");

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);
		purchaseOrderDO.setState(PurchaseOrderStateEnum.DRAFT);
		purchaseOrderMapper.updateById(purchaseOrderDO);
	}

	@Override
	@Transactional
	public void rejectApprove(PurchaseOrderRejectApproveCmd purchaseOrderRejectApproveCmd) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getOrderId, purchaseOrderRejectApproveCmd.getOrderId());
		queryWrapper.last("limit 1");

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);
		purchaseOrderDO.setState(PurchaseOrderStateEnum.DRAFT);
		purchaseOrderMapper.updateById(purchaseOrderDO);
	}

	@Override
	@Transactional
	public void finalApprove(PurchaseOrderFinalApproveCmd purchaseOrderFinalApproveCmd) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getOrderId, purchaseOrderFinalApproveCmd.getOrderId());
		queryWrapper.last("limit 1");

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);
		purchaseOrderDO.setState(PurchaseOrderStateEnum.SHIPPING);

		// 自动生成发货单 purchaseOrderDO 生成 shipOrder,orderPackage 变成 shipOrderPackage（按照报价价格分组插入）,orderSupplier 变成shipOrderItem（按照规格分组插入）
		// 1. 创建发货单
		ShipOrderDO shipOrderDO = new ShipOrderDO();
		shipOrderDO.setPurchaseOrderId(purchaseOrderDO.getOrderId());
		shipOrderDO.setOrderSn("FH" + generateShipOrderSn()); // 生成发货单编号

		// 从车辆信息中获取相关信息
		OrderVehicleDO orderVehicleDO = orderVehicleMapper.selectOne(
			Wrappers.lambdaQuery(OrderVehicleDO.class)
				.eq(OrderVehicleDO::getOrderId, purchaseOrderDO.getOrderId())
		);

		if (orderVehicleDO != null) {
			shipOrderDO.setLicensePlate(orderVehicleDO.getPlate());
			shipOrderDO.setDriverName(orderVehicleDO.getDriver());
			shipOrderDO.setDriverPhone(orderVehicleDO.getPhone());
			shipOrderDO.setShippingDate(orderVehicleDO.getDeliveryTime());
			shipOrderDO.setShippingAddress(orderVehicleDO.getOrigin());
			shipOrderDO.setReceivingAddress(orderVehicleDO.getDestination());
			shipOrderDO.setFreightDebt(orderVehicleDO.getPrice());
			if (orderVehicleDO.getOpenStrawCurtain()) {
				shipOrderDO.setStrawMatDebt(orderVehicleDO.getStrawCurtainPrice());
			}
			shipOrderDO.setDealerId(orderVehicleDO.getDealerId());
			shipOrderDO.setDealerName(orderVehicleDO.getDealerName());
			shipOrderDO.setVehicleNo(orderVehicleDO.getVehicleNo());
		}

		// 从公司信息中获取相关信息
		OrderCompanyDO orderCompanyDO = orderCompanyMapper.selectOne(
			Wrappers.lambdaQuery(OrderCompanyDO.class)
				.eq(OrderCompanyDO::getOrderId, purchaseOrderDO.getOrderId())
		);

		if (orderCompanyDO != null) {
			shipOrderDO.setCompanyId(orderCompanyDO.getCompanyId());
			shipOrderDO.setCompanyName(orderCompanyDO.getFullName());
		}

		// 从经销商信息中获取相关信息
		OrderDealerDO orderDealerDO = orderDealerMapper.selectOne(
			Wrappers.lambdaQuery(OrderDealerDO.class)
				.eq(OrderDealerDO::getOrderId, purchaseOrderDO.getOrderId())
		);

		// 设置其他基本信息
		shipOrderDO.setCreatedBy(purchaseOrderFinalApproveCmd.getCreatedBy());
		shipOrderDO.setCreatedByName(purchaseOrderFinalApproveCmd.getCreatedByName());

		// 4. 从OrderCostDO中提取人工费、商标费等费用信息
		List<OrderCostDO> orderCostDOList = orderCostMapper.selectList(
			Wrappers.lambdaQuery(OrderCostDO.class)
				.eq(OrderCostDO::getOrderId, purchaseOrderDO.getOrderId())
		);

		// 计算人工费总额
		BigDecimal totalLaborFee = orderCostDOList.stream()
			.filter(cost -> CostItemCostTypeEnum.HUMAN_COST.getType() == cost.getCostType().getType())
			.map(cost -> {
				if (cost.getPrice() != null && cost.getCount() != null) {
					return cost.getPrice().multiply(BigDecimal.valueOf(cost.getCount()));
				}
				return BigDecimal.ZERO;
			})
			.reduce(BigDecimal.ZERO, BigDecimal::add);
		shipOrderDO.setLaborFee(totalLaborFee);

		// 计算商标费总额
		BigDecimal totalTrademarkFee = orderCostDOList.stream()
			.filter(cost -> "商标费".equals(cost.getName()))
			.map(cost -> {
				if (cost.getPrice() != null && cost.getCount() != null) {
					return cost.getPrice().multiply(BigDecimal.valueOf(cost.getCount()));
				}
				return BigDecimal.ZERO;
			})
			.reduce(BigDecimal.ZERO, BigDecimal::add);
		shipOrderDO.setTrademarkFee(totalTrademarkFee);

		// 计算打码费总额
		BigDecimal totalCodingFee = orderCostDOList.stream()
			.filter(cost -> "打码费".equals(cost.getName()))
			.map(cost -> {
				if (cost.getPrice() != null && cost.getCount() != null) {
					return cost.getPrice().multiply(BigDecimal.valueOf(cost.getCount()));
				}
				return BigDecimal.ZERO;
			})
			.reduce(BigDecimal.ZERO, BigDecimal::add);
		shipOrderDO.setTrademarkFee(totalCodingFee);

		shipOrderDO.setCodingFee(totalTrademarkFee);

		// 2. 处理包材信息，转换为发货单包材信息（按照boxCategoryId和boxProductName分组）
		List<OrderSupplierDO> orderSupplierDOList = orderSupplierMapper.selectList(
			Wrappers.lambdaQuery(OrderSupplierDO.class)
				.eq(OrderSupplierDO::getOrderId, purchaseOrderDO.getOrderId())
		);

		// 收集所有的包材信息
		List<Long> orderSupplierIdList = orderSupplierDOList.stream()
			.map(OrderSupplierDO::getOrderSupplierId)
			.toList();

		List<OrderPackageDO> orderPackageDOList = new ArrayList<>();
		if (CollUtil.isNotEmpty(orderSupplierIdList)) {
			orderPackageDOList = orderPackageMapper.selectList(
				Wrappers.lambdaQuery(OrderPackageDO.class)
					.in(OrderPackageDO::getOrderSupplierId, orderSupplierIdList)
			);
		}
		// 计算纸箱费总额
		BigDecimal totalCartonFee = orderPackageDOList.stream()
			.map(p -> {
				if (p.getBoxSalePrice() != null && p.getBoxCount() != null) {
					return p.getBoxSalePrice().multiply(BigDecimal.valueOf(p.getBoxCount()));
				}
				return BigDecimal.ZERO;
			})
			.reduce(BigDecimal.ZERO, BigDecimal::add);

		shipOrderDO.setCartonFee(totalCartonFee);

		// 插入发货单
		shipOrderMapper.insert(shipOrderDO);

		// 按boxCategoryId和boxProductName分组包材信息
		Map<String, List<OrderPackageDO>> packageGroupByKey = orderPackageDOList.stream()
			.collect(Collectors.groupingBy(p -> p.getBoxCategoryId() + "_" + p.getBoxProductName()));

		// 创建发货单包材信息
		for (Map.Entry<String, List<OrderPackageDO>> entry : packageGroupByKey.entrySet()) {
			List<OrderPackageDO> packages = entry.getValue();

			// 合并相同类型的包材信息
			ShipOrderPackageDO shipOrderPackageDO = new ShipOrderPackageDO();
			shipOrderPackageDO.setShipOrderId(shipOrderDO.getShipOrderId());

			// 使用第一个包材的信息作为基础
			OrderPackageDO firstPackage = packages.get(0);
			shipOrderPackageDO.setBoxCategory(firstPackage.getBoxCategoryId());
			shipOrderPackageDO.setBoxProduct(firstPackage.getBoxProductName());

			// 使用第一个包材的销售价格作为单价
			shipOrderPackageDO.setUnitPrice(firstPackage.getBoxSalePrice());

			// 计算总数量
			int totalQuantity = packages.stream()
				.mapToInt(OrderPackageDO::getBoxCount)
				.sum();
			shipOrderPackageDO.setQuantity(totalQuantity);

			// 计算总金额
			BigDecimal unitPrice = firstPackage.getBoxSalePrice() != null ? firstPackage.getBoxSalePrice() : BigDecimal.ZERO;
			BigDecimal totalAmount = unitPrice.multiply(BigDecimal.valueOf(totalQuantity));
			shipOrderPackageDO.setItemAmount(totalAmount);

			// 计算总重量（如果有）
			BigDecimal totalWeight = packages.stream()
				.map(p -> {
					if (p.getBoxProductWeight() != null && p.getBoxCount() != null) {
						return p.getBoxProductWeight().multiply(BigDecimal.valueOf(p.getBoxCount()));
					}
					return BigDecimal.ZERO;
				})
				.reduce(BigDecimal.ZERO, BigDecimal::add);
			shipOrderPackageDO.setTotalWeight(totalWeight);

			shipOrderPackageDO.setSingleWeight(shipOrderPackageDO.getTotalWeight().divide(shipOrderPackageDO.getUnitPrice(), 2, RoundingMode.HALF_UP));

			shipOrderPackageMapper.insert(shipOrderPackageDO);
		}

		// 3. 处理供应商信息，转换为发货单项信息（按照规格分组）
		// 按销售单价分组供应商信息
		Map<BigDecimal, List<OrderSupplierDO>> supplierGroupByPrice = orderSupplierDOList.stream()
			.collect(Collectors.groupingBy(OrderSupplierDO::getSalePrice));

		// 创建发货单项信息
		for (Map.Entry<BigDecimal, List<OrderSupplierDO>> entry : supplierGroupByPrice.entrySet()) {
			List<OrderSupplierDO> suppliers = entry.getValue();

			// 合并相同价格的供应商信息
			ShipOrderItemDO shipOrderItemDO = new ShipOrderItemDO();
			shipOrderItemDO.setShipOrderId(shipOrderDO.getShipOrderId());

			// 计算总毛重
			BigDecimal totalGrossWeight = suppliers.stream()
				.map(OrderSupplierDO::getGrossWeight)
				.filter(Objects::nonNull)
				.reduce(BigDecimal.ZERO, BigDecimal::add);
			shipOrderItemDO.setGrossWeight(totalGrossWeight);

			// 计算总净重
			BigDecimal totalNetWeight = suppliers.stream()
				.map(OrderSupplierDO::getNetWeight)
				.filter(Objects::nonNull)
				.reduce(BigDecimal.ZERO, BigDecimal::add);
			shipOrderItemDO.setNetWeight(totalNetWeight);

			shipOrderItemDO.setBoxWeight(totalGrossWeight.subtract(totalNetWeight));

			// 计算总箱数
			Integer totalBoxCount = suppliers.stream()
				.map(OrderSupplierDO::getOrderPackageDOList)
				.flatMap(Collection::stream)
				.map(OrderPackageDO::getBoxCount)
				.reduce(0, Integer::sum);

			shipOrderItemDO.setBoxCount(totalBoxCount);

			// 设置单价
			BigDecimal salePrice = entry.getKey();
			shipOrderItemDO.setUnitPrice(salePrice);

			// 计算总金额
			if (salePrice != null) {
				BigDecimal totalAmount = salePrice.multiply(totalNetWeight);
				shipOrderItemDO.setTotalAmount(totalAmount);
			}

			shipOrderItemMapper.insert(shipOrderItemDO);
		}

		purchaseOrderMapper.updateById(purchaseOrderDO);
	}

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

	@Override
	@Transactional
	public void rejectFinal(PurchaseOrderRejectFinalCmd purchaseOrderRejectFinalCmd) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getOrderId, purchaseOrderRejectFinalCmd.getOrderId());
		queryWrapper.last("limit 1");

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);
		purchaseOrderDO.setState(PurchaseOrderStateEnum.WAITING_AUDIT);
		purchaseOrderMapper.updateById(purchaseOrderDO);
	}

	@Override
	public Long countBy(PurchaseOrderCountQry purchaseOrderCountQry) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getCreatedBy, purchaseOrderCountQry.getCreatedBy());
		queryWrapper.eq(PurchaseOrderDO::getState, purchaseOrderCountQry.getState());
		return purchaseOrderMapper.selectCount(queryWrapper);
	}

	@Override
	@Transactional
	public PurchaseOrder saveStep1(PurchaseOrderStep1Cmd purchaseOrderStep1Cmd) {
		PurchaseOrderDO purchaseOrderDO;

		// 如果订单ID为空，则创建新订单
		if (purchaseOrderStep1Cmd.getOrderId() == null) {
			purchaseOrderDO = purchaseOrderConvert.toPurchaseOrderDO(purchaseOrderStep1Cmd);
			purchaseOrderDO.setState(PurchaseOrderStateEnum.DRAFT);
			purchaseOrderDO.setOrderSn("CG" + generateShipOrderSn());
			purchaseOrderMapper.insert(purchaseOrderDO);
		} else {
			// 否则更新现有订单
			LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
			queryWrapper.eq(PurchaseOrderDO::getOrderId, purchaseOrderStep1Cmd.getOrderId());
			queryWrapper.select(PurchaseOrderDO::getOrderId, PurchaseOrderDO::getActive);
			queryWrapper.last("limit 1");
			purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);
			purchaseOrderDO.setActive(purchaseOrderStep1Cmd.getActive());
			purchaseOrderMapper.updateById(purchaseOrderDO);
		}

		// 保存或更新车辆信息
		OrderVehicle orderVehicle = purchaseOrderStep1Cmd.getOrderVehicle();
		orderVehicle.setOrderId(purchaseOrderDO.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, purchaseOrderDO.getOrderId());
			OrderVehicleDO existingVehicle = orderVehicleMapper.selectOne(vehicleQueryWrapper);

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

		// 保存或更新经销商信息
		OrderDealer orderDealer = purchaseOrderStep1Cmd.getOrderDealer();
		orderDealer.setOrderId(purchaseOrderDO.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, purchaseOrderDO.getOrderId());
			OrderDealerDO existingDealer = orderDealerMapper.selectOne(dealerQueryWrapper);

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

		// 更新费用信息（精细化处理）
		// 获取现有的费用列表
		LambdaQueryWrapper<OrderCostDO> costQueryWrapper = Wrappers.lambdaQuery(OrderCostDO.class);
		costQueryWrapper.eq(OrderCostDO::getOrderId, purchaseOrderDO.getOrderId());
		List<OrderCostDO> existingCosts = orderCostMapper.selectList(costQueryWrapper);

		// 获取更新的费用列表
		List<OrderCost> updatedCosts = purchaseOrderStep1Cmd.getOrderCostList().stream().toList();

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

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

		for (OrderCost updatedCost : updatedCosts) {
			updatedCost.setOrderId(purchaseOrderDO.getOrderId());
			OrderCostDO costDO = orderCostConvert.toOrderCostDO(updatedCost);

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

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

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

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

		return purchaseOrderConvert.toPurchaseOrder(purchaseOrderDO);
	}

	@Override
	@Transactional
	public void saveStep2(PurchaseOrderStep2Cmd purchaseOrderStep2Cmd) {
		Long orderId = purchaseOrderStep2Cmd.getOrderId();

		// 否则更新现有订单
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getOrderId, orderId);
		queryWrapper.select(PurchaseOrderDO::getOrderId, PurchaseOrderDO::getActive);
		queryWrapper.last("limit 1");
		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);
		purchaseOrderDO.setActive(purchaseOrderStep2Cmd.getActive());
		purchaseOrderMapper.updateById(purchaseOrderDO);

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

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

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

		// 将更新后的供应商映射到ID字典中便于查找
		Map<Long, Long> existingSupplierMap = existingSuppliers.stream().collect(Collectors.toMap(OrderSupplierDO::getSupplierId, OrderSupplierDO::getOrderSupplierId));

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

		for (OrderSupplier updatedSupplier : updatedSuppliers) {
			// 检查供应商ID是否为空，如果为空则创建新的供应商
			if (Objects.isNull(updatedSupplier.getSupplierId())) {
				SupplierDO supplierDO1 = supplierConvert.toSupplierDO(updatedSupplier);
				supplierDO1.setStatus(Boolean.TRUE);
				supplierDO1.setCreatedBy(purchaseOrderStep2Cmd.getCreatedBy());
				supplierDO1.setCreatedByName(purchaseOrderStep2Cmd.getCreatedByName());
				supplierMapper.insert(supplierDO1);

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

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

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

				Long orderSupplierId = existingSupplierMap.get(updatedSupplier.getSupplierId());
				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);

		if (purchaseOrderStep2Cmd.getActive() == 3) {
			// 更新费用信息（精细化处理）
			// 获取现有的费用列表
			LambdaQueryWrapper<OrderCostDO> costQueryWrapper = Wrappers.lambdaQuery(OrderCostDO.class);
			costQueryWrapper.eq(OrderCostDO::getOrderId, orderId);
			List<OrderCostDO> existingCosts = orderCostMapper.selectList(costQueryWrapper);

			// 获取更新的费用列表
			List<OrderCost> updatedCosts = purchaseOrderStep2Cmd.getOrderCostList().stream().toList();

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

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

			for (OrderCost updatedCost : updatedCosts) {
				updatedCost.setOrderId(orderId);
				OrderCostDO costDO = orderCostConvert.toOrderCostDO(updatedCost);

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

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

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

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

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

			for (OrderSupplierDO supplierDO : allAffectedSuppliers) {
				// 查找对应的更新数据
				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);

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

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

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

						if (orderPackage.getOrderPackageId() != null && existingPackageMap.containsKey(orderPackage.getOrderPackageId())) {
							// 更新已存在的包材
							orderPackageDO.setOrderPackageId(orderPackage.getOrderPackageId());
							packagesToUpdate.add(orderPackageDO);
							// 从现有映射中移除，剩下的就是需要删除的
							existingPackageMap.remove(orderPackage.getOrderPackageId());
						} 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);
				}
			}
		}
	}

	@Override
	@Transactional
	public void saveStep3(PurchaseOrderStep3Cmd purchaseOrderStep3Cmd) {
		Long orderId = purchaseOrderStep3Cmd.getOrderId();

		// 否则更新现有订单
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getOrderId, orderId);
		queryWrapper.select(PurchaseOrderDO::getOrderId, PurchaseOrderDO::getActive);
		queryWrapper.last("limit 1");
		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);
		purchaseOrderDO.setActive(purchaseOrderStep3Cmd.getActive());
		purchaseOrderMapper.updateById(purchaseOrderDO);

		// 更新费用信息（精细化处理）
		// 获取现有的费用列表
		LambdaQueryWrapper<OrderCostDO> costQueryWrapper = Wrappers.lambdaQuery(OrderCostDO.class);
		costQueryWrapper.eq(OrderCostDO::getOrderId, orderId);
		List<OrderCostDO> existingCosts = orderCostMapper.selectList(costQueryWrapper);

		// 获取更新的费用列表
		List<OrderCost> updatedCosts = purchaseOrderStep3Cmd.getOrderCostList().stream().toList();

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

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

		for (OrderCost updatedCost : updatedCosts) {
			updatedCost.setOrderId(orderId);
			OrderCostDO costDO = orderCostConvert.toOrderCostDO(updatedCost);

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

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

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

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

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

		OrderVehicleDO orderVehicleDO = orderVehicleMapper.selectOne(queryWrapper);
		return orderVehicleDO != null ? orderVehicleDO.getVehicleNo() : null;
	}
}

