package com.starry.admin.modules.withdraw.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.starry.admin.modules.withdraw.entity.EarningsLineEntity;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface EarningsLineMapper extends BaseMapper<EarningsLineEntity> {

    @Select("SELECT COALESCE(SUM(amount), 0) " +
            "FROM play_earnings_line " +
            "WHERE deleted = 0 " +
            "  AND clerk_id = #{clerkId} " +
            "  AND (status = 'available' OR (status = 'frozen' AND unlock_time <= #{now}))")
    BigDecimal sumWithdrawableAmount(@Param("clerkId") String clerkId, @Param("now") LocalDateTime now);

    @Select("SELECT COALESCE(SUM(amount), 0) " +
            "FROM play_earnings_line " +
            "WHERE deleted = 0 " +
            "  AND clerk_id = #{clerkId} " +
            "  AND status = 'frozen' " +
            "  AND unlock_time > #{now}")
    BigDecimal sumPendingAmount(@Param("clerkId") String clerkId, @Param("now") LocalDateTime now);

    @Select("SELECT * " +
            "FROM play_earnings_line " +
            "WHERE deleted = 0 " +
            "  AND clerk_id = #{clerkId} " +
            "  AND (status = 'available' OR (status = 'frozen' AND unlock_time <= #{now})) " +
            "ORDER BY unlock_time ASC")
    List<EarningsLineEntity> selectWithdrawableLines(@Param("clerkId") String clerkId, @Param("now") LocalDateTime now);

    @Select("<script>" +
            "SELECT COALESCE(SUM(el.amount), 0) " +
            "FROM play_earnings_line el " +
            "JOIN play_order_info oi ON oi.id = el.order_id " +
            "WHERE el.deleted = 0 " +
            "  AND oi.deleted = 0 " +
            "  AND el.clerk_id = #{clerkId} " +
            "  AND el.status &lt;&gt; 'reversed' " +
            "<if test='orderIds != null and orderIds.size &gt; 0'>" +
            "  AND el.order_id IN " +
            "    <foreach item='id' collection='orderIds' open='(' separator=',' close=')'>#{id}</foreach>" +
            "</if>" +
            "<if test='startTime != null'>" +
            "  AND oi.purchaser_time &gt;= #{startTime}" +
            "</if>" +
            "<if test='endTime != null'>" +
            "  AND oi.purchaser_time &lt;= #{endTime}" +
            "</if>" +
            "</script>")
    BigDecimal sumAmountByClerkAndOrderIds(@Param("clerkId") String clerkId,
                                           @Param("orderIds") Collection<String> orderIds,
                                           @Param("startTime") String startTime,
                                           @Param("endTime") String endTime);
}
