package com.it.rattan.monisuo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.it.rattan.monisuo.entity.OrderTrade;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 交易订单Mapper
 */
@Mapper
public interface OrderTradeMapper extends BaseMapper<OrderTrade> {

    // ========== 分析相关查询 ==========

    /**
     * 指定类型和时间段内的交易金额
     */
    @Select("SELECT IFNULL(SUM(amount), 0) FROM order_trade WHERE type = #{type} AND create_time >= #{startTime}")
    BigDecimal sumAmountByTypeAndTime(@Param("type") int type, @Param("startTime") LocalDateTime startTime);

    /**
     * 指定类型和时间段内的交易笔数
     */
    @Select("SELECT COUNT(*) FROM order_trade WHERE type = #{type} AND create_time >= #{startTime}")
    int countByTypeAndTime(@Param("type") int type, @Param("startTime") LocalDateTime startTime);

    /**
     * 指定类型和时间范围内的交易金额
     */
    @Select("SELECT IFNULL(SUM(amount), 0) FROM order_trade WHERE type = #{type} AND create_time >= #{startTime} AND create_time < #{endTime}")
    BigDecimal sumAmountByTypeAndTimeRange(@Param("type") int type, @Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);

    /**
     * 指定时间段内的活跃用户数
     */
    @Select("SELECT COUNT(DISTINCT user_id) FROM order_trade WHERE create_time >= #{startTime} AND create_time < #{endTime}")
    int countDistinctUserByTime(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);

    /**
     * 按币种分组统计交易金额
     */
    @Select("SELECT coin_code as coinCode, coin_name as coinName, SUM(amount) as amount FROM order_trade " +
            "WHERE create_time >= #{startTime} GROUP BY coin_code, coin_name ORDER BY amount DESC")
    List<Map<String, Object>> sumAmountGroupByCoin(@Param("startTime") LocalDateTime startTime);

    /**
     * 指定时间段内的手续费总额（假设手续费率为0.1%）
     */
    @Select("SELECT IFNULL(SUM(amount * 0.001), 0) FROM order_trade WHERE status = 2 AND create_time >= #{startTime}")
    BigDecimal sumFeeByTime(@Param("startTime") LocalDateTime startTime);
}
