package com.seer.teach.mall.app.order.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.seer.teach.common.constants.CommonConstant;
import com.seer.teach.common.enums.CommentStatusEnum;
import com.seer.teach.common.enums.OperateTypeEnum;
import com.seer.teach.common.enums.OrderStatusEnum;
import com.seer.teach.common.enums.TenantEnum;
import com.seer.teach.common.enums.pay.PayChannelEnum;
import com.seer.teach.common.enums.PaymentModeEnum;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.enums.ShippingStatusEnum;
import com.seer.teach.common.enums.UserTypeEnum;
import com.seer.teach.common.enums.pay.PayStatusEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.MoneyUtil;
import com.seer.teach.common.utils.OrderIdGenerator;
import com.seer.teach.mall.annotation.OrderLog;
import com.seer.teach.mall.app.good.service.IAppGoodsSpecificationService;
import com.seer.teach.mall.service.IAddressService;
import com.seer.teach.mall.app.order.service.IAppCartService;
import com.seer.teach.mall.app.order.service.IAppOrderService;
import com.seer.teach.mall.entity.CartEntity;
import com.seer.teach.mall.entity.GoodsEntity;
import com.seer.teach.mall.entity.GoodsSpecificationEntity;
import com.seer.teach.mall.entity.OrderChildEntity;
import com.seer.teach.mall.entity.OrderEntity;
import com.seer.teach.mall.entity.OrderGoodsEntity;
import com.seer.teach.mall.handler.OrderHandler;
import com.seer.teach.mall.request.OrderGoodReq;
import com.seer.teach.mall.request.OrderReq;
import com.seer.teach.mall.request.OrderSettlementReq;
import com.seer.teach.mall.request.OrderUpdateReq;
import com.seer.teach.mall.response.AddressResp;
import com.seer.teach.mall.response.OrderSettlementRespVO;
import com.seer.teach.mall.service.IGoodsService;
import com.seer.teach.mall.service.IOrderChildService;
import com.seer.teach.mall.service.IOrderGoodsService;
import com.seer.teach.mall.service.IOrderService;
import com.seer.teach.mall.util.OrderLogUtils;
import com.seer.teach.pay.api.wallet.CoinAccountServiceApi;
import com.seer.teach.pay.api.wallet.dto.CoinConfigRespDTO;
import com.seer.teach.pay.api.wallet.dto.CoinToAmountRespDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户订单服务实现类
 * </p>
 *
 * @author Captain
 * @since 2025-06-10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppOrderServiceImpl implements IAppOrderService {

    private final IOrderService orderService;

    private final IGoodsService goodsService;

    private final IOrderGoodsService orderGoodsService;

    private final IAddressService addressService;

    private final IAppCartService cartService;

    private final CoinAccountServiceApi accountServiceApi;

    private final IAppGoodsSpecificationService goodsSpecificationService;

    private final IOrderChildService orderChildService;

    @Resource
    private List<OrderHandler> orderHandlers;

    @Override
    public OrderSettlementRespVO getSettlementOrderDetail(OrderSettlementReq orderSettlementReq) {
        log.info("开始处理订单结算请求");
        List<OrderSettlementReq.Item> items = orderSettlementReq.getItems();
        if (CollectionUtils.isEmpty(items)) {
            log.warn("订单结算请求中无商品项");
            return new OrderSettlementRespVO();
        }
        List<Integer> skuIdList = new ArrayList<>();
        List<Integer> cartIdList = new ArrayList<>();
        for (OrderSettlementReq.Item item : items) {
            if (Objects.nonNull(item.getCartId())) {
                cartIdList.add(item.getCartId());
            }
            if (Objects.nonNull(item.getSkuId())) {
                skuIdList.add(item.getSkuId());
            }
        }
        log.debug("从购物车ID列表中提取SKU ID，购物车ID列表: {}", cartIdList);
        if (CollectionUtil.isNotEmpty(cartIdList)) {
            List<CartEntity> cartEntityList = cartService.listByIds(cartIdList);
            if (CollectionUtil.isNotEmpty(cartEntityList)) {
                skuIdList.addAll(cartEntityList.stream().map(CartEntity::getSkuId).collect(Collectors.toList()));
            }
        }

        AssertUtils.notEmpty(skuIdList, ResultCodeEnum.GOOD_NOT_FOUND);
        log.info("根据SKU ID列表查询商品规格信息，SKU ID列表: {}", skuIdList);
        // 根据商品规格ID列表查询商品实体列表
        List<GoodsSpecificationEntity> goodsSpecificationEntityList = goodsSpecificationService.list(new LambdaUpdateWrapper<>(GoodsSpecificationEntity.class).in(GoodsSpecificationEntity::getId, skuIdList));

        AssertUtils.notEmpty(goodsSpecificationEntityList, ResultCodeEnum.GOOD_NOT_FOUND);

        // 初始化订单结算响应中的商品项列表和总价格
        List<OrderSettlementRespVO.Item> goodRespList = new ArrayList<>();
        Map<Integer, Integer> map = items.stream().collect(Collectors.toMap(OrderSettlementReq.Item::getSkuId, OrderSettlementReq.Item::getCount, (old, newItem) -> newItem));
        BigDecimal totalPrices = BigDecimal.ZERO;

        Set<Integer> goodIdList = goodsSpecificationEntityList.stream().map(GoodsSpecificationEntity::getGoodsId).collect(Collectors.toSet());
        List<GoodsEntity> goodsEntities = goodsService.listByIds(goodIdList);
        Map<Integer, GoodsEntity> goodsEntityMap = goodsEntities.stream().collect(Collectors.toMap(GoodsEntity::getId, Function.identity(), (v1, v2) -> v1));
        // 构建订单结算响应中的商品项，并计算总价格
        int totalCount = 0;
        for (GoodsSpecificationEntity goodSku : goodsSpecificationEntityList) {
            Integer count = map.getOrDefault(goodSku.getId(), 1);
            GoodsEntity goods = goodsEntityMap.get(goodSku.getGoodsId());
            if (Objects.isNull(goods)) {
                continue;
            }
            OrderSettlementRespVO.Item item = new OrderSettlementRespVO.Item();
            item.setName(goods.getName());
            item.setGoodsId(goods.getId());

            BigDecimal price = new BigDecimal(String.valueOf(goodSku.getPrice())).multiply(new BigDecimal(count));
            item.setPrice(price);
            item.setPicUrl(goodSku.getPicUrl());
            item.setCount(count);
            item.setSkuId(goodSku.getId());
            item.setAttributeList(goodSku.getAttributes());
            goodRespList.add(item);
            // 只计算在线支付的商品
            if (PaymentModeEnum.ONLINE.getCode().intValue() == goods.getPaymentMode().intValue()) {
                totalPrices = totalPrices.add(price);
            }
            totalCount += count;
        }
        OrderSettlementRespVO settlementRespVO = new OrderSettlementRespVO();
        settlementRespVO.setItems(goodRespList);
        settlementRespVO.setTotalCount(totalCount);
        if (PayChannelEnum.COIN.getCode().equalsIgnoreCase(orderSettlementReq.getChannelCode())) {
            settlementRespVO.setTotalPrice(totalPrices);
        } else {
            CoinToAmountRespDTO coinToAmountRespDTO = accountServiceApi.convertCoinToAmount(String.valueOf(totalPrices));
            settlementRespVO.setTotalPrice(new BigDecimal(coinToAmountRespDTO.getAmount()));
        }
        log.info("订单结算完成，用户使用[{}]支付的总价格: {}, 总数量: {}", orderSettlementReq.getChannelCode(), totalPrices, totalCount);
        return settlementRespVO;
    }

    @Transactional(rollbackFor = Exception.class, timeout = 120)
    @Override
    @OrderLog(operateType = OperateTypeEnum.CREATE, content = "用户创建订单")
    public String createOrder(OrderReq order) throws CommonException {
        log.info("开始创建新订单，收货人: {}, 商品数量: {}", order.getConsignee(), order.getGoods().size());
        // 校验收获地址是否存在
        checkAddress(order);

        OrderEntity orderEntity = new OrderEntity();
        int userId = getUserId();
        log.debug("当前用户ID: {}", userId);
        // 1: 生成订单号
        String orderSn = OrderIdGenerator.generateOrderId(OrderIdGenerator.MALL_ORDER_PREFIX);
        log.debug("生成订单号: {}", orderSn);
        orderEntity.setOrderSn(orderSn);
        orderEntity.setUserId(userId);
        // 2: 获取商品规格ID列表
        Map<Integer, Integer> skuCountMapping = order.getGoods().stream().collect(Collectors.toMap(OrderGoodReq::getSkuId, OrderGoodReq::getNumber, (old, newItem) -> newItem));
        Set<Integer> skuIdList = getSkuIdList(order, skuCountMapping);
        log.info("用户[{}]查询商品规格ID列表: {}", userId, skuIdList);
        // 3: 查询sku
        List<GoodsSpecificationEntity> skuList = goodsSpecificationService.listByIds(skuIdList);
        if (CollectionUtils.isEmpty(skuList)) {
            log.warn("未找到的商品规格ID");
            throw new CommonException(ResultCodeEnum.GOOD_NOT_FOUND);
        }
        Set<Integer> goodsIdList = skuList.stream().map(GoodsSpecificationEntity::getGoodsId).collect(Collectors.toSet());
        List<GoodsEntity> goodsEntities = goodsService.listByIds(goodsIdList);
        Map<Integer, GoodsEntity> goodsEntityMap = goodsEntities.stream().collect(Collectors.toMap(GoodsEntity::getId, Function.identity(), (v1, v2) -> v1));
        // 4: 设置基本信息和状态
        CoinConfigRespDTO coinConfig = accountServiceApi.getActiveAndLatestCoinConfig();
        buildOrder(order, orderEntity, skuList, skuCountMapping, goodsEntityMap,coinConfig);

        // 5: 保存订单
        boolean saveResult = orderService.save(orderEntity);
        Integer orderId = orderEntity.getId();
        log.info("订单保存结果：{},订单Id[{}]", saveResult ? "成功" : "失败", orderId);

        if (!saveResult) {
            log.error("订单保存失败，订单号: {}", orderSn);
            throw new CommonException(ResultCodeEnum.ORDER_SAVE_ERROR);
        }
        // 6: 保存子订单
        Collection<OrderChildEntity> childrenOrders = saveChildOrder(skuList, orderEntity, coinConfig,skuCountMapping);

        // 7: 构建订单子项
        List<OrderGoodsEntity> orderItems = buildOrderItems(skuList, goodsEntityMap, skuCountMapping, orderId, childrenOrders, coinConfig);

        // 8: 保存订单子项
        boolean result = orderGoodsService.saveBatch(orderItems);
        log.info("订单商品保存结果：{}", result ? "成功" : "失败");

        if (!result) {
            log.error("订单商品保存失败，订单号: {}", orderSn);
            throw new CommonException(ResultCodeEnum.ORDER_SAVE_ERROR);
        }

        // 9:订单创建后的逻辑
        log.debug("开始执行订单创建后的处理逻辑");
        orderHandlers.forEach(handler -> {
            try {
                handler.afterOrderCreate(orderEntity, orderItems, goodsEntityMap);
                log.debug("订单处理器 {} 执行完成", handler.getClass().getSimpleName());
            } catch (Exception e) {
                log.error("订单处理器 {} 执行异常", handler.getClass().getSimpleName(), e);
            }
        });

        // 10: 清空购物车
        clearCart(order);

        // 11: 保存日志
        OrderLogUtils.setCreateOrderInfo(childrenOrders);
        log.info("订单创建完成，订单号: {}", orderSn);
        return orderSn;
    }

    private void checkAddress(OrderReq order) {
        // 如果是经销商，则不检查收货地址
        if(StringUtils.hasText(order.getTenantId()) && TenantEnum.DEALER.getCode().equalsIgnoreCase(order.getTenantId())){
            return;
        }
        Optional<AddressResp> addressByIdIfDefault = addressService.getAddressByIdIfDefault(order.getAddressId());
        if (!addressByIdIfDefault.isPresent()) {
            log.warn("未找到收货地址");
            throw new CommonException(ResultCodeEnum.NO_TRACKING_SHIPPING_ADDRESS);
        }
    }

    private Collection<OrderChildEntity> saveChildOrder(List<GoodsSpecificationEntity> skuList, OrderEntity orderEntity, CoinConfigRespDTO coinConfig,Map<Integer, Integer> skuCountMapping) {
        Map<Long, List<GoodsSpecificationEntity>> merchantUserList = skuList.stream()
                .filter(goods -> Objects.nonNull(goods.getMerchantUserId()))
                .collect(Collectors.groupingBy(GoodsSpecificationEntity::getMerchantUserId, Collectors.toList()));
        log.info("开始保存子订单");
        if (CollectionUtil.isEmpty(merchantUserList)) {
            log.info("没有子订单");
            return Collections.emptyList();
        }
        Collection<OrderChildEntity> childOrders = new ArrayList<>();
        merchantUserList.forEach((merchantUserId, goodsList) -> {
            BigDecimal totalCoin = goodsList.stream()
                    .map(goods -> goods.getPrice().multiply(BigDecimal.valueOf(skuCountMapping.getOrDefault(goods.getId(), 1))))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal cnyPrice = getGoodsCnyPrice(totalCoin, coinConfig);
            OrderChildEntity childOrder = new OrderChildEntity();
            childOrder.setParentOrderId(orderEntity.getId());
            childOrder.setChildOrderSn(OrderIdGenerator.generateOrderId(OrderIdGenerator.MALL_CHILD_ORDER_PREFIX));
            childOrder.setUserId(orderEntity.getUserId());
            childOrder.setAddressId(orderEntity.getAddressId());
            childOrder.setAddTime(LocalDateTime.now());
            childOrder.setGoodsPrice(cnyPrice);
            childOrder.setActualPrice(cnyPrice);
            childOrder.setOrderPrice(cnyPrice);
            childOrder.setOrderTotalCoin(totalCoin);
            childOrder.setMerchantUserId(merchantUserId);
            childOrder.setPayStatus(PayStatusEnum.PENDING.getCode());
            childOrder.setOrderStatus(OrderStatusEnum.PENDING_PAYMENT.getCode());
            childOrder.setWeight(getChildOrderWeight(goodsList));
            childOrder.setVolume(getChildOrderVolume(goodsList));
            childOrders.add(childOrder);
        });
        boolean saveBatch = orderChildService.saveBatch(childOrders);
        log.info("子订单保存结果：{}", saveBatch ? "成功" : "失败");
        return childOrders;
    }

    private String getChildOrderWeight(List<GoodsSpecificationEntity> goodsList) {
        if (CollectionUtil.isNotEmpty(goodsList)) {
            return goodsList.stream().filter(item -> StringUtils.hasText(item.getWeight()))
                    .map(item -> new BigDecimal(item.getWeight()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add).toPlainString();
        }
        return null;
    }

    private String getChildOrderVolume(List<GoodsSpecificationEntity> goodsList) {
        if (CollectionUtil.isNotEmpty(goodsList)) {
            return goodsList.stream().filter(item -> StringUtils.hasText(item.getVolume()))
                    .map(item -> new BigDecimal(item.getVolume()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add).toPlainString();
        }
        return null;
    }

    private List<OrderGoodsEntity> buildOrderItems(List<GoodsSpecificationEntity> skuList, Map<Integer, GoodsEntity> goodsEntityMap, Map<Integer, Integer> specMap, Integer orderId, Collection<OrderChildEntity> childrenOrders, CoinConfigRespDTO coinConfig) {
        log.debug("开始构建订单商品项");
        Map<Long, Integer> merchantUserAndChildIdMapping = new HashMap<>();
        if (CollectionUtil.isNotEmpty(childrenOrders)) {
            merchantUserAndChildIdMapping.putAll(childrenOrders.stream().collect(Collectors.toMap(OrderChildEntity::getMerchantUserId, OrderChildEntity::getId)));
        }
        List<OrderGoodsEntity> orderGoodsEntities = new ArrayList<>();
        for (GoodsSpecificationEntity spec : skuList) {
            GoodsEntity goods = goodsEntityMap.get(spec.getGoodsId());
            if (Objects.isNull(goods)) {
                log.warn("未找到商品信息，商品规格ID: {}", spec.getId());
                continue;
            }
            int number = specMap.getOrDefault(spec.getId(), 1);
            OrderGoodsEntity orderItem = new OrderGoodsEntity();
            orderItem.setOrderId(orderId);
            if (CollectionUtil.isNotEmpty(merchantUserAndChildIdMapping)) {
                orderItem.setChildOrderId(merchantUserAndChildIdMapping.get(spec.getMerchantUserId()));
            }
            orderItem.setGoodsId(spec.getGoodsId());
            orderItem.setNumber(number);
            orderItem.setSkuId(spec.getId());
            orderItem.setCoin(spec.getPrice());
            orderItem.setPrice(getGoodsCnyPrice(spec.getPrice(), coinConfig));
            orderItem.setAttributes(getAttributes(spec.getAttributes()));
            orderItem.setGoodsName(goods.getName());
            if (StringUtils.hasText(spec.getPicUrl())) {
                orderItem.setPicUrl(spec.getPicUrl());
            } else {
                orderItem.setPicUrl(goods.getPrimaryPicUrl());
            }
            orderItem.setCommentStatus(CommentStatusEnum.NON_COMMENTED.getCode());
            orderItem.setTenantId(goods.getTenantId());
            orderGoodsEntities.add(orderItem);
            log.debug("构建订单商品项完成，商品ID: {}, 数量: {}", spec.getGoodsId(), number);
        }
        log.info("订单商品项构建完成，共 {} 项", orderGoodsEntities.size());
        return orderGoodsEntities;
    }

    private BigDecimal getGoodsCnyPrice(BigDecimal amount,CoinConfigRespDTO coinConfig) {
        if (Objects.nonNull(amount)) {
            return MoneyUtil.yuanToCentWithBigDecimal(MoneyUtil.convertCoinToAmount(amount, coinConfig.getExchangeRatio()));
        }
        return BigDecimal.ZERO;
    }

    private Set<Integer> getSkuIdList(OrderReq order, Map<Integer, Integer> specMap) {
        log.debug("开始提取SKU ID列表");
        Set<Integer> skuIdList = new HashSet<>();
        List<Integer> cartIdList = new ArrayList<>();

        for (OrderGoodReq item : order.getGoods()) {
            if (Objects.nonNull(item.getCartId())) {
                cartIdList.add(item.getCartId());
            }
            if (Objects.nonNull(item.getSkuId())) {
                skuIdList.add(item.getSkuId());
            }
        }
        log.debug("从订单中提取到直接SKU ID: {}，购物车ID: {}", skuIdList, cartIdList);
        if (CollectionUtil.isNotEmpty(cartIdList)) {
            List<CartEntity> cartEntityList = cartService.listByIds(cartIdList);
            if (CollectionUtil.isNotEmpty(cartEntityList)) {
                for (CartEntity cat : cartEntityList) {
                    skuIdList.add(cat.getSkuId());
                    specMap.put(cat.getSkuId(), cat.getNumber());
                }
            }
        }
        log.debug("最终SKU ID列表: {}", skuIdList);
        return skuIdList;
    }

    private void clearCart(OrderReq order) {
        log.debug("开始清理购物车");
        Set<Integer> cartIdList = new HashSet<>();
        for (OrderGoodReq good : order.getGoods()) {
            if (Objects.nonNull(good.getCartId())) {
                cartIdList.add(good.getCartId());
            }
        }
        if (CollectionUtil.isNotEmpty(cartIdList)) {
            boolean removeBatchResult = cartService.removeBatchByIds(cartIdList);
            log.info("删除购物车结果:{}, 删除的购物车ID: {}", removeBatchResult, cartIdList);
        }
    }

    private static void buildOrder(OrderReq order, OrderEntity orderEntity, List<GoodsSpecificationEntity> skuList, Map<Integer, Integer> specMap, Map<Integer, GoodsEntity> goodsEntityMap,CoinConfigRespDTO coinConfig) {
        log.debug("开始构建订单基本信息");
        orderEntity.setAddressId(order.getAddressId());
        orderEntity.setConsignee(order.getConsignee());
        orderEntity.setMobile(order.getMobile());
        orderEntity.setProvince(order.getProvince());
        orderEntity.setCity(order.getCity());
        orderEntity.setDistrict(order.getDistrict());
        orderEntity.setAddress(order.getAddress());
        orderEntity.setAddTime(LocalDateTime.now());
        orderEntity.setOrderStatus(OrderStatusEnum.PENDING_PAYMENT.getCode());
        orderEntity.setShippingStatus(ShippingStatusEnum.NOT_SHIPPED.getCode());
        orderEntity.setPayStatus(PayStatusEnum.PENDING.getCode());
        orderEntity.setCommentStatus(CommentStatusEnum.NON_COMMENTED.getCode());
        orderEntity.setPostscript(order.getPostscript());
        BigDecimal goodsTotalPrice = BigDecimal.ZERO;
        for (GoodsSpecificationEntity spec : skuList) {
            GoodsEntity goods = goodsEntityMap.get(spec.getGoodsId());
            if (Objects.isNull(goods)) {
                continue;
            }
            if (PaymentModeEnum.OFFLINE.getCode().intValue() == goods.getPaymentMode().intValue()) {
                log.info("商品[{}]：{} 线下支付，不参与订单结算", goods.getId(), goods.getName());
                continue;
            }
            int number = specMap.getOrDefault(spec.getId(), 1);
            BigDecimal itemTotal = spec.getPrice().multiply(BigDecimal.valueOf(number));
            goodsTotalPrice = goodsTotalPrice.add(itemTotal);
        }
        BigDecimal orderTotalCoin = goodsTotalPrice;
        orderEntity.setOrderTotalCoin(orderTotalCoin);
        BigDecimal price = MoneyUtil.yuanToCentWithBigDecimal(MoneyUtil.convertCoinToAmount(goodsTotalPrice, coinConfig.getExchangeRatio()));
        orderEntity.setGoodsPrice(price);
        orderEntity.setActualPrice(price);
        orderEntity.setOrderPrice(price);
        orderEntity.setCoinConfigId(coinConfig.getConfigId());
        orderEntity.setExchangeRatio(coinConfig.getExchangeRatio());

        log.debug("订单总金额: {}", goodsTotalPrice);
        GoodsEntity goodsEntity = goodsEntityMap.values().stream().findFirst().orElse(null);
        if (Objects.nonNull(goodsEntity)) {
            orderEntity.setTenantId(goodsEntity.getTenantId());
            orderEntity.setPaymentMode(goodsEntity.getPaymentMode());
        } else {
            orderEntity.setTenantId(CommonConstant.DEFAULT_TENANT_ID);
            orderEntity.setPaymentMode(PaymentModeEnum.ONLINE.getCode());
        }
        log.info("订单基本信息构建完成，订单金额: {}, 租户ID: {}, 支付方式: {}", goodsTotalPrice, orderEntity.getTenantId(), orderEntity.getPaymentMode());
    }

    private List<GoodsSpecificationEntity.Attribute> getAttributes(List<GoodsSpecificationEntity.Attribute> attributes) {
        if (CollectionUtils.isEmpty(attributes)) {
            return Collections.emptyList();
        }
        List<GoodsSpecificationEntity.Attribute> orderAttributes = new ArrayList<>();
        for (GoodsSpecificationEntity.Attribute attribute : attributes) {
            GoodsSpecificationEntity.Attribute orderAttribute = new GoodsSpecificationEntity.Attribute();
            orderAttribute.setAttributeId(attribute.getAttributeId());
            orderAttribute.setAttributeName(attribute.getAttributeName());
            orderAttribute.setValueId(attribute.getValueId());
            orderAttribute.setValueName(attribute.getValueName());
            orderAttributes.add(orderAttribute);
        }
        return orderAttributes;
    }

    @Transactional(rollbackFor = Exception.class, timeout = 120)
    @Override
    @OrderLog(operateType = OperateTypeEnum.UPDATE, content = "用户更新订单")
    public boolean updateOrder(OrderReq orderReq) {
        log.info("开始更新订单，订单ID: {}", orderReq.getId());

        OrderEntity queryOrder = orderService.checkOrderByOrderId(orderReq.getId());

        // 检查订单是否可以修改（例如：仅允许"待付款"状态和"待发货"状态的订单）
        if (OrderStatusEnum.PENDING_PAYMENT.getCode() != queryOrder.getOrderStatus() && OrderStatusEnum.PAID.getCode() != queryOrder.getOrderStatus()) {
            log.warn("订单状态不允许修改，当前状态: {}", queryOrder.getOrderStatus());
            throw new CommonException(ResultCodeEnum.ORDER_NON_UPDATE);
        }
        OrderEntity order = new OrderEntity();
        order.setId(orderReq.getId());
        order.setConsignee(orderReq.getConsignee());
        order.setProvince(orderReq.getProvince());
        order.setMobile(orderReq.getMobile());
        order.setAddress(orderReq.getAddress());
        order.setPostscript(orderReq.getPostscript());
        order.setDistrict(orderReq.getDistrict());
        order.setCity(orderReq.getCity());
        order.setAddressId(orderReq.getAddressId());
        log.debug("更新订单字段内容: {}", order);

        if (Objects.nonNull(orderReq.getChildOrderId())) {
            boolean childUpdateResult = orderChildService.updateAddressIdByChildOrderId(orderReq.getChildOrderId(), orderReq.getAddressId());
            log.info("更新子订单地址结果:{}", childUpdateResult);
        }

        boolean result = orderService.updateById(order);
        log.info("订单更新结果：{}", result ? "成功" : "失败");
        int userId = getUserId();
        OrderLogUtils.setUserInfo(userId, UserTypeEnum.PARENT);
        OrderLogUtils.setUpdateOrderInfo(orderReq.getId(), orderReq.getChildOrderId(), userId);
        return result;
    }

    @Transactional(rollbackFor = Exception.class, timeout = 120)
    @Override
    @OrderLog(operateType = OperateTypeEnum.UPDATE, content = "用户取消订单")
    public boolean cancelOrder(String orderSn) {
        Integer userId = getUserId();
        log.info("用户[{}]开始取消订单，订单sn: {}", userId, orderSn);

        OrderEntity queryOrder = orderService.checkOrderBySn(orderSn);

        checkOrder(queryOrder);

        // 1. 检查订单是否可以修改（仅允许"待付款"状态和"待发货"状态的订单）
        if (OrderStatusEnum.PENDING_PAYMENT.getCode() != queryOrder.getOrderStatus() && OrderStatusEnum.PAID.getCode() != queryOrder.getOrderStatus()) {
            log.warn("订单状态不允许取消，当前状态: {}", queryOrder.getOrderStatus());
            throw new CommonException(ResultCodeEnum.ORDER_NON_UPDATE);
        }

        // 2. 查询所有的子订单
        List<OrderChildEntity> orderChildren = orderChildService.getListByParentId(queryOrder.getId());
        log.debug("订单子订单列表数量: {}", orderChildren.size());

        // 3. 取消子订单
        Set<Integer> childrenOrderIds = orderChildren.stream().map(OrderChildEntity::getId).collect(Collectors.toSet());
        boolean cancelChildOrderResult = orderChildService.cancelOrder(childrenOrderIds, userId);
        if (!cancelChildOrderResult) {
            log.error("子订单取消失败，订单sn: {},子订单sn:{}", orderSn, childrenOrderIds);
            return false;
        }

        // 4. 取消父订单
        boolean cancelResult = orderService.cancelOrder(queryOrder.getId(), OrderStatusEnum.CANCELED, userId);
        log.info("用户[{}]父订单取消结果：{}", userId, cancelResult ? "成功" : "失败");

        if (!cancelResult) {
            return false;
        }

        // 5. 执行订单取消后的后置处理
        List<OrderGoodsEntity> items = orderGoodsService.listByOrderId(queryOrder.getId());
        log.debug("开始执行订单取消后的处理逻辑");
        orderHandlers.forEach(orderHandler -> {
            try {
                orderHandler.afterOrderCancel(queryOrder, items);
                log.debug("订单取消处理器 {} 执行完成", orderHandler.getClass().getSimpleName());
            } catch (Exception e) {
                log.error("订单取消处理器 {} 执行异常", orderHandler.getClass().getSimpleName(), e);
            }
        });

        // 6. 记录订单日志
        OrderLogUtils.setCancelChildOrderInfo(orderChildren);
        log.info("订单取消完成，订单号: {}", orderSn);
        return true;
    }

    @Override
    public boolean cancelChildOrder(String childOrderSn) {
        Integer userId = getUserId();
        log.info("用户[{}]开始取消子订单，子订单SN：{}", userId, childOrderSn);

        // 1. 检查订单是否可以修改（仅允许"待付款"状态和"待发货"状态的订单）
        OrderChildEntity queryChildOrder = orderChildService.checkOrderChildByChildOrderSn(childOrderSn);
        if (OrderStatusEnum.PENDING_PAYMENT.getCode() != queryChildOrder.getOrderStatus() && OrderStatusEnum.PAID.getCode() != queryChildOrder.getOrderStatus()) {
            log.warn("子订单状态不允许取消，当前状态: {}", queryChildOrder.getOrderStatus());
            throw new CommonException(ResultCodeEnum.ORDER_NON_UPDATE);
        }
        // 1.1 校验父订单是否存在
        OrderEntity parentOrder = orderService.checkOrderByOrderId(queryChildOrder.getParentOrderId());

        // 2. 更新子订单状态
        boolean cancelChildOrderResult = orderChildService.cancelOrder(queryChildOrder.getId(), userId);
        log.info("用户[{}]子订单取消结果：{}", userId, cancelChildOrderResult ? "成功" : "失败");

        if (!cancelChildOrderResult) {
            log.error("子订单取消失败，子订单sn:{}", childOrderSn);
            return false;
        }

        // 3, 取消父订单
        List<OrderChildEntity> orderChildren = orderChildService.getListByParentId(queryChildOrder.getId());
        OrderStatusEnum orderStatusEnum = null;
        Optional<OrderChildEntity> any = orderChildren.stream().filter(
                        childOrder -> !childOrder.getChildOrderSn().equals(childOrderSn) && OrderStatusEnum.CANCELED.getCode() != childOrder.getOrderStatus()).
                findAny();
        if (any.isPresent()) {
            orderStatusEnum = OrderStatusEnum.PART_CANCELED;
        } else {
            orderStatusEnum = OrderStatusEnum.CANCELED;
        }
        boolean cancelResult = orderService.cancelOrder(queryChildOrder.getParentOrderId(), orderStatusEnum, userId);
        log.info("用户[{}]的父订单取消结果：{}", userId, cancelResult ? "成功" : "失败");

        // 4. 执行订单取消后的后置处理
        List<OrderGoodsEntity> items = orderGoodsService.listByChildOrderId(queryChildOrder.getId());
        orderHandlers.forEach(orderHandler -> {
            try {
                orderHandler.afterOrderCancel(parentOrder,queryChildOrder, items);
                log.debug("订单取消处理器子订单取消后事件 {} 执行完成", orderHandler.getClass().getSimpleName());
            } catch (Exception e) {
                log.error("订单取消处理器子订单取消后事件 {} 执行异常", orderHandler.getClass().getSimpleName(), e);
            }
        });

        // 4. 记录订单日志
        OrderLogUtils.setCancelChildOrderInfo(queryChildOrder);
        log.info("子订单取消完成，子订单SN: {}", childOrderSn);
        return true;
    }

    @OrderLog(operateType = OperateTypeEnum.DELETE, content = "用户删除订单")
    @Transactional(rollbackFor = Exception.class, timeout = 120)
    @Override
    public boolean deleteOrder(OrderUpdateReq orderUpdateReq) {
        Integer orderId = orderUpdateReq.getOrderId();
        int userId = getUserId();
        log.info("用户[{}]开始删除订单，订单ID: {},子订单ID：{}", userId, orderId, orderUpdateReq.getChildOrderId());
        OrderEntity queryOrder = orderService.checkOrderByOrderId(orderId);
        checkOrder(queryOrder);
        List<OrderChildEntity> allChildOrders = orderChildService.getListByParentId(orderId);
        Integer childOrderId = orderUpdateReq.getChildOrderId();
        if (Objects.nonNull(childOrderId)) {
            OrderChildEntity orderChildEntity = orderChildService.checkOrderChild(childOrderId);
            if (!orderChildEntity.getParentOrderId().equals(orderId)) {
                log.warn("子订单不属于该订单");
                throw new CommonException(ResultCodeEnum.ORDER_NOT_BELONG);
            }
            if ( OrderStatusEnum.CANCELED.getCode() != orderChildEntity.getOrderStatus()){
                throw new CommonException(ResultCodeEnum.ORDER_NON_DELETE);
            }
            boolean removeGoodItemResult = orderGoodsService.deleteOrderGoodsByOrderChildId(childOrderId);
            log.info("用户[{}]订单商品删除结果：{}", userId, removeGoodItemResult);
            boolean childRemoveResult = orderChildService.deleteOrderByIdAndMerchantId(childOrderId, orderChildEntity.getMerchantUserId());
            if (!childRemoveResult) {
                log.warn("子订单删除失败，订单ID: {},子订单ID：{}", orderId, childOrderId);
                throw new CommonException(ResultCodeEnum.ORDER_NON_DELETE);
            }
            log.info("用户[{}]子订单删除结果：{}", userId, "成功");
            Set<Integer> otherChildOrderId = allChildOrders.stream()
                    .filter(item -> item.getOrderStatus() != OrderStatusEnum.DELETED.getCode() && !Objects.equals(item.getId(), childOrderId))
                    .map(OrderChildEntity::getId).collect(Collectors.toSet());
            if (CollectionUtil.isEmpty(otherChildOrderId)) {
                boolean removeResult = orderService.deleteOrder(queryOrder.getId(), userId);
                log.info("用户[{}]父订单删除结果：{}", userId, removeResult ? "成功" : "失败");
            } else {
                log.info("用户[{}]父订单[{}]中还有其他订单，不能删除父订单，其他订单ID ：{}", userId, orderId, JSONUtil.toJsonStr(otherChildOrderId));
            }
            //添加订单日志
            OrderLogUtils.setDeleteOrderInfo(Collections.singletonList(orderChildEntity));
            log.info("订单删除完成，订单ID: {},子订单Id:{}", orderId, childOrderId);
            return true;
        } else {
            orderGoodsService.deleteOrderGoodsByOrderId(orderId);
            boolean removeOrderGoodResult = orderService.deleteOrder(orderId, userId);
            log.info("订单商品删除结果：{}", removeOrderGoodResult ? "成功" : "失败");
            boolean removeOrderChildrenResult = orderChildService.deleteOrderByParentOrderId(orderId);
            log.info("子订单删除结果：{}", removeOrderChildrenResult ? "成功" : "失败");
            boolean result = orderService.deleteOrder(orderId, userId);
            log.info("订单删除结果：{}", result ? "成功" : "失败");
            //添加订单日志
            OrderLogUtils.setDeleteOrderInfo(allChildOrders);
            log.info("订单删除完成，订单ID: {}", orderId);
            return result;
        }
    }

    @OrderLog(operateType = OperateTypeEnum.UPDATE, content = "用户确认收货")
    @Override
    public boolean receiveOrder(OrderUpdateReq orderUpdateReq) {
        Integer orderId = orderUpdateReq.getOrderId();
        Integer userId = getUserId();
        log.info("用户[{}]开始确认收货，订单Id: {},子订单ID:{}", userId, orderId, orderUpdateReq.getChildOrderId());

        OrderChildEntity childOrder = orderChildService.checkOrderChild(orderUpdateReq.getChildOrderId());
        log.debug("用户[{}]查询结果: {}", userId, childOrder);

        AssertUtils.isTrue(childOrder.getOrderStatus() == OrderStatusEnum.SHIPPED.getCode(), ResultCodeEnum.ORDER_NOT_SHIPPED);
        AssertUtils.isTrue(childOrder.getParentOrderId().intValue() == orderUpdateReq.getOrderId(), ResultCodeEnum.ORDER_NOT_FOUND);

        boolean confirmResult = orderService.receiveOrder(orderUpdateReq.getOrderId(), childOrder.getChildOrderSn(), userId);
        log.info("用户[{}]订单确认收货结果：{}", userId, confirmResult ? "成功" : "失败");
        //添加订单日志
        OrderLogUtils.setUserInfo(userId, UserTypeEnum.PARENT);
        OrderLogUtils.setReceiveOrderInfo(orderUpdateReq.getOrderId(), orderUpdateReq.getChildOrderId(), userId);
        log.info("订单确认收货完成，订单Id: {}", orderId);
        return confirmResult;
    }

    @Override
    public List<OrderEntity> getUnpaidOrders() {
        return orderService.list(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getOrderStatus, OrderStatusEnum.PENDING_PAYMENT.getCode()));
    }

    @OrderLog(operateType = OperateTypeEnum.DELETE, content = "系统自动取消订单")
    @Override
    @Transactional(rollbackFor = Exception.class, timeout = 120)
    public void expireOrder(OrderEntity orderEntity) {
        log.info("系统开始自动取消订单，订单ID: {}", orderEntity.getId());
        // 1. 更新订单状态为已过期
        OrderEntity order = new OrderEntity();
        order.setId(orderEntity.getId());
        order.setOrderStatus(OrderStatusEnum.CANCELED.getCode());
        order.setPayStatus(PayStatusEnum.CANCEL.getCode());
        order.setUpdateTime(LocalDateTime.now());
        boolean updated = orderService.updateById(order);
        log.info("订单状态更新结果：{}", updated ? "成功" : "失败");

        if (!updated) {
            log.error("订单状态更新失败，订单ID: {}", orderEntity.getId());
            return;
        }

        // 2. 执行订单取消后的后置处理
        List<OrderGoodsEntity> items = orderGoodsService.list(new LambdaQueryWrapper<>(OrderGoodsEntity.class).eq(OrderGoodsEntity::getOrderId, orderEntity.getId()));
        log.debug("开始执行订单过期后的处理逻辑");
        orderHandlers.forEach(orderHandler -> {
            try {
                orderHandler.afterOrderCancel(orderEntity, items);
                log.debug("订单过期处理器 {} 执行完成", orderHandler.getClass().getSimpleName());
            } catch (Exception e) {
                log.error("订单过期处理器 {} 执行异常", orderHandler.getClass().getSimpleName(), e);
            }
        });

        // 3. 添加订单日志
        OrderLogUtils.setUserInfo(0, UserTypeEnum.SYSTEM);
        OrderLogUtils.setExpireOrderInfo(orderEntity.getId(), null);
        log.info("订单自动取消完成，订单ID: {}", orderEntity.getId());
    }

    @Override
    public List<OrderEntity> getOverdueOrders(int autoConfirmReceiveDays) {
        return orderService.list(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getOrderStatus, OrderStatusEnum.SHIPPED.getCode())
                .lt(OrderEntity::getDeliveryTime, LocalDateTime.now().minusDays(autoConfirmReceiveDays)));
    }

    @Override
    public boolean deliveryOrder(OrderUpdateReq orderUpdateReq) {
        Integer userId = getUserId();
        Integer orderId = orderUpdateReq.getOrderId();
        log.info("仓管[{}]订单发货开始,订单ID{}", userId, orderId);
        OrderEntity order = orderService.getById(orderId);
        AssertUtils.notNull(order, ResultCodeEnum.ORDER_NOT_FOUND);
        log.info("订单信息：{}", order);
        AssertUtils.isTrue(order.getOrderStatus() == OrderStatusEnum.CONFIRMED.getCode(), ResultCodeEnum.ORDER_NOT_WAIT_SHIP);

        List<OrderGoodsEntity> goodsEntities = orderGoodsService.list(new LambdaQueryWrapper<OrderGoodsEntity>()
                .eq(OrderGoodsEntity::getOrderId, orderId));
        AssertUtils.notEmpty(goodsEntities, ResultCodeEnum.GOOD_NOT_FOUND);

        // 更新订单的状态
        boolean updateOrderStatusResult = orderService.update(new LambdaUpdateWrapper<OrderEntity>()
                .eq(OrderEntity::getId, orderId)
                .set(OrderEntity::getOrderStatus, OrderStatusEnum.WAREHOUSE_SHIPPED.getCode())
                .set(OrderEntity::getShippingStatus, ShippingStatusEnum.SHIPPED.getCode())
                .set(OrderEntity::getDeliveryTime, LocalDateTime.now()));

        log.info("更新订单状态结果: {}", updateOrderStatusResult);

        // 设置订单日志信息
        OrderLogUtils.setDeliveryOrderInfo(orderId, getUserId(), orderUpdateReq.getChildOrderId(), ShippingStatusEnum.SHIPPED, CommentStatusEnum.NON_COMMENTED);
        log.info("订单发货完成，订单ID: {}", orderId);
        return updateOrderStatusResult;
    }

    private void checkOrder(OrderEntity queryOrder) {
        int userId = getUserId();
        if (userId != queryOrder.getUserId()) {
            throw new CommonException(ResultCodeEnum.ORDER_UPDATE_UNAUTHORIZED);
        }
    }

    private int getUserId() {
        return StpUtil.getLoginIdAsInt();
    }

}