package com.wzj.soopin.order.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wzj.soopin.order.domain.entity.OrderItem;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * 订单中所包含的商品Mapper接口
 *
 * @author zcc
 */
@Mapper
public interface OrderItemMapper extends BaseMapper<OrderItem> {
    /**
     * 查询订单中所包含的商品列表
     *
     * @param orderItem 订单中所包含的商品
     * @return 订单中所包含的商品集合
     */
    List<OrderItem> selectByEntity(OrderItem orderItem);

    /**
     * 根据订单ID查询商品名称
     *
     * @param orderId 订单ID
     * @return 商品名称
     */
    @Select("SELECT p.name " +
            "FROM oms_order_item oi " +
            "JOIN pms_product p ON oi.product_id = p.id " +
            "WHERE oi.order_id = #{orderId} " +
            "LIMIT 1")
    String getName(Long orderId);

    /**
     * 查询交易量最多的商品列表
     * 统计已完成订单中商品的销售数量
     *
     * @param limit 查询数量限制
     * @return 商品交易量信息列表
     */
    @Select("SELECT " +
            "    oi.product_id, " +
            "    oi.product_name, " +
            "    oi.pic, " +
            "    oi.out_product_id, " +
            "    oi.product_category_id, " +
            "    SUM(oi.quantity) as total_quantity, " +
            "    SUM(oi.quantity * oi.sale_price) as total_amount, " +
            "    COUNT(DISTINCT o.id) as order_count " +
            "FROM oms_order_item oi " +
            "JOIN oms_order o ON oi.order_id = o.id " +
            "WHERE o.status = 3 " +  // 已完成订单
            "    AND o.delete_status = 0 " +  // 未删除订单
            "GROUP BY oi.product_id, oi.product_name, oi.pic, oi.out_product_id, oi.product_category_id " +
            "ORDER BY total_quantity DESC " +
            "LIMIT #{limit}")
    List<Map<String, Object>> selectTopTradingProducts(int limit);
}
