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 org.apache.ibatis.annotations.Update;
import shop.alien.entity.store.StoreCommentAppeal;
import shop.alien.entity.store.vo.StoreCommentAppealVo;

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

/**
 * 评论申诉表 Mapper 接口
 *
 * @author ssk
 * @since 2025-01-02
 */
public interface StoreCommentAppealMapper extends BaseMapper<StoreCommentAppeal> {

    /**
     * 申诉历史-分页查询
     * 注意：comment_id 关联的是 common_rating.id（评价ID），不是 store_comment.id
     * 注意：common_rating 表不加 delete_flag = 0 条件，以便申诉通过后仍能显示评价快照数据
     *
     * @param page         分页参数
     * @param queryWrapper 查询条件
     * @return IPage<StoreCommentAppealVo>
     */
    @Select("select a.*, b.dict_detail appeal_status_str, c.content comment_content, c.score comment_star, c.score score, c.other_score, c.is_anonymous, c.image_urls commentImgId, d.user_name, d.user_image, e.store_name, f.phone store_phone, f.name store_contact, e.store_type " +
            "from store_comment_appeal a " +
            "left join store_dictionary b on a.appeal_status = b.dict_id and b.type_name = 'appealStatus' and b.delete_flag = 0 " +
            "left join common_rating c on a.comment_id = c.id " +
            "left join life_user d on c.user_id = d.id and d.delete_flag = 0 " +
            "left join store_info e on a.store_id = e.id and e.delete_flag = 0 " +
            "Left join store_user f on e.id = f.store_id and f.delete_flag = 0 ${ew.customSqlSegment}")
    IPage<StoreCommentAppealVo> getStoreCommentAppealPage(IPage<StoreCommentAppealVo> page, @Param(Constants.WRAPPER) QueryWrapper<StoreCommentAppealVo> queryWrapper);

    /**
     * 申诉历史-全部查询
     * 注意：comment_id 关联的是 common_rating.id（评价ID），不是 store_comment.id
     * 注意：common_rating 表不加 delete_flag = 0 条件，以便申诉通过后仍能显示评价快照数据
     *
     * @param queryWrapper 查询条件
     * @return List<StoreCommentAppealVo>
     */
    @Select("select a.*, b.dict_detail appeal_status_str, c.content comment_content, c.score comment_star, d.user_name, d.user_image, e.store_name, f.phone store_phone, f.name store_contact, e.store_type from store_comment_appeal a " +
            "left join store_dictionary b on a.appeal_status = b.dict_id and b.type_name = 'appealStatus' and b.delete_flag = 0 " +
            "left join common_rating c on a.comment_id = c.id " +
            "left join life_user d on c.user_id = d.id and d.delete_flag = 0 " +
            "left join store_info e on a.store_id = e.id and e.delete_flag = 0 " +
            "Left join store_user f on e.id = f.store_id and f.delete_flag = 0 ${ew.customSqlSegment}")
    List<StoreCommentAppealVo> getStoreCommentAppealList(@Param(Constants.WRAPPER) QueryWrapper<StoreCommentAppealVo> queryWrapper);

    /**
     * 申诉详情
     * 注意：comment_id 关联的是 common_rating.id（评价ID），不是 store_comment.id
     * 注意：common_rating 表不加 delete_flag = 0 条件，以便申诉通过后仍能显示评价快照数据
     *
     * @param queryWrapper 查询条件
     * @return StoreCommentAppealVo
     */
    @Select("select a.*, b.dict_detail appeal_status_str, c.content comment_content, c.score, c.other_score, a.created_time comment_time, c.score comment_star, c.is_anonymous, c.image_urls commentImgId, d.user_name, e.phone store_phone, d.user_name userName, d.user_image userImage " +
            "from store_comment_appeal a " +
            "left join store_dictionary b on a.appeal_status = b.dict_id and b.type_name = 'appealStatus' and b.delete_flag = 0 " +
            "left join common_rating c on a.comment_id = c.id " +
            "left join life_user d on c.user_id = d.id and d.delete_flag = 0 " +
            "left join store_user e on a.store_id = e.store_id and e.delete_flag = 0 ${ew.customSqlSegment}")
    StoreCommentAppealVo getCommentDetail(@Param(Constants.WRAPPER) QueryWrapper<StoreCommentAppealVo> queryWrapper);


    /**
     * 申诉列表（平台端使用）
     * 注意：comment_id 关联的是 common_rating.id（评价ID），不是 store_comment.id
     * 注意：common_rating 表不加 delete_flag = 0 条件，以便申诉通过后仍能显示评价快照数据
     *
     * @return List<Map < String, Object>>
     */
    @Select("SELECT sca.id, sca.appeal_reason, sca.appeal_status, cr.content comment_content, si.img_url, cr.image_urls user_img_url, cr.id comment_id, cr.business_id " +
            "FROM store_comment_appeal sca " +
            "LEFT JOIN common_rating cr ON sca.comment_id = cr.id " +
            "LEFT JOIN store_img si ON sca.img_id = si.id " +
            "WHERE sca.appeal_status = 0 and record_id is null AND sca.delete_flag = 0")
    List<Map<String, Object>> getAppealList();

    /**
     * 申诉列表：申诉创建时间在当前时间 45～72 小时前（含边界），且待处理、未提交 AI 分析，每次最多 10 条
     */
    @Select("SELECT sca.id, sca.appeal_reason, sca.appeal_status, cr.content comment_content, si.img_url, cr.image_urls user_img_url, cr.id comment_id, cr.business_id " +
            "FROM store_comment_appeal sca " +
            "LEFT JOIN common_rating cr ON sca.comment_id = cr.id " +
            "LEFT JOIN store_img si ON sca.img_id = si.id " +
            "WHERE sca.appeal_status = 0 AND sca.record_id IS NULL AND sca.delete_flag = 0 " +
            "AND sca.created_time <= DATE_SUB(NOW(), INTERVAL 5 MINUTE) " +

//            "AND sca.created_time >= DATE_SUB(NOW(), INTERVAL 72 HOUR) " +
//            "AND sca.created_time <= DATE_SUB(NOW(), INTERVAL 45 HOUR) " +
            "ORDER BY sca.created_time ASC " +
            "LIMIT 10")
    List<Map<String, Object>> getAppealListBetween45And72Hours();


    @Select("SELECT sca.id, sca.appeal_status, sca.final_result, sca.comment_id, sca.record_id, sca.store_id " +
            "FROM store_comment_appeal sca " +
            "WHERE sca.appeal_status = 0 AND sca.record_id IS NOT NULL AND sca.delete_flag = 0")
    List<StoreCommentAppeal> getPendingAppeals();

    /**
     * 用户补充申诉-AI 分析结果轮询列表：处理中、已提交 record_id、存在用户补充，每次最多 10 条
     */
    @Select("SELECT sca.id, sca.appeal_status, sca.final_result, sca.comment_id, sca.record_id, sca.store_id " +
            "FROM store_comment_appeal sca " +
            "WHERE sca.appeal_status = 3 AND sca.record_id IS NOT NULL AND sca.delete_flag = 0 " +
            "ORDER BY sca.updated_time ASC " +
            "LIMIT 10")
    List<StoreCommentAppeal> getSupplementPendingAppeals();

    @Update("UPDATE store_comment_appeal " +
            "SET appeal_status = #{appealStatus}, final_result = #{finalResult} " +
            "WHERE record_id = #{recordId}")
    void updateByRecordId(@Param("recordId") Integer recordId,
                          @Param("appealStatus") Integer appealStatus,
                          @Param("finalResult") String finalResult);


    @Update("UPDATE store_comment_appeal " +
            "SET appeal_status = #{appealStatus}, final_result = #{finalResult} " +
            "WHERE id = #{id}")
    void updateByRecordIdNew(@Param("id") Integer id,
                          @Param("appealStatus") Integer appealStatus,
                          @Param("finalResult") String finalResult);

    /**
     * 查询用户近30天评价被申诉通过的记录，按通过时间倒序（最新在前）
     */
    @Select("select *\n" +
            "from store_comment_appeal sca\n" +
            "where sca.comment_id in (select id from common_rating cr where cr.user_id=#{userId} and cr.business_type = 1)\n" +
            "and sca.appeal_status = 2\n" +
            "and sca.delete_flag = 0\n" +
            "and sca.created_time >= DATE_SUB(NOW(), INTERVAL 30 DAY)\n" +
            "order by sca.updated_time desc")
    List<StoreCommentAppeal> canRate(@Param("userId") Integer userId);
}
