package shop.alien.mapper;

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 org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import shop.alien.entity.store.LifeAppealManage;
import shop.alien.entity.store.StoreComment;
import shop.alien.entity.store.vo.*;

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

/**
 * 评论表 Mapper 接口
 *
 * @author ssk
 * @since 2025-01-02
 */
public interface StoreCommentMapper extends BaseMapper<StoreComment> {

    /**
     * 申诉分页查询
     *
     * @param page         分页参数
     * @param queryWrapper 查询参数
     * @return IPage<LifeAppealManageVo>
     */
    @Select("SELECT a.*, b.dict_detail as appeal_type_str FROM life_appeal_manage a "
            + "left join store_dictionary b on a.appeal_type = b.dict_id and b.type_name = 'appealType' ${ew.customSqlSegment}")
    IPage<StoreComment> getList(IPage<LifeAppealManageVo> page, @Param(Constants.WRAPPER) QueryWrapper<LifeAppealManage> queryWrapper);

    /**
     * 查询评论
     *
     * @param queryWrapper 查询条件
     * @return List<StoreCommentVo>
     */
    @Select("SELECT a.*, IF(INSTR( a.phone_id, 'user' ) > 0, b.user_name, c.store_name ) user_name, "
            + "IF(INSTR( a.phone_id, 'store' ) > 0, d.head_img, b.user_image ) user_image FROM store_comment a "
            + "left join life_user b on a.user_id = b.id and b.delete_flag = 0 "
            + "left join store_info c on a.store_id = c.id and c.delete_flag = 0 "
            + "left join store_user d on d.store_id = c.id and d.delete_flag = 0 ${ew.customSqlSegment}")
    List<StoreCommentVo> getCommentList(@Param(Constants.WRAPPER) QueryWrapper<StoreCommentVo> queryWrapper);

    /**
     * 评论数和评分
     *
     * @param businessId   业务id
     * @param businessType 业务类型
     * @param storeId      门店id
     * @return Map<String, String>
     */
    @Select("SELECT SUM((SELECT count( id ) FROM store_comment WHERE business_type = #{businessType} AND reply_id IS NULL " +
            "AND (#{businessId} IS NULL OR business_id = #{businessId}) AND (#{storeId} IS NULL OR store_id = #{storeId})) + " +
            "(SELECT count( id ) FROM store_comment WHERE business_type = #{businessType} AND reply_id IN " +
            "(SELECT id FROM store_comment WHERE business_type = #{businessType} AND reply_id IS NULL " +
            "AND (#{businessId} IS NULL OR business_id = #{businessId})) AND (#{storeId} IS NULL OR store_id = #{storeId}))) AS count, " +
            "(SELECT count( id ) FROM store_comment WHERE business_type = #{businessType} AND reply_id IS NULL " +
            "AND (#{businessId} IS NULL OR business_id = #{businessId}) AND (#{storeId} IS NULL OR store_id = #{storeId})) AS rootCount, " +
            "(SELECT IF(SUM( score ) ,SUM( score ) ,0) FROM store_comment WHERE business_type = #{businessType} " +
            "AND reply_id IS NULL AND (#{businessId} IS NULL OR business_id = #{businessId}) AND (#{storeId} IS NULL OR store_id = #{storeId})) AS score")
    Map<String, Object> getCommentCountAndScore(@Param("businessId") Integer businessId, @Param("businessType") Integer businessType, @Param("storeId") Integer storeId);

    /**
     * 根据业务id分组获取根评论
     *
     * @param businessType 业务类型
     * @param storeId      门店id
     * @return List<StoreCommentVo>
     */
    @Select("SELECT count( id ) commitCount, business_id as businessId FROM store_comment WHERE business_type = #{businessType} " +
            "AND reply_id IS NULL AND (#{storeId} IS NULL OR store_id = #{storeId}) GROUP BY business_id")
    List<StoreCommentVo> getRootCommitCount(@Param("businessType") Integer businessType, @Param("storeId") Integer storeId);

    /**
     * 根据回复id分组获取子评论
     *
     * @param businessType 业务类型
     * @param storeId      门店id
     * @return List<StoreCommentVo>
     */
    @Select("SELECT count( id ) commitCount, reply_id as replyId FROM store_comment WHERE business_type = #{businessType} " +
            "AND reply_id IS NOT NULL AND (#{storeId} IS NULL OR store_id = #{storeId}) GROUP BY reply_id")
    List<StoreCommentVo> getSonCommitCount(@Param("businessType") Integer businessType, @Param("storeId") Integer storeId);

    /**
     * 评价分页查询
     *
     * @param page         分页参数
     * @param queryWrapper 查询条件
     * @return IPage<StoreCommentVo>
     */
    @Select("SELECT a.*, COALESCE(b.user_name, c.store_name) user_name, "
            + "IF(INSTR( a.phone_id, 'store' ) > 0, d.head_img, b.user_image ) user_image FROM store_comment a "
            + "left join life_user b on a.user_id = b.id and b.delete_flag = 0 "
            + "left join store_info c on a.store_id = c.id and c.delete_flag = 0 "
            + "left join store_user d on d.store_id = c.id and d.delete_flag = 0 ${ew.customSqlSegment}")
    IPage<StoreCommentVo> getCommentPage(IPage<StoreCommentVo> page, @Param(Constants.WRAPPER) QueryWrapper<StoreCommentVo> queryWrapper);

    /**
     * 获取评论相关数据
     *
     * @param storeId 门店id
     * @return StoreCommitPercentVo
     */
    @Select("select (select COUNT(1) from store_comment where business_type = 5 and delete_flag = 0 and reply_id is null and score >= 4.5 and store_id = #{storeId}) highCommentCount, " +
            "(select COUNT(1) from store_comment where business_type = 5 and delete_flag = 0 and reply_id is null and score >= 3 and score <= 4 and store_id = #{storeId}) midCommentCount, " +
            "(select COUNT(1) from store_comment where business_type = 5 and delete_flag = 0 and reply_id is null and score >= 0.5 and score <= 2.5 and store_id = #{storeId}) lowCommentCount, " +
            "(select COUNT(1) from store_comment where business_type = 5 and delete_flag = 0 and score is not null and store_id = #{storeId}) allCommentCount, " +
            "(select count(1) from store_comment where business_type = 5 and reply_id is null and delete_flag = 0 and store_id = #{storeId}) rootCommentCount, " +
            "(select count(DISTINCT reply_id) from store_comment where reply_id is NOT null and store_id = #{storeId} and phone_id like '%store%' and delete_flag = 0 and business_type = 1) commentCount ")
    StoreCommitPercentVo getCommentByStoreId(Integer storeId);

    @Select("SELECT " +
            "ifnull(SUM( score ),0) score," +
            "ifnull(SUM( score_one ),0) scoreOne," +
            "ifnull(SUM( score_two ),0) scoreTwo," +
            "ifnull(SUM( score_three ),0) scoreThree," +
            "COUNT(0) total " +
            "FROM" +
            "`store_comment` " +
            "WHERE " +
            "business_type = 6 " +
            "AND delete_flag = 0 " +
            "AND reply_id IS NULL " +
            "AND store_id = #{storeId}")
    StoreInfoScoreVo getCommentCountAndScoreInfo(@Param("storeId") Integer storeId);

/*
    with total_coupon as (
select lgbm.id,lgbm.group_type,lgbm.group_name,lgbm.image_id,2 coupon_type
from life_group_buy_main lgbm
union all
select lc.id,0 group_type,lc.name group_name,0 image_id,1 coupon_type
from life_coupon lc
)
SELECT
	luo.*,
	tc.group_type groupBuyType,
	tc.group_name groupBuyName,
	tc.image_id groupBuyImgId,
	store.business_section storeType
FROM
	life_user_order luo
LEFT JOIN order_coupon_middle ocm ON
	luo.id = ocm.order_id
LEFT JOIN total_coupon tc ON
	ocm.coupon_id = tc.id
	and tc.coupon_type = luo.coupon_type
LEFT JOIN store_info store on
	luo.store_id = store.id
WHERE
	luo.`status` in (2, 7)
	AND luo.delete_flag = 0
	AND luo.user_id = 142
	AND luo.id NOT IN (
	SELECT
		business_id
	FROM
		store_comment
	WHERE
		business_type = 5
		AND user_id = 142
		AND delete_flag = 0)
 */
    @Select("SELECT " +
            "luo.*,lgbm.group_type groupBuyType,lgbm.group_name groupBuyName,lgbm.image_id groupBuyImgId,store.business_section storeType, store.business_types_name businessTypesName, store.store_name storeName " +
            "FROM life_user_order luo LEFT JOIN order_coupon_middle ocm ON luo.id = ocm.order_id LEFT JOIN life_group_buy_main lgbm ON ocm.coupon_id = lgbm.id LEFT JOIN store_info store on luo.store_id = store.id " +
            "WHERE luo.`status` in (2,7) " +
            "AND luo.coupon_type = 2 " +
            "AND luo.delete_flag = 0 " +
            "AND luo.user_id = #{userId} " +
            "AND luo.id NOT IN (SELECT business_id FROM store_comment WHERE business_type = 5 AND user_id = #{userId})")
    IPage<LifeUserOrderCommentVo> getCommentOrderWPJPage(IPage<LifeUserOrderCommentVo> page, @Param("userId") String userId);

    @Select("SELECT " +
            "luo.*,lgbm.group_type groupBuyType,lgbm.group_name groupBuyName,lgbm.image_id groupBuyImgId,store.business_section storeType, store.business_types_name businessTypesName, store.store_name storeName " +
            "FROM life_user_order luo LEFT JOIN order_coupon_middle ocm ON luo.id = ocm.order_id LEFT JOIN life_group_buy_main lgbm ON ocm.coupon_id = lgbm.id LEFT JOIN store_info store on luo.store_id = store.id " +
            "WHERE luo.`status` in (2,7) " +
            "AND luo.coupon_type = 2 " +
            "AND luo.delete_flag = 0 " +
            "AND luo.user_id = #{userId} " +
            "AND luo.id IN (SELECT business_id FROM store_comment WHERE business_type = 5 AND user_id = #{userId} AND delete_flag = 0)")
    IPage<LifeUserOrderCommentVo> getCommentOrderYPJPage(IPage<LifeUserOrderCommentVo> page, @Param("userId") String userId);

    @Select("SELECT\n" +
            "\ts.*,\n" +
            "\tlu.user_name, \n" +
            "\tlu.user_image \n" +
            "FROM\n" +
            "\tstore_comment s\n" +
            "\tLEFT JOIN life_user lu ON s.user_id = lu.id \n" +
            "WHERE\n" +
            "\ts.business_type = 6 \n" +
            "\tAND s.store_id = #{storeId}\n" +
            "\tLIMIT 1")
    StoreCommentVo getCommentOneInfo(@Param("storeId") int storeId);

    /**
     * 当前用户的全部评价（店铺订单评价 + 律师订单评价）
     */
    @Select("SELECT * FROM ( " +
            "SELECT " +
            "luo.id, luo.user_id, luo.store_id, " +
            "CONVERT(luo.quan_id USING utf8mb4) COLLATE utf8mb4_unicode_ci AS quan_id, " +
            "CONVERT(luo.quan_code USING utf8mb4) COLLATE utf8mb4_unicode_ci AS quan_code, " +
            "CONVERT(luo.order_no USING utf8mb4) COLLATE utf8mb4_unicode_ci AS order_no, " +
            "CONVERT(luo.order_str USING utf8mb4) COLLATE utf8mb4_unicode_ci AS order_str, " +
            "luo.status, " +
            "CONVERT(luo.price USING utf8mb4) COLLATE utf8mb4_unicode_ci AS price, " +
            "CONVERT(luo.final_price USING utf8mb4) COLLATE utf8mb4_unicode_ci AS final_price, " +
            "luo.buy_time, luo.pay_time, " +
            "CONVERT(luo.pay_method USING utf8mb4) COLLATE utf8mb4_unicode_ci AS pay_method, " +
            "luo.used_time, luo.refund_time, luo.coupon_type, luo.cancel_time, " +
            "CONVERT(luo.cancel_reason USING utf8mb4) COLLATE utf8mb4_unicode_ci AS cancel_reason, " +
            "luo.finish_time, luo.delete_flag, luo.created_time, luo.created_user_id, luo.updated_time, luo.updated_user_id, luo.send_discount_coupon_flag, luo.expert_order_id, luo.order_appraise, " +
            "lgbm.image_id AS groupBuyImgId, NULL AS groupBuyImgUrl, " +
            "CONVERT(lgbm.group_name USING utf8mb4) COLLATE utf8mb4_unicode_ci AS groupBuyName, " +
            "lgbm.group_type AS groupBuyType, " +
            "CONVERT(store.business_section USING utf8mb4) COLLATE utf8mb4_unicode_ci AS storeType, " +
            "CONVERT(store.business_types_name USING utf8mb4) COLLATE utf8mb4_unicode_ci AS businessTypesName, " +
            "CONVERT(store.store_name USING utf8mb4) COLLATE utf8mb4_unicode_ci AS storeName, " +
            "CONVERT(sc.comment_content USING utf8mb4) COLLATE utf8mb4_unicode_ci AS commentContent, sc.score, sc.created_time AS commentDate, " +
            "CONVERT(sc.img_id USING utf8mb4) COLLATE utf8mb4_unicode_ci AS imgId, 1 AS src " +
            "FROM store_comment sc " +
            "LEFT JOIN life_user_order luo ON sc.business_id = luo.id " +
            "LEFT JOIN order_coupon_middle ocm ON luo.id = ocm.order_id " +
            "LEFT JOIN life_group_buy_main lgbm ON ocm.coupon_id = lgbm.id " +
            "LEFT JOIN store_info store ON luo.store_id = store.id " +
            "WHERE sc.business_type = 5 AND sc.delete_flag = 0 AND sc.user_id = #{userId} " +
            "UNION ALL " +
            "SELECT " +
            "CAST(lor.order_id AS CHAR CHARACTER SET utf8mb4) COLLATE utf8mb4_unicode_ci AS id, " +
            "CAST(lor.user_id AS CHAR CHARACTER SET utf8mb4) COLLATE utf8mb4_unicode_ci AS user_id, " +
            "NULL AS store_id, NULL AS quan_id, NULL AS quan_code, " +
            "CONVERT(lor.order_number USING utf8mb4) COLLATE utf8mb4_unicode_ci AS order_no, " +
            "NULL AS order_str, NULL AS status, NULL AS price, NULL AS final_price, NULL AS buy_time, NULL AS pay_time, NULL AS pay_method, NULL AS used_time, NULL AS refund_time, NULL AS coupon_type, NULL AS cancel_time, NULL AS cancel_reason, NULL AS finish_time, lor.delete_flag, lor.created_time, lor.created_user_id, lor.updated_time, lor.updated_user_id, NULL AS send_discount_coupon_flag, NULL AS expert_order_id, NULL AS order_appraise, " +
            "NULL AS groupBuyImgId, NULL AS groupBuyImgUrl, NULL AS groupBuyName, NULL AS groupBuyType, NULL AS storeType, NULL AS businessTypesName, NULL AS storeName, " +
            "lor.review_content AS commentContent, lor.overall_rating AS score, lor.created_time AS commentDate, " +
            "CONVERT(lor.review_images USING utf8mb4) COLLATE utf8mb4_unicode_ci AS imgId, 2 AS src " +
            "FROM lawyer_order_review lor " +
            "WHERE lor.delete_flag = 0 AND lor.user_id = #{userId} " +
            ") t ORDER BY t.commentDate DESC")
    IPage<LifeUserOrderCommentVo> getUserAllCommentsPage(IPage<LifeUserOrderCommentVo> page, @Param("userId") Integer userId);
}
