package com.ruoyi.school.member.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ruoyi.school.member.domain.ScMemberCard;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 会员卡Mapper接口
 */
@Mapper
public interface ScMemberCardMapper extends BaseMapper<ScMemberCard> {

    /**
     * 根据会员ID查询会员卡列表
     */
//    @Select("SELECT a.*,b.card_name FROM sc_member_cards a,sc_member_card_types b " +
//            "WHERE a.card_type_id=b.card_type_id and member_id = #{memberId} AND is_deleted = 0 " +
//            "ORDER BY created_at DESC")
    @Select("SELECT * FROM sc_member_cards " +
            "WHERE member_id = #{memberId} AND is_deleted = 0 " +
            "ORDER BY created_at DESC")
    List<ScMemberCard> selectByMemberId(@Param("memberId") Long memberId);

    /**
     * 根据卡号查询会员卡
     */
    @Select("SELECT * FROM sc_member_cards WHERE card_no = #{cardNo} AND is_deleted = 0")
    ScMemberCard selectByCardNo(@Param("cardNo") String cardNo);

    /**
     * 查询已过期的会员卡
     */
    @Select("SELECT * FROM sc_member_cards WHERE status = 'EXPIRED' OR (expiry_date IS NOT NULL AND expiry_date < CURDATE()) AND is_deleted = 0")
    List<ScMemberCard> selectExpiredCards();

    /**
     * 查询即将到期的会员卡（N天内到期）
     */
    @Select("SELECT * FROM sc_member_cards WHERE expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL #{days} DAY) AND status = 'ACTIVE' AND is_deleted = 0")
    List<ScMemberCard> selectExpiringCards(@Param("days") Integer days);

    @Select("SELECT count(1) FROM sc_member_cards WHERE remaining_total_fee <= #{fee} AND status = 'ACTIVE' AND is_deleted = 0")
    Integer selectFeeWillExpireCards(@Param("fee") Integer fee);

    @Select("SELECT count(1) FROM sc_member_cards WHERE remaining_count <= #{hour} AND status = 'ACTIVE' AND is_deleted = 0")
    Integer selectHourWillExpireCards(@Param("hour") Integer hour);

    /**
     * 更新会员卡状态
     */
    @Update("UPDATE sc_member_cards SET status = #{status}, updated_at = NOW() WHERE id = #{id} AND is_deleted = 0")
    int updateStatus(@Param("id") Long id, @Param("status") String status);

    /**
     * 扣减次数
     */
    @Update("UPDATE sc_member_cards SET remaining_count = remaining_count - #{count}, updated_at = NOW() WHERE id = #{id} AND remaining_count >= #{count} AND is_deleted = 0")
    int deductCount(@Param("id") Long id, @Param("count") Integer count);

    /**
     * 增加次数
     */
    @Update("UPDATE sc_member_cards SET remaining_count = remaining_count + #{count}, updated_at = NOW() WHERE id = #{id} AND is_deleted = 0")
    int addCount(@Param("id") Long id, @Param("count") Integer count);

}
