package com.wzj.soopin.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzj.soopin.goods.mapper.SkuMapper;
import com.wzj.soopin.order.convert.OrderConvert;
import com.wzj.soopin.order.convert.OrderItemConvert;
import com.wzj.soopin.order.domain.bo.OrderBo;
import com.wzj.soopin.order.domain.entity.Order;
import com.wzj.soopin.order.domain.entity.OrderItem;
import com.wzj.soopin.order.domain.vo.OrderVO;
import com.wzj.soopin.order.mapper.OrderItemMapper;
import com.wzj.soopin.order.mapper.OrderMapper;
import com.wzj.soopin.order.service.IMemberOrderService;
import com.wzj.soopin.order.service.IMerchantOrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.tenant.helper.TenantHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
@Slf4j
public class MerchantOrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IMerchantOrderService {

    private final OrderConvert convert;
    private final OrderItemMapper orderItemMapper;
    private final SkuMapper skuMapper;
    private final OrderItemConvert orderItemConvert;
    @Override
    public Page<OrderVO> page( OrderBo bo) {
        Page<Order> resultPage = baseMapper.selectPage(bo.getPage(),bo.toWrapper());

        Page<OrderVO> orderVOPage = convert.toVO(resultPage);
        List<OrderVO> orderVOList = orderVOPage.getRecords();
        if (orderVOList.isEmpty()) {
            return orderVOPage;
        }

        // 获取所有订单id
        List<Long> orderIds = orderVOList.stream()
            .map(OrderVO::getId)
            .collect(Collectors.toList());

        // 根据订单id查询订单详情
        QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
        orderItemQueryWrapper.in("order_id", orderIds);
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemQueryWrapper);

        // 按照订单id分组订单详情
        Map<Long, List<OrderItem>> orderItemMapByOrderId = orderItemList.stream()
            .collect(Collectors.groupingBy(OrderItem::getOrderId));

        for (OrderVO orderVO : orderVOList) {
            List<OrderItem> orderItems = orderItemMapByOrderId.get(orderVO.getId());
            if (orderItems != null) {
                orderVO.setItems(orderItemConvert.toVO(orderItems));
            }
        }

        return orderVOPage;
    }
}
