package shop.alien.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import shop.alien.entity.second.vo.SecondGoodsRecommendVo;
import shop.alien.entity.store.LifeCollect;

import java.util.List;

/**
 * 收藏
 */
@Mapper
public interface LifeCollectMapper extends BaseMapper<LifeCollect> {

    /**
     * 获取收藏的二级商品
     * @param page
     * @param userId
     * @param collectUserType 收藏人 user_id_user_type
     * @param collectRefId 收藏人 user_id_ref_id
     * @param position 经纬度
     * @return
     */
    @Select("<script>" +
            "SELECT " +
            "  sg.id, " +
            "  sg.user_id, " +
            "  sg.title, " +
            "  sg.price, " +
            "  sg.price AS amount, " +
            "  sg.home_image, " +
            "  sg.video_first_frame, " +
            "  sg.collect_count, " +
            "  lc.created_time, " +
            // 距离计算字段（你原有的逻辑）
            "  ROUND(ST_Distance_Sphere(ST_GeomFromText(CONCAT('POINT(', REPLACE(#{position}, ',', ' '), ')' )), ST_GeomFromText(CONCAT('POINT(', REPLACE(sg.position, ',', ' '), ')' ))) / 1000, 2) AS dist " +
            "FROM second_goods sg " +
            // 内连接：只查询【当前用户】收藏的商品
            "INNER JOIN life_collect lc " +
            "  ON lc.business_id = sg.id " +
            "  AND lc.business_type = 1 " +
            "  AND lc.delete_flag = 0 " +
            "  AND lc.user_id_user_type = #{collectUserType} " +
            "  AND lc.user_id_ref_id = #{collectRefId} " +
            "WHERE sg.delete_flag = 0 " +
            // 动态排除屏蔽商品（空集合不拼接，避免SQL报错）
            "<if test=\"shieldedGoodsIds != null and !shieldedGoodsIds.isEmpty()\">" +
            "  AND sg.id NOT IN " +
            "  <foreach collection='shieldedGoodsIds' item='id' open='(' separator=',' close=')'>" +
            "    #{id}" +
            "  </foreach>" +
            "</if>" +
            "GROUP BY sg.id " +
            // 按收藏时间倒序排序
            "ORDER BY lc.created_time DESC" +
            "</script>")
    IPage<SecondGoodsRecommendVo> collectSecondGoodsByPage(IPage<SecondGoodsRecommendVo> page, @Param("userId") Integer userId, @Param("collectUserType") Integer collectUserType, @Param("collectRefId") Integer collectRefId, @Param("position") String position, @Param("shieldedGoodsIds") List<Integer> shieldedGoodsIds);
}