package com.ylx.point.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylx.point.domain.PointUserLog;
import com.ylx.point.domain.dto.UserPointPageDTO;
import com.ylx.point.domain.vo.UserPointLogVO;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Map;

/**
 * 用户积分流水Mapper接口
 *
 * @author wzj
 * @date 2026-03-25
 */
public interface PointUserLogMapper extends BaseMapper<PointUserLog> {

    @Select("<script>" +
            "SELECT " +
            "   COALESCE(SUM(CASE WHEN op_type = 1 THEN points ELSE 0 END) - " +
            "            SUM(CASE WHEN op_type IN (2, 3) THEN points ELSE 0 END), 0) AS totalPoints, " +
            "   COALESCE(SUM(CASE WHEN month = #{currentMonth} AND op_type = 1 THEN points ELSE 0 END), 0) AS earnedPoints, " +
            "   COALESCE(SUM(CASE WHEN is_expired = 0 AND expire_time &gt;= #{startOfThisMonth} AND expire_time &lt;= #{endOfThisMonth} THEN points ELSE 0 END), 0) AS expirePoints " +
            "FROM point_user_log " +
            "WHERE open_id = #{openId} " +
            "</script>")
    Map<String, Object> selectPointStatistics(
            @Param("openId") String openId,
            @Param("currentMonth") String currentMonth,
            @Param("startOfThisMonth") String startOfThisMonth,
            @Param("endOfThisMonth") String endOfThisMonth);

    Page<UserPointLogVO> getUserPointLogList(Page<PointUserLog> page, @Param("dto") UserPointPageDTO dto);

    /**
     * 获取用户可用积分余额
     * 计算公式：未过期收入总和 - 支出总和
     */
    @Select("SELECT COALESCE(SUM(CASE WHEN op_type = 1 AND is_expired != 1 THEN points ELSE 0 END) - " +
            "SUM(CASE WHEN op_type IN (2, 3) THEN points ELSE 0 END), 0) AS points " +
            "FROM point_user_log WHERE open_id = #{openId}")
    Integer selectAvailableBalance(@Param("openId") String openId);
}
