package com.seer.teach.mall.convert;

import cn.hutool.core.collection.CollectionUtil;
import com.seer.teach.mall.api.resp.OrderDTO;
import com.seer.teach.mall.api.resp.OrderItemDTO;
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.response.AddressResp;
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.response.OrderSettlementRespVO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

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

@Mapper
public interface OrderConverter {

    OrderConverter INSTANCE = Mappers.getMapper(OrderConverter.class);

    OrderResp one(OrderEntity order);

    List<OrderResp> list(List<OrderEntity> orders);

    OrderSettlementRespVO.Address convert(AddressResp address);

    OrderChildResp convertOrderChild2Resp(OrderChildEntity orderChild);

    List<OrderChildResp> convertOrderChildren(List<OrderChildEntity> orders);

    @Mapping(target = "orderChildren", source = "childOrders")
    OrderDTO convert2DTO(OrderEntity order, List<OrderChildEntity> childOrders);

    List<OrderItemDTO> convertOrderItems(List<OrderGoodsEntity> orderItems);

    default OrderDTO convertOne2DTO(OrderEntity order, List<OrderChildEntity> childOrders, List<OrderGoodsEntity> orderItems) {
        OrderDTO orderDTO = convert2DTO(order, childOrders);

        List<OrderItemDTO> orderItemList = convertOrderItems(orderItems);
        if (CollectionUtil.isEmpty(orderItemList)) {
            return orderDTO;
        }
        if (CollectionUtil.isEmpty(orderDTO.getOrderChildren())) {
            return orderDTO;
        }
        Map<Integer, List<OrderItemDTO>> goodsMapping = convertOrderItems(orderItems).stream()
                .filter(item -> Objects.nonNull(item.getChildOrderId()))
                .collect(Collectors.groupingBy(OrderItemDTO::getChildOrderId));
        orderDTO.getOrderChildren().forEach(child -> {
            child.setOrderItems(goodsMapping.get(child.getId()));
        });
        return orderDTO;
    }
}