package shop.alien.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
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.CommonComment;
import shop.alien.entity.store.vo.CommonCommentVo;

import java.util.List;

/**
 * 评论表 Mapper 接口
 *
 * @author system
 * @since 2025-01-XX
 */
@Mapper
public interface CommonCommentMapper extends BaseMapper<CommonComment> {


    /**
     * 查询评论列表（含用户/商户信息）
     * 
     * 关联说明：
     * - 用户评论（comment_type=1）：关联 life_user 表获取用户头像和昵称
     * - 商户评论（comment_type=2）：关联 store_user 表获取商户头像和昵称
     *   （通过子查询取每个店铺的主账号记录，即 id 最小的记录）
     */
    @Select("SELECT cc.*, " +
            "IF(cc.comment_type = 1, lu.user_image, su.head_img) AS headImg, " +
            "IF(cc.comment_type = 1, lu.user_name, su.nick_name) AS headName, " +
            "IF(cc.comment_type = 1, lu.user_phone, su.phone) AS headPhone, " +
            "IF(cc.comment_type = 2, si.store_name, NULL) AS storeName, " +
            "IF(llr.id IS NULL, '0', '1') AS isLike " +
            "FROM common_comment cc " +
            "LEFT JOIN life_user lu ON cc.user_id = lu.id AND lu.delete_flag = 0 " +
            "LEFT JOIN store_info si ON cc.merchant_id = si.id AND si.delete_flag = 0 " +
            "LEFT JOIN store_user su ON cc.merchant_id = su.store_id AND su.delete_flag = 0 " +
            "AND su.id = (SELECT MIN(su2.id) FROM store_user su2 WHERE su2.store_id = cc.merchant_id AND su2.delete_flag = 0) " +
            "LEFT JOIN life_like_record llr ON llr.huifu_id = cc.id " +
            "AND llr.`type` = #{type} " +
            "AND llr.dianzan_user_type = 1 AND llr.dianzan_ref_id = #{dianzanId} " +
            "AND llr.delete_flag = 0 " +
            "${ew.customSqlSegment}")
    List<CommonCommentVo> selectALlComment(@Param("page") Page<CommonCommentVo> page,
                                           @Param(Constants.WRAPPER)QueryWrapper<CommonCommentVo> wrapper,
                                           @Param("type") String type,
                                           @Param("dianzanId") Long dianzanId);

    @Select("select cc.source_id sourceId,count(*) commentCount\n" +
            "from common_comment cc\n" +
            "where \n" +
            "cc.source_type = #{businessType}\n" +
            "and cc.delete_flag = 0\n" +
            "group by source_id")
    List<CommonCommentVo> getCommentCount(Integer type);

    /**
     * 批量查询评论数量（按sourceId分组统计）
     * 
     * @param sourceType 来源类型
     * @param sourceIds 来源ID列表
     * @return sourceId -> commentCount 的映射列表
     */
    @Select("<script>" +
            "SELECT cc.source_id AS sourceId, COUNT(*) AS commentCount " +
            "FROM common_comment cc " +
            "WHERE cc.source_type = #{sourceType} " +
            "AND cc.delete_flag = 0 " +
            "<if test='sourceIds != null and sourceIds.size() > 0'>" +
            "AND cc.source_id IN " +
            "<foreach collection='sourceIds' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</if>" +
            "GROUP BY cc.source_id" +
            "</script>")
    List<CommonCommentVo> batchGetCommentCount(@Param("sourceType") Integer sourceType, 
                                                @Param("sourceIds") List<Integer> sourceIds);

    /**
     * 批量逻辑删除评论（使用原生 SQL 绕过 @TableLogic 注解限制）
     *
     * @param sourceType 来源类型
     * @param sourceId   来源ID（评价ID）
     * @return 影响行数
     */
    @Update("UPDATE common_comment SET delete_flag = 1, updated_time = NOW() " +
            "WHERE source_type = #{sourceType} AND source_id = #{sourceId} AND delete_flag = 0")
    int logicDeleteBySourceId(@Param("sourceType") Integer sourceType, @Param("sourceId") Integer sourceId);

    @Select("select * from common_comment ${ew.customSqlSegment}")
    CommonComment selectAll(@Param(Constants.WRAPPER) LambdaQueryWrapper<CommonComment> and);
}

