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.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.time.LocalDateTime;
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 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 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 OrderAuditMapper orderAuditMapper;

	@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.getAuditState()), PurchaseOrderDO::getAuditState, purchaseOrderPageQry.getAuditState());
		queryWrapper.eq(Objects.nonNull(purchaseOrderPageQry.getCreatedBy()), PurchaseOrderDO::getCreatedBy, purchaseOrderPageQry.getCreatedBy());
		queryWrapper.eq(Objects.nonNull(purchaseOrderPageQry.getType()), PurchaseOrderDO::getType, purchaseOrderPageQry.getType());

		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);
		queryWrapper.like(StrUtil.isNotBlank(purchaseOrderListQry.getOrderSn()), PurchaseOrderDO::getOrderSn, purchaseOrderListQry.getOrderSn());
		queryWrapper.eq(Objects.nonNull(purchaseOrderListQry.getState()), PurchaseOrderDO::getState, purchaseOrderListQry.getState());
		queryWrapper.eq(Objects.nonNull(purchaseOrderListQry.getAuditState()), PurchaseOrderDO::getAuditState, purchaseOrderListQry.getAuditState());
		queryWrapper.eq(Objects.nonNull(purchaseOrderListQry.getCreatedBy()), PurchaseOrderDO::getCreatedBy, purchaseOrderListQry.getCreatedBy());
		queryWrapper.eq(Objects.nonNull(purchaseOrderListQry.getType()), PurchaseOrderDO::getType, purchaseOrderListQry.getType());
		queryWrapper.select(PurchaseOrderDO::getOrderId, PurchaseOrderDO::getOrderSn, PurchaseOrderDO::getState, PurchaseOrderDO::getAuditState, PurchaseOrderDO::getType);

		queryWrapper.orderByDesc(PurchaseOrderDO::getCreatedAt);
		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.eq(Objects.nonNull(purchaseOrderShowQry.getType()), PurchaseOrderDO::getType, purchaseOrderShowQry.getType());

		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();

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

			purchaseOrderDO.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());
				});
			}

			purchaseOrderDO.setOrderSupplierDOList(orderSupplierDOList);

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

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

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

			LambdaQueryWrapper<OrderShipItemDO> queryWrapper7 = Wrappers.lambdaQuery(OrderShipItemDO.class);
			queryWrapper7.eq(OrderShipItemDO::getOrderId, purchaseOrderDO.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());
				});
			}
			purchaseOrderDO.setOrderShipDOList(orderShipDOList);


		}

		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.eq(PurchaseOrderDO::getState, PurchaseOrderStateEnum.WAITING_AUDIT);
		queryWrapper.last("limit 1");

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);

		if (Objects.isNull(purchaseOrderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_PURCHASE_ORDER_NOT_WAITING_AUDIT);
		}
		purchaseOrderDO.setPricingMethod(purchaseOrderApproveCmd.getPricingMethod());

		if (!purchaseOrderApproveCmd.getDraft()) {
			purchaseOrderDO.setAuditState(PurchaseOrderAuditStateEnum.PENDING_BOSS_APPROVAL);

			// 更新审核记录状态为审核成功
			LambdaQueryWrapper<OrderAuditDO> auditQueryWrapper = Wrappers.lambdaQuery(OrderAuditDO.class);
			auditQueryWrapper.eq(OrderAuditDO::getOrderId, purchaseOrderApproveCmd.getOrderId());
			auditQueryWrapper.eq(OrderAuditDO::getState, OrderAuditStateEnum.WAITING_AUDIT);
			auditQueryWrapper.eq(OrderAuditDO::getType, OrderAuditTypeEnum.REVIEWER_AUDIT);
			OrderAuditDO orderAuditDO = orderAuditMapper.selectOne(auditQueryWrapper);

			if (orderAuditDO != null) {
				orderAuditDO.setState(OrderAuditStateEnum.AUDIT_SUCCESS);
				orderAuditDO.setAuditAt(LocalDateTime.now());
				orderAuditDO.setAuditBy(purchaseOrderApproveCmd.getCreatedBy());
				orderAuditDO.setAuditByName(purchaseOrderApproveCmd.getCreatedByName());
				orderAuditMapper.updateById(orderAuditDO);
			} else {
				// 如果审核记录不存在，抛出异常
				throw new BizException(BizErrorCode.B_BIZ_ORDER_AUDIT_NOT_FOUND);
			}


			// 自动生成报老板待审核记录（每次都创建新记录）
			OrderAuditDO orderAuditDO1 = new OrderAuditDO();
			orderAuditDO1.setOrderId(purchaseOrderApproveCmd.getOrderId());
			orderAuditDO1.setType(OrderAuditTypeEnum.BOSS_AUDIT);
			orderAuditDO1.setState(OrderAuditStateEnum.WAITING_AUDIT);
			orderAuditDO1.setCreatedBy(purchaseOrderApproveCmd.getCreatedBy());
			orderAuditDO1.setCreatedByName(purchaseOrderApproveCmd.getCreatedByName());
			orderAuditMapper.insert(orderAuditDO1);
		}

		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 = purchaseOrderConvert.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 = purchaseOrderConvert.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);
				}
			}
		}

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

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

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

	/**
	 * 保存订单发货信息
	 */
	private void saveOrderShip(Long orderId, List<OrderShip> orderShipList, PurchaseOrderApproveCmd purchaseOrderApproveCmd) {
		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 = orderShipConvert.toOrderShipDO(updatedShip);
			orderShipDO.setCreatedBy(purchaseOrderApproveCmd.getCreatedBy());
			orderShipDO.setCreatedByName(purchaseOrderApproveCmd.getCreatedByName());
			if (purchaseOrderApproveCmd.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 {
				// 新增发货单
				// 生成发货单编号
				if (StrUtil.isBlank(orderShipDO.getOrderSn())) {
					orderShipDO.setOrderSn("SO" + 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); // 稍后设置
							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);
			}
		});
	}

	/**
	 * 保存发货单明细
	 */
	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);

		// 将现有明细映射到 itemId 字典中便于查找
		Map<Long, OrderShipItemDO> existingItemMap = existingItems.stream()
			.filter(item -> item.getItemId() != null)
			.collect(Collectors.toMap(OrderShipItemDO::getItemId, Function.identity()));

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

		for (OrderShipItem updatedItem : orderShipItemList) {
			OrderShipItemDO itemDO = orderShipItemConvert.toOrderShipItemDO(updatedItem);

			if (existingItemMap.containsKey(updatedItem.getItemId())) {
				// 更新已存在的明细
				itemDO.setItemId(updatedItem.getItemId());
				itemDO.setOrderShipId(orderShipDO.getOrderShipId());
				itemsToUpdate.add(itemDO);
				// 从现有映射中移除，剩下的就是需要删除的
				existingItemMap.remove(updatedItem.getItemId());
			} else {
				// 新增明细
				itemDO.setOrderShipId(orderShipDO.getOrderShipId());
				itemsToInsert.add(itemDO);
			}
		}

		// 删除不再需要的明细
		existingItemMap.values().forEach(OrderShipItemDO::deleteById);

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

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

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

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);

		if (Objects.isNull(purchaseOrderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_PURCHASE_ORDER_NOT_DRAFT);
		}

		purchaseOrderDO.setState(PurchaseOrderStateEnum.WAITING_AUDIT);
		purchaseOrderDO.setAuditState(PurchaseOrderAuditStateEnum.PENDING_QUOTE_APPROVAL);

		purchaseOrderMapper.updateById(purchaseOrderDO);

		// 自动生成报价审核员待审核记录（每次都创建新记录）
		OrderAuditDO orderAuditDO = new OrderAuditDO();
		orderAuditDO.setOrderId(purchaseOrderSubmitReviewCmd.getOrderId());
		orderAuditDO.setType(OrderAuditTypeEnum.REVIEWER_AUDIT);
		orderAuditDO.setState(OrderAuditStateEnum.WAITING_AUDIT);
		orderAuditDO.setCreatedBy(purchaseOrderSubmitReviewCmd.getCreatedBy());
		orderAuditDO.setCreatedByName(purchaseOrderSubmitReviewCmd.getCreatedByName());
		orderAuditMapper.insert(orderAuditDO);
	}

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

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);

		if (Objects.isNull(purchaseOrderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_PURCHASE_ORDER_NOT_WAITING_FOR_WITHDRAW);
		}


		purchaseOrderDO.setState(PurchaseOrderStateEnum.DRAFT);
		purchaseOrderDO.setAuditState(PurchaseOrderAuditStateEnum.NONE);
		purchaseOrderMapper.updateById(purchaseOrderDO);

		// 更新审核记录状态为草稿（撤回审核）
		LambdaQueryWrapper<OrderAuditDO> auditQueryWrapper = Wrappers.lambdaQuery(OrderAuditDO.class);
		auditQueryWrapper.eq(OrderAuditDO::getOrderId, purchaseOrderWithdrawReviewCmd.getOrderId());
		auditQueryWrapper.eq(OrderAuditDO::getState, OrderAuditStateEnum.WAITING_AUDIT);
		auditQueryWrapper.eq(OrderAuditDO::getType, OrderAuditTypeEnum.REVIEWER_AUDIT);
		OrderAuditDO orderAuditDO = orderAuditMapper.selectOne(auditQueryWrapper);

		if (orderAuditDO != null) {
			orderAuditDO.setState(OrderAuditStateEnum.AUDIT_CANCEL);
			orderAuditDO.setAuditAt(LocalDateTime.now());
			orderAuditDO.setAuditBy(purchaseOrderWithdrawReviewCmd.getCreatedBy());
			orderAuditDO.setAuditByName(purchaseOrderWithdrawReviewCmd.getCreatedByName());
			orderAuditMapper.updateById(orderAuditDO);
		}
	}

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

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);

		if (Objects.isNull(purchaseOrderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_PURCHASE_ORDER_NOT_WAITING_AUDIT);
		}

		purchaseOrderDO.setState(PurchaseOrderStateEnum.REJECTED);
		purchaseOrderDO.setAuditState(PurchaseOrderAuditStateEnum.QUOTE_REJECTED);

		purchaseOrderMapper.updateById(purchaseOrderDO);

		// 更新审核记录
		LambdaQueryWrapper<OrderAuditDO> auditQueryWrapper = Wrappers.lambdaQuery(OrderAuditDO.class);
		auditQueryWrapper.eq(OrderAuditDO::getOrderId, purchaseOrderRejectApproveCmd.getOrderId());
		auditQueryWrapper.eq(OrderAuditDO::getState, OrderAuditStateEnum.WAITING_AUDIT);
		auditQueryWrapper.eq(OrderAuditDO::getType, OrderAuditTypeEnum.REVIEWER_AUDIT);
		OrderAuditDO orderAuditDO = orderAuditMapper.selectOne(auditQueryWrapper);

		if (orderAuditDO != null) {
			orderAuditDO.setState(OrderAuditStateEnum.AUDIT_REJECTED);
			orderAuditDO.setAuditReason(purchaseOrderRejectApproveCmd.getRejectReason());
			orderAuditDO.setAuditAt(LocalDateTime.now());
			orderAuditDO.setAuditBy(purchaseOrderRejectApproveCmd.getCreatedBy());
			orderAuditDO.setAuditByName(purchaseOrderRejectApproveCmd.getCreatedByName());
			orderAuditMapper.updateById(orderAuditDO);
		} else {
			// 如果审核记录不存在，抛出异常
			throw new BizException(BizErrorCode.B_BIZ_ORDER_AUDIT_NOT_FOUND);
		}

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

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

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);

		if (Objects.isNull(purchaseOrderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_PURCHASE_ORDER_NOT_WAITING_FOR_FINAL_APPROVE);
		}

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

		// 更新审核记录为审核成功
		LambdaQueryWrapper<OrderAuditDO> auditQueryWrapper = Wrappers.lambdaQuery(OrderAuditDO.class);
		auditQueryWrapper.eq(OrderAuditDO::getOrderId, purchaseOrderFinalApproveCmd.getOrderId());
		auditQueryWrapper.eq(OrderAuditDO::getState, OrderAuditStateEnum.WAITING_AUDIT);
		auditQueryWrapper.eq(OrderAuditDO::getType, OrderAuditTypeEnum.BOSS_AUDIT);
		OrderAuditDO orderAuditDO = orderAuditMapper.selectOne(auditQueryWrapper);

		if (orderAuditDO != null) {
			orderAuditDO.setState(OrderAuditStateEnum.AUDIT_SUCCESS);
			orderAuditDO.setAuditAt(LocalDateTime.now());
			orderAuditDO.setAuditBy(purchaseOrderFinalApproveCmd.getCreatedBy());
			orderAuditDO.setAuditByName(purchaseOrderFinalApproveCmd.getCreatedByName());
			orderAuditMapper.updateById(orderAuditDO);
		} else {
			// 如果审核记录不存在，抛出异常
			throw new BizException(BizErrorCode.B_BIZ_ORDER_AUDIT_NOT_FOUND);
		}

		purchaseOrderMapper.updateById(purchaseOrderDO);

		// 发货单改成已发货（待回款）
		LambdaUpdateWrapper<OrderShipDO> updateWrapper = Wrappers.lambdaUpdate(OrderShipDO.class);
		updateWrapper.eq(OrderShipDO::getOrderId, purchaseOrderDO.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
	@Transactional
	public void rejectFinal(PurchaseOrderRejectFinalCmd purchaseOrderRejectFinalCmd) {
		LambdaQueryWrapper<PurchaseOrderDO> queryWrapper = Wrappers.lambdaQuery(PurchaseOrderDO.class);
		queryWrapper.eq(PurchaseOrderDO::getOrderId, purchaseOrderRejectFinalCmd.getOrderId());
		queryWrapper.eq(PurchaseOrderDO::getState, PurchaseOrderStateEnum.WAITING_AUDIT);
		queryWrapper.eq(PurchaseOrderDO::getAuditState, PurchaseOrderAuditStateEnum.PENDING_BOSS_APPROVAL);
		queryWrapper.last("limit 1");

		PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectOne(queryWrapper);

		if (Objects.isNull(purchaseOrderDO)) {
			throw new BizException(BizErrorCode.B_BIZ_PURCHASE_ORDER_NOT_WAITING_FOR_REJECT_FINAL);
		}

		purchaseOrderDO.setState(PurchaseOrderStateEnum.REJECTED);
		purchaseOrderDO.setAuditState(PurchaseOrderAuditStateEnum.BOSS_REJECTED);
		purchaseOrderMapper.updateById(purchaseOrderDO);

		// 更新审核记录
		LambdaQueryWrapper<OrderAuditDO> auditQueryWrapper = Wrappers.lambdaQuery(OrderAuditDO.class);
		auditQueryWrapper.eq(OrderAuditDO::getOrderId, purchaseOrderRejectFinalCmd.getOrderId());
		auditQueryWrapper.eq(OrderAuditDO::getState, OrderAuditStateEnum.WAITING_AUDIT);
		auditQueryWrapper.eq(OrderAuditDO::getType, OrderAuditTypeEnum.BOSS_AUDIT);
		OrderAuditDO orderAuditDO = orderAuditMapper.selectOne(auditQueryWrapper);

		if (orderAuditDO != null) {
			orderAuditDO.setState(OrderAuditStateEnum.AUDIT_REJECTED);
			orderAuditDO.setAuditReason(purchaseOrderRejectFinalCmd.getRejectReason());
			orderAuditDO.setAuditAt(LocalDateTime.now());
			orderAuditDO.setAuditBy(purchaseOrderRejectFinalCmd.getCreatedBy());
			orderAuditDO.setAuditByName(purchaseOrderRejectFinalCmd.getCreatedByName());
			orderAuditMapper.updateById(orderAuditDO);
		} else {
			// 如果审核记录不存在，抛出异常
			throw new BizException(BizErrorCode.B_BIZ_ORDER_AUDIT_NOT_FOUND);
		}
	}

	@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" + generateOrderShipSn());
			purchaseOrderDO.setType(purchaseOrderStep1Cmd.getType());
			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());
			purchaseOrderDO.setState(PurchaseOrderStateEnum.DRAFT);
			purchaseOrderDO.setType(purchaseOrderStep1Cmd.getType());
			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);
			}
		}

		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());
		purchaseOrderDO.setState(PurchaseOrderStateEnum.DRAFT);
		purchaseOrderDO.setType(purchaseOrderStep2Cmd.getType());

		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()));

		// 收集需要更新和新增的供应商
		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(purchaseOrderStep2Cmd.getCreatedBy());
					supplierDO.setCreatedByName(purchaseOrderStep2Cmd.getCreatedByName());
					supplierMapper.insert(supplierDO);
				}

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

			updatedSupplier.setOrderId(orderId);
			OrderSupplierDO orderSupplierDO = purchaseOrderConvert.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 (purchaseOrderStep2Cmd.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(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());
		purchaseOrderDO.setForeman(purchaseOrderStep3Cmd.getForeman());
		purchaseOrderDO.setType(purchaseOrderStep3Cmd.getType());
		purchaseOrderDO.setState(PurchaseOrderStateEnum.DRAFT);
		purchaseOrderMapper.updateById(purchaseOrderDO);

		saveOrderCostItem(orderId, purchaseOrderStep3Cmd.getOrderCostItemList().stream().toList());
		saveOrderCost(purchaseOrderDO.getOrderId(), purchaseOrderStep3Cmd.getOrderCostList().stream().toList());

		// 空箱费
		if (purchaseOrderStep3Cmd.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 : purchaseOrderStep3Cmd.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);
		return orderVehicleDO != null ? orderVehicleDO.getVehicleNo() : null;
	}

	/**
	 * 更新费用信息（精细化处理）
	 * 获取现有的费用列表
	 *
	 * @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 = purchaseOrderConvert.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);
	}
}

