package shop.alien.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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 shop.alien.entity.store.CommonRating;
import shop.alien.entity.store.vo.StoreInfoScoreVo;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 评价表 Mapper 接口
 *
 * @author system
 * @since 2025-01-XX
 */
@Mapper
public interface CommonRatingMapper extends BaseMapper<CommonRating> {

    /**
     * 获取评价数量和评价分数信息
     *
     * @param businessId 门店ID
     * @param businessType 业务类型
     * @return 评价数量和评价分数信息
     */
    @Select("SELECT " +
            "IFNULL(SUM(score), 0) AS score, " +
            "IFNULL(SUM(score_one), 0) AS scoreOne, " +
            "IFNULL(SUM(score_two), 0) AS scoreTwo, " +
            "IFNULL(SUM(score_three), 0) AS scoreThree, " +
            "COUNT(0) AS total " +
            "FROM `common_rating` " +  // FROM 后加空格，避免和表名拼接成 FROM`common_rating`
            "WHERE business_type = #{businessType} " +
            "AND delete_flag = 0 " +
            "AND audit_status = 1 " +
            "AND business_id = #{businessId}")
    StoreInfoScoreVo getCommentCountAndScoreInfo(@Param("businessType")Integer businessType,@Param("businessId")Integer businessId);



    @Select("SELECT " +
            "IFNULL(SUM(score), 0) AS score, " +
            "IFNULL(SUM(score_one), 0) AS scoreOne, " +
            "IFNULL(SUM(score_two), 0) AS scoreTwo, " +
            "IFNULL(SUM(score_three), 0) AS scoreThree, " +
            "COUNT(0) AS total " +
            "FROM `common_rating` " +  // FROM 后加空格，避免和表名拼接成 FROM`common_rating`
            "WHERE business_type = #{businessType} " +
            "AND delete_flag = 0 " +
            "AND audit_status = 1 " +
            "AND business_id = #{businessId} " +
            "GROUP BY user_id"
    )
    List<StoreInfoScoreVo> getStoreInfoScoreNew(@Param("businessType")Integer businessType, @Param("businessId")Integer businessId);


     /**
     * 获取评价数量
     */
    @Select("SELECT\n" +
//            "    -- 1. 总评论数（当前门店、根评论、未删除）\n" +
//            "    COUNT(1) AS totalCount,\n" +
            "    -- 2. 有图评论数（image_urls 不为 null 且不为空字符串）\n" +
            "    SUM(CASE WHEN image_urls IS NOT NULL AND image_urls != '' AND TRIM(image_urls) <> '' THEN 1 ELSE 0 END) AS imageCount,\n" +
            "    -- 3. 好评数（score >= 4.5）\n" +
            "    SUM(CASE WHEN score >= 4.5 THEN 1 ELSE 0 END) AS goodCount,\n" +
            "    -- 4. 中评数（score >= 3.0 AND score <= 4.0）\n" +
            "    SUM(CASE WHEN score >= 3.0 AND score <= 4.0 THEN 1 ELSE 0 END) AS midCount,\n" +
            "    -- 5. 差评数（score >= 0.5 AND score <= 2.5）\n" +
            "    SUM(CASE WHEN score >= 0.5 AND score <= 2.5 THEN 1 ELSE 0 END) AS badCount\n" +
            "FROM\n" +
            "    common_rating\n" +
            "   ${ew.customSqlSegment}\n")
    Map<String, Object> getRatingCount(@Param(Constants.WRAPPER) QueryWrapper<CommonRating> wrapper);

    /**
     * 逻辑删除评价（使用原生 SQL 绕过 @TableLogic 注解限制）
     *
     * @param id 评价ID
     * @return 影响行数
     */
    @Update("UPDATE common_rating SET delete_flag = 1, updated_time = NOW() WHERE id = #{id}")
    int logicDeleteById(@Param("id") Integer id);

    IPage<CommonRating> getMyRatingList(Page<CommonRating> page, @Param(Constants.WRAPPER) QueryWrapper<CommonRating> wrapper);

    /**
     * 分页查询评价列表（支持 wrapper 条件，如 business_id、business_type、audit_status、is_show 等）
     *
     * @param page    分页参数
     * @param wrapper 查询条件，例如：
     *                wrapper.eq(CommonRating::getBusinessId, businessId);
     *                wrapper.eq(CommonRating::getBusinessType, businessType);
     *                wrapper.eq(CommonRating::getAuditStatus, 1);
     *                wrapper.eq(CommonRating::getIsShow, 1);
     * @return 分页结果
     */
    Integer getRatingWithNoReply( @Param(Constants.WRAPPER) Wrapper<CommonRating> wrapper);

    /**
     * 统计该用户在该店铺下已通过审核的好评次数（用于好评送券参与次数限制）
     * 注意：统计包括已删除的评论，防止用户删除评论后再次获得券
     * 审核成功之前的评论不计算在参与次数中（只统计审核成功时间在活动审核时间之后的评论）
     * @param userId 用户ID
     * @param storeId 店铺ID（business_id）
     * @param activityAuditTime 活动审核时间，为null时统计所有历史好评
     * @return 已通过的好评条数（business_type=1, audit_status=1, score>=4.5），包括已删除的评论
     */
    @Select("<script>" +
            "SELECT COUNT(*) FROM common_rating " +
            "WHERE business_type = 1 " +
            "AND business_id = #{storeId} " +
            "AND user_id = #{userId} " +
            "AND audit_status = 1 " +
            "AND score >= 4.5 " +
            "<if test='activityAuditTime != null'>" +
            "AND updated_time >= #{activityAuditTime} " +
            "</if>" +
            "</script>")
    int countPassedGoodRatingsByUserAndStore(@Param("userId") Long userId, @Param("storeId") Integer storeId, @Param("activityAuditTime") Date activityAuditTime);
}

