package cn.ysk.cashier.mybatis.mapper;

import cn.ysk.cashier.pojo.shop.TbShopUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【tb_shop_user(商户储值会员)】的数据库操作Mapper
* @createDate 2024-07-06 11:46:46
* @Entity cn.ysk.cashier.mybatis.entity.TbMShopUser
*/
public interface TbMShopUserMapper extends BaseMapper<TbShopUser> {
    @Select("<script>" +
            "SELECT \n" +
            "    COUNT(DISTINCT a.id) AS userTotal, \n" +
            "    COALESCE(SUM(flow.total_amount), 0) AS chageTotal, \n" +
            "    COALESCE(SUM(a.amount), 0) AS balanceTotal \n" +
            "FROM \n" +
            "    tb_shop_user AS a\n" +
            "    LEFT JOIN (\n" +
            "        SELECT shop_user_id, SUM(amount) AS total_amount \n" +
            "        FROM tb_shop_user_flow \n" +
            "        WHERE biz_code IN ('cashMemberIn','scanMemberIn', 'scanMemberAwardIn') \n" +
            "        GROUP BY shop_user_id\n" +
            "    ) AS flow ON flow.shop_user_id = a.id\n" +
            "WHERE \n" +
            "    a.shop_id = #{shopId} \n" +
            "<if test=\"isVip !=null\">\n" +
            "            and a.is_vip=#{isVip}\n" +
            "</if>" +
            "</script>")
    Map<String, Object> selectUserSummary(@Param("shopId") String shopId, @Param("isVip") Integer isVip);

    @Update("update tb_shop_user set amount=amount-#{orderAmount}, consume_amount=consume_amount+#{orderAmount} where id=#{vipUserId} and amount-#{orderAmount} >= 0")
    long decrBalance(@Param("vipUserId") Integer vipUserId, @Param("orderAmount") BigDecimal orderAmount);
}




