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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.AfterSaleStatusEnum;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mall.convert.OrderConverter;
import com.seer.teach.mall.convert.OrderGoodsConverter;
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.entity.TradeAfterSaleEntity;
import com.seer.teach.mall.mapper.OrderMapper;
import com.seer.teach.mall.mapper.TradeAfterSaleMapper;
import com.seer.teach.mall.request.OrderPageListReq;
import com.seer.teach.mall.response.OrderChildResp;
import com.seer.teach.mall.response.OrderItemResp;
import com.seer.teach.mall.response.OrderResp;
import com.seer.teach.mall.service.IOrderChildService;
import com.seer.teach.mall.service.IOrderGoodsService;
import com.seer.teach.mall.service.IOrderQueryService;
import com.seer.teach.user.api.UserInfoServiceApi;
import com.seer.teach.user.api.dto.UserInfoDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Slf4j
@Service
public class OrderQueryServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements IOrderQueryService {

    private final IOrderGoodsService orderGoodsService;

    private final TradeAfterSaleMapper tradeAfterSaleMapper;

    private final UserInfoServiceApi userInfoServiceApi;

    private final IOrderChildService orderChildService;

    @Override
    public OrderResp getOrderByOrderId(Integer orderId) {
        // 查询订单主信息
        OrderEntity orderEntity = getOrderMainInfo(orderId);

        OrderResp orderResp = OrderConverter.INSTANCE.one(orderEntity);

        if (orderResp != null) {
            // 获取订单商品信息
            List<OrderGoodsEntity> orderItems = orderGoodsService.listByOrderId(orderId);

            // 构建子订单商品映射
            Map<Integer, List<OrderItemResp>> childGoodsMapping = buildChildGoodsMapping(orderItems);

            // 构建子订单信息
            buildChildOrders(orderResp, childGoodsMapping);
        }
        return orderResp;
    }

    @Override
    public OrderResp getOrderDetail(Integer orderId) {
        log.info("开始查询订单详情，订单ID: {}", orderId);

        // 查询订单主信息
        OrderEntity orderEntity = getOrderMainInfo(orderId);

        // 转换为主订单响应对象
        OrderResp orderResp = OrderConverter.INSTANCE.one(orderEntity);

        // 获取订单商品信息
        List<OrderGoodsEntity> orderItems = orderGoodsService.listByOrderId(orderId);

        log.debug("订单[{}]关联的商品数量为: {}", orderId, orderItems.size());

        // 构建子订单商品映射
        Map<Integer, List<OrderItemResp>> childGoodsMapping = buildChildGoodsMapping(orderItems);

        // 构建子订单信息
        buildChildOrdersWithUserInfo(orderResp, childGoodsMapping);

        log.info("成功返回订单详情，订单ID: {}", orderId);
        return orderResp;
    }

    @Override
    public OrderResp myOrderChildDetail(Integer childOrderId) {
        OrderChildEntity orderChildEntity = orderChildService.getById(childOrderId);

        AssertUtils.notNull(orderChildEntity, ResultCodeEnum.ORDER_NOT_FOUND);
        // 查询订单主信息
        OrderEntity orderEntity = getOrderMainInfo(orderChildEntity.getParentOrderId());
        OrderResp orderResp = OrderConverter.INSTANCE.one(orderEntity);
        // 转换为主订单响应对象
        OrderChildResp orderChildResp = OrderConverter.INSTANCE.convertOrderChild2Resp(orderChildEntity);


        // 获取订单商品信息
        List<OrderGoodsEntity> orderItems = orderGoodsService.listByChildOrderId(childOrderId);

        // 构建子订单商品映射
        Map<Integer, List<OrderItemResp>> childGoodsMapping = buildChildGoodsMapping(orderItems);

        // 构建子订单信息
        buildChildOrderWithUserInfo(orderResp,orderChildResp, childGoodsMapping);

        return orderResp;
    }


    @Override
    public OrderChildResp getOrderChildDetail(Integer childOrderId) {
        OrderChildEntity orderChildEntity = orderChildService.getById(childOrderId);

        AssertUtils.notNull(orderChildEntity, ResultCodeEnum.ORDER_NOT_FOUND);
        OrderChildResp orderChildResp = OrderConverter.INSTANCE.convertOrderChild2Resp(orderChildEntity);
        // 获取订单商品信息
        List<OrderGoodsEntity> orderItems = orderGoodsService.list(new LambdaQueryWrapper<>(OrderGoodsEntity.class)
                .eq(OrderGoodsEntity::getChildOrderId, childOrderId));

        // 构建子订单商品映射
        orderChildResp.setOrderItems(OrderGoodsConverter.INSTANCE.list(orderItems));
        // 构建子订单信息
        buildChildOrderWithUserInfo(orderChildResp);

        return orderChildResp;
    }

    @Override
    public PageListBean<OrderResp> getOrderPage(OrderPageListReq params, Integer userId, Integer deliveryUserId) {
        log.info("用户[{}]查询订单列表，分页参数：size={}, current={}, orderStatus={}", userId, params.getLimits(), params.getPage(), params.getOrderStatus());

        // 构建分页查询条件
        IPage<OrderEntity> pageParams = new Page<>(params.getPage(), params.getLimits());
        IPage<OrderEntity> orderPage = super.page(pageParams, buildOrderPageQueryWrapper(params, userId, deliveryUserId));

        List<OrderEntity> records = orderPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            log.warn("用户[{}]未找到订单数据", userId);
            return new PageListBean<>();
        }

        // 转换为订单响应列表
        PageListBean<OrderResp> orderRespPage = PageConverterUtils.convertPageListBean(orderPage, OrderConverter.INSTANCE::list);

        Set<Integer> orderIds = orderRespPage.getList().stream()
                .map(OrderResp::getId)
                .collect(Collectors.toSet());

        // 获取订单商品信息
        List<OrderGoodsEntity> goodsEntities = orderGoodsService.getOrderGoodsByOrderIds(orderIds);
        if (CollectionUtils.isEmpty(goodsEntities)) {
            return new PageListBean<>();
        }

        // 构建子订单商品映射
        Map<Integer, List<OrderItemResp>> childGoodsMapping = buildChildGoodsMapping(goodsEntities);

        // 构建子订单信息
        Map<Integer, List<OrderChildResp>> orderChildrenMap = buildChildOrder(orderIds, childGoodsMapping,deliveryUserId);

        // 填充每个订单的详细信息
        orderRespPage.getList().forEach(orderResp -> {
            Integer orderId = orderResp.getId();
            orderResp.setOrderChildren(orderChildrenMap.get(orderId));
        });

        log.info("用户[{}]成功返回订单列表，共{}条记录", userId, orderRespPage.getList().size());
        return orderRespPage;
    }


    @Override
    public PageListBean<OrderChildResp> getOrderChildrenPage(OrderPageListReq params) {
        log.info("查询子订单列表，分页参数：size={}, current={}", params.getLimits(), params.getPage());

        // 构建分页查询条件
        IPage<OrderChildEntity> pageParams = new Page<>(params.getPage(), params.getLimits());
        LambdaQueryWrapper<OrderChildEntity> queryWrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        queryWrapper.eq(Objects.nonNull(params.getOrderStatus()), OrderChildEntity::getOrderStatus, params.getOrderStatus())
                .likeRight(StringUtils.hasText(params.getConsignee()), OrderChildEntity::getChildOrderSn, params.getConsignee())
                .eq(StringUtils.hasText(params.getTenantId()), OrderChildEntity::getTenantId, params.getTenantId())
                .eq(Objects.nonNull(params.getMerchantUserId()), OrderChildEntity::getMerchantUserId, params.getMerchantUserId())
                .eq(Objects.nonNull(params.getUserId()), OrderChildEntity::getUserId, params.getUserId())
                .orderByDesc(OrderChildEntity::getId);

        // 执行分页查询
        IPage<OrderChildEntity> orderChildPage = orderChildService.page(pageParams, queryWrapper);

        List<OrderChildEntity> records = orderChildPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            log.warn("未找到子订单数据");
            return new PageListBean<>();
        }

        // 转换为订单响应列表
        PageListBean<OrderChildResp> orderChildRespPageList = PageConverterUtils.convertPageListBean(orderChildPage, OrderConverter.INSTANCE::convertOrderChildren);

        // 收集订单ID
        Set<Integer> orderChildrenIds = orderChildRespPageList.getList().stream().map(OrderChildResp::getId).collect(Collectors.toSet());

        // 获取订单商品信息
        List<OrderGoodsEntity> goodsEntities = orderGoodsService.getOrderGoodsByOrderChildIds(orderChildrenIds);
        if (CollectionUtils.isEmpty(goodsEntities)) {
            return new PageListBean<>();
        }

        // 构建子订单商品映射
        Map<Integer, List<OrderItemResp>> childGoodsMapping = buildChildGoodsMapping(goodsEntities);

        // 构建子订单信息
        buildChildOrder(orderChildRespPageList.getList(), childGoodsMapping);

        log.info("成功返回子订单列表，共{}条记录", orderChildRespPageList.getList().size());
        return orderChildRespPageList;
    }

    /**
     * 获取订单主信息
     *
     * @param orderId 订单ID
     * @return 订单实体
     */
    private OrderEntity getOrderMainInfo(Integer orderId) {
        LambdaQueryWrapper<OrderEntity> orderQueryWrapper = new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getId, orderId);

        OrderEntity queryOrder = super.getOne(orderQueryWrapper);

        if (Objects.isNull(queryOrder)) {
            log.warn("未找到订单，订单ID: {}", orderId);
            throw new CommonException(ResultCodeEnum.ORDER_NOT_FOUND);
        }

        log.debug("找到订单信息: {}", queryOrder);
        return queryOrder;
    }

    /**
     * 构建子订单与商品的映射关系
     *
     * @param orderItems 订单商品列表
     * @return 子订单与商品的映射
     */
    private Map<Integer, List<OrderItemResp>> buildChildGoodsMapping(List<OrderGoodsEntity> orderItems) {
        return OrderGoodsConverter.INSTANCE.list(orderItems).stream()
                .filter(item -> Objects.nonNull(item.getChildOrderId()))
                .collect(Collectors.groupingBy(OrderItemResp::getChildOrderId));
    }

    /**
     * 构建订单详情中的子订单信息
     *
     * @param orderResp         订单响应对象
     * @param childGoodsMapping 子订单与商品的映射
     */
    private void buildChildOrders(OrderResp orderResp, Map<Integer, List<OrderItemResp>> childGoodsMapping) {
        if (CollectionUtil.isEmpty(childGoodsMapping)) {
            return;
        }
        List<OrderChildEntity> orderChildren = orderChildService.getListByParentId(orderResp.getId());
        if (CollectionUtil.isEmpty(orderChildren)) {
            return;
        }
        Integer orderId = orderResp.getId();
        List<OrderChildResp> orderChildrenResp = OrderConverter.INSTANCE.convertOrderChildren(orderChildren);

        orderChildrenResp.forEach(childResp -> {
            // 设置订单商品项
            List<OrderItemResp> items = childGoodsMapping.get(childResp.getId());
            if (CollUtil.isNotEmpty(items)) {
                for (OrderItemResp item : items) {
                    item.setChildOrderId(childResp.getId());
                    item.setOrderId(orderId);
                }
                childResp.setOrderItems(items);
            }
        });
        orderResp.setOrderChildren(orderChildrenResp);
    }

    /**
     * 构建订单详情中的子订单信息
     *
     * @param orderResp         订单响应对象
     * @param childGoodsMapping 子订单与商品的映射
     */
    private void buildChildOrdersWithUserInfo(OrderResp orderResp, Map<Integer, List<OrderItemResp>> childGoodsMapping) {
        if (CollectionUtil.isEmpty(childGoodsMapping)) {
            return;
        }
        List<OrderChildEntity> orderChildren = orderChildService.getListByParentId(orderResp.getId());
        if (CollectionUtil.isEmpty(orderChildren)) {
            return;
        }
        // 获取用户信息 - 优化用户ID收集逻辑
        Set<Integer> userIds = new HashSet<>();
        userIds.add(orderResp.getUserId());
        if (Objects.nonNull(orderResp.getDeliveryUserId())) {
            userIds.add(orderResp.getDeliveryUserId());
        }

        // 更简洁的方式收集子订单相关用户ID
        orderChildren.forEach(child -> {
            userIds.add(child.getUserId());
            if (Objects.nonNull(child.getDeliveryUserId())) {
                userIds.add(child.getDeliveryUserId());
            }
        });
        Integer orderId = orderResp.getId();
        Map<Integer, UserInfoDTO> userMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(userIds)) {
            List<UserInfoDTO> users = userInfoServiceApi.getListByUserIds(userIds);
            userMap.putAll(users.stream().collect(Collectors.toMap(UserInfoDTO::getId, Function.identity(), (old, newItem) -> newItem)));
        }

        List<OrderChildResp> orderChildrenResp = OrderConverter.INSTANCE.convertOrderChildren(orderChildren);
        // 获取子订单的售后状态
        Map<Integer, Integer> childOrderAfterSaleStatusMap = getChildOrderAfterSaleStatusMap(orderId);

        orderChildrenResp.forEach(childResp -> {
            // 设置订单商品项
            List<OrderItemResp> items = childGoodsMapping.get(childResp.getId());
            if (CollUtil.isNotEmpty(items)) {
                for (OrderItemResp item : items) {
                    item.setChildOrderId(childResp.getId());
                    item.setOrderId(orderId);
                }
                childResp.setOrderItems(items);
            }

            // 设置售后状态
            childResp.setAfterSaleStatus(childOrderAfterSaleStatusMap.getOrDefault(childResp.getId(), AfterSaleStatusEnum.NON_APPLY.getStatus()));

            // 设置收货人信息
            UserInfoDTO consigneeUser = userMap.get(childResp.getUserId());
            if (consigneeUser != null) {
                childResp.setConsignee(getUserName(consigneeUser));
                childResp.setMobile(consigneeUser.getMobile());
            }

            // 设置配送人员信息
            UserInfoDTO deliveryUserInfoDTO = userMap.get(childResp.getDeliveryUserId());
            if (deliveryUserInfoDTO != null) {
                childResp.setDeliveryRealName(getUserName(deliveryUserInfoDTO));
                childResp.setDeliveryUserMobile(deliveryUserInfoDTO.getMobile());
            }
        });
        orderResp.setOrderChildren(orderChildrenResp);

        UserInfoDTO userInfoDTO = userInfoServiceApi.getById(orderResp.getUserId());
        if (Objects.nonNull(userInfoDTO)) {
            orderResp.setUnionId(userInfoDTO.getUnionId());
        }
    }

    /**
     * 构建订单详情中的子订单信息
     *
     * @param orderResp         订单响应对象
     * @param orderChildResp         订单响应对象
     * @param childGoodsMapping 子订单与商品的映射
     */
    private void buildChildOrderWithUserInfo(OrderResp orderResp,OrderChildResp orderChildResp, Map<Integer, List<OrderItemResp>> childGoodsMapping) {
        if (CollectionUtil.isEmpty(childGoodsMapping)) {
            return;
        }
        // 设置订单商品项
        List<OrderItemResp> items = childGoodsMapping.get(orderChildResp.getId());
        if (CollUtil.isNotEmpty(items)) {
            for (OrderItemResp item : items) {
                item.setChildOrderId(orderChildResp.getId());
                item.setOrderId(orderChildResp.getParentOrderId());
            }
            orderChildResp.setOrderItems(items);
        }
        buildChildOrderWithUserInfo(orderChildResp);

        orderResp.setOrderChild(orderChildResp);
    }

    /**
     * 构建订单详情中的子订单信息
     *
     * @param orderChildResp         订单响应对象
     */
    private void buildChildOrderWithUserInfo(OrderChildResp orderChildResp) {
        // 获取用户信息 - 优化用户ID收集逻辑
        Set<Integer> userIds = new HashSet<>();
        userIds.add(orderChildResp.getUserId());
        if (Objects.nonNull(orderChildResp.getDeliveryUserId())) {
            userIds.add(orderChildResp.getDeliveryUserId());
        }
        Integer orderChildId = orderChildResp.getId();
        Map<Integer, UserInfoDTO> userMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(userIds)) {
            List<UserInfoDTO> users = userInfoServiceApi.getListByUserIds(userIds);
            userMap.putAll(users.stream().collect(Collectors.toMap(UserInfoDTO::getId, Function.identity(), (old, newItem) -> newItem)));
        }
        // 获取子订单的售后状态
        Map<Integer, Integer> childOrderAfterSaleStatusMap = getChildOrderAfterSaleStatusMapByChildOrderId(orderChildId);

        // 设置售后状态
        orderChildResp.setAfterSaleStatus(childOrderAfterSaleStatusMap.getOrDefault(orderChildResp.getId(), AfterSaleStatusEnum.NON_APPLY.getStatus()));
        // 设置用户信息
        UserInfoDTO userInfoDTO = userInfoServiceApi.getById(orderChildResp.getUserId());
        if (Objects.nonNull(userInfoDTO)) {
            orderChildResp.setUnionId(userInfoDTO.getUnionId());
        }

        // 设置收货人信息
        UserInfoDTO consigneeUser = userMap.get(orderChildResp.getUserId());
        if (consigneeUser != null) {
            orderChildResp.setConsignee(getUserName(consigneeUser));
            orderChildResp.setMobile(consigneeUser.getMobile());
        }

        // 设置配送人员信息
        UserInfoDTO deliveryUserInfoDTO = userMap.get(orderChildResp.getDeliveryUserId());
        if (deliveryUserInfoDTO != null) {
            orderChildResp.setDeliveryRealName(getUserName(deliveryUserInfoDTO));
            orderChildResp.setDeliveryUserMobile(deliveryUserInfoDTO.getMobile());
        }
    }

    /**
     * 构建子订单信息
     *
     * @param orderChildrenResp 子订单集合
     * @param childGoodsMapping 子订单商品映射
     * @return 子订单信息映射
     */
    private void buildChildOrder(List<OrderChildResp> orderChildrenResp, Map<Integer, List<OrderItemResp>> childGoodsMapping) {
        Set<Integer> childOrderIds = orderChildrenResp.stream().map(OrderChildResp::getId).collect(Collectors.toSet());
        Map<Integer, Integer> childOrderAfterSaleStatusMap = getChildOrderAfterSaleStatusMap(childOrderIds);
        orderChildrenResp.forEach(childOrder -> {
            childOrder.setOrderItems(childGoodsMapping.get(childOrder.getId()));
            // 设置售后状态
            childOrder.setAfterSaleStatus(childOrderAfterSaleStatusMap.getOrDefault(childOrder.getId(), AfterSaleStatusEnum.NON_APPLY.getStatus()));
        });
    }

    /**
     * 构建子订单信息
     *
     * @param orderIds          订单ID集合
     * @param childGoodsMapping 子订单商品映射
     * @return 子订单信息映射
     */
    private Map<Integer, List<OrderChildResp>> buildChildOrder(Set<Integer> orderIds, Map<Integer, List<OrderItemResp>> childGoodsMapping,Integer deliveryUserId) {
        Map<Integer, List<OrderChildResp>> orderChildrenMap = new HashMap<>();

        List<OrderChildEntity> orderChildren = orderChildService.getListByParentIds(orderIds);
        List<OrderChildResp> orderChildrenResp = OrderConverter.INSTANCE.convertOrderChildren(orderChildren);
        Set<Integer> childOrderIds = orderChildrenResp.stream().map(OrderChildResp::getId).collect(Collectors.toSet());
        Map<Integer, Integer> childOrderAfterSaleStatusMap = getChildOrderAfterSaleStatusMap(childOrderIds);
        Map<Integer, UserInfoDTO> userMappings = new HashMap<>();
        if(Objects.nonNull(deliveryUserId)){
            Set<Integer> userIds = orderChildrenResp.stream().map(OrderChildResp::getUserId).collect(Collectors.toSet());
            List<UserInfoDTO> users = userInfoServiceApi.getListByUserIds(userIds);
            if(CollectionUtil.isNotEmpty(users)){
                userMappings.putAll(users.stream().collect(Collectors.toMap(UserInfoDTO::getId, Function.identity(), (old, newItem) -> newItem)));
            }
        }
        orderChildrenResp.forEach(childOrder -> {

            childOrder.setOrderItems(childGoodsMapping.get(childOrder.getId()));
            // 设置售后状态
            childOrder.setAfterSaleStatus(childOrderAfterSaleStatusMap.getOrDefault(childOrder.getId(), AfterSaleStatusEnum.NON_APPLY.getStatus()));
            Integer orderId = childOrder.getParentOrderId();
            if( orderChildrenMap.containsKey(orderId)){
                orderChildrenMap.get(orderId).add(childOrder);
            }else{
                List<OrderChildResp> newList = new ArrayList<>();
                newList.add(childOrder);
                orderChildrenMap.put(orderId, newList);
            }
            UserInfoDTO userInfoDTO = userMappings.get(childOrder.getUserId());
            if(Objects.nonNull(userInfoDTO)){
                childOrder.setConsignee(getUserName(userInfoDTO));
                childOrder.setMobile(userInfoDTO.getMobile());
            }
        });
        return orderChildrenMap;
    }

    /**
     * 获取子订单的售后状态映射
     *
     * @param orderId 订单ID
     * @return 子订单ID与售后状态的映射
     */
    private Map<Integer, Integer> getChildOrderAfterSaleStatusMap(Integer orderId) {
        // 查询该订单下的所有售后单
        List<TradeAfterSaleEntity> tradeAfterSaleEntities = tradeAfterSaleMapper.selectList(
                new LambdaQueryWrapper<TradeAfterSaleEntity>()
                        .eq(TradeAfterSaleEntity::getOrderId, orderId));

        return getChildOrderAfterSaleStatusMap(tradeAfterSaleEntities);
    }

    /**
     * 获取子订单的售后状态映射
     *
     * @param childOrderIds 子订单ID
     * @return 子订单ID与售后状态的映射
     */
    private Map<Integer, Integer> getChildOrderAfterSaleStatusMap(Set<Integer> childOrderIds) {
        // 查询该订单下的所有售后单
        List<TradeAfterSaleEntity> tradeAfterSaleEntities = tradeAfterSaleMapper.selectList(
                new LambdaQueryWrapper<TradeAfterSaleEntity>()
                        .in(TradeAfterSaleEntity::getChildOrderId, childOrderIds));

        return getChildOrderAfterSaleStatusMap(tradeAfterSaleEntities);
    }

    /**
     * 获取子订单的售后状态映射
     *
     * @param childOrderId 订单ID
     * @return 子订单ID与售后状态的映射
     */
    private Map<Integer, Integer> getChildOrderAfterSaleStatusMapByChildOrderId(Integer childOrderId) {
        // 查询该订单下的所有售后单
        List<TradeAfterSaleEntity> tradeAfterSaleEntities = tradeAfterSaleMapper.selectList(
                new LambdaQueryWrapper<TradeAfterSaleEntity>()
                        .eq(TradeAfterSaleEntity::getChildOrderId, childOrderId));

        return getChildOrderAfterSaleStatusMap(tradeAfterSaleEntities);
    }

    private Map<Integer, Integer> getChildOrderAfterSaleStatusMap(List<TradeAfterSaleEntity> tradeAfterSaleEntities) {
        // 如果没有售后单，直接返回空Map
        if (CollectionUtil.isEmpty(tradeAfterSaleEntities)) {
            return new HashMap<>();
        }

        // 按子订单ID分组并直接转换为售后状态映射
        return tradeAfterSaleEntities.stream()
                .filter(entity -> Objects.nonNull(entity.getChildOrderId()))
                .collect(Collectors.groupingBy(
                        TradeAfterSaleEntity::getChildOrderId,
                        Collectors.collectingAndThen(
                                Collectors.mapping(TradeAfterSaleEntity::getStatus, Collectors.toSet()),
                                statuses -> statuses.stream().anyMatch(AfterSaleStatusEnum.APPLYING_STATUSES::contains)
                                        ? AfterSaleStatusEnum.APPLY.getStatus()
                                        : AfterSaleStatusEnum.NON_APPLY.getStatus()
                        )
                ));
    }

    /**
     * 构建订单分页查询条件
     *
     * @param params         查询参数
     * @param userId         用户ID
     * @param deliveryUserId 配送用户ID
     * @return 查询条件包装器
     */
    private LambdaQueryWrapper<OrderEntity> buildOrderPageQueryWrapper(OrderPageListReq params, Integer userId, Integer deliveryUserId) {
        return new LambdaQueryWrapper<OrderEntity>()
                .eq(Objects.nonNull(params.getOrderStatus()), OrderEntity::getOrderStatus, params.getOrderStatus())
                .eq(Objects.nonNull(userId), OrderEntity::getUserId, userId)
                .eq(Objects.nonNull(params.getOrderSn()), OrderEntity::getOrderSn, params.getOrderSn())
                .in(CollectionUtil.isNotEmpty(params.getOrderStatusList()), OrderEntity::getOrderStatus, params.getOrderStatusList())
                .likeRight(org.apache.commons.lang3.StringUtils.isNotBlank(params.getConsignee()), OrderEntity::getConsignee, params.getConsignee())
                .likeRight(org.apache.commons.lang3.StringUtils.isNotBlank(params.getMobile()), OrderEntity::getMobile, params.getMobile())
                .eq(Objects.nonNull(params.getProvince()), OrderEntity::getProvince, params.getProvince())
                .eq(Objects.nonNull(params.getCity()), OrderEntity::getCity, params.getCity())
                .eq(Objects.nonNull(params.getDistrict()), OrderEntity::getDistrict, params.getDistrict())
                .eq(Objects.nonNull(params.getPayStatus()), OrderEntity::getPayStatus, params.getPayStatus())
                .eq(Objects.nonNull(params.getShippingStatus()), OrderEntity::getShippingStatus, params.getShippingStatus())
                .eq(Objects.nonNull(params.getTenantId()), OrderEntity::getTenantId, params.getTenantId())
                .orderByDesc(OrderEntity::getId);
    }

    private String getUserName(UserInfoDTO userInfoDTO) {
        if (StringUtils.hasText(userInfoDTO.getRealName())) {
            return userInfoDTO.getRealName();
        }
        if (StringUtils.hasText(userInfoDTO.getNickName())) {
            return userInfoDTO.getNickName();
        }
        return userInfoDTO.getUserName();
    }

}