package shop.alien.mapper.second;

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.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import shop.alien.entity.second.SecondEntrustUser;
import shop.alien.entity.second.vo.SecondEntrustUserResultVo;

import java.util.List;

/**
 * <p>
 * 二手委托人信息表 Mapper 接口
 * </p>
 *
 * @author ssk
 * @since 2025-11-21
 */
@Mapper
public interface SecondEntrustUserMapper extends BaseMapper<SecondEntrustUser> {

    /**
     * 分页查询委托人信息列表（以姓名+身份证号为维度分组）
     *
     * @param page 分页对象
     * @param wrapper 查询条件
     * @return 委托人信息分页列表
     */
    @Select("select " +
            "  MIN(entrust.id) as id, " +
            "  entrust.entrust_user_name as entrustUserName, " +
            "  entrust.entrust_id_card as entrustIdCard, " +
            "  entrust.entrust_user_phone as entrustUserPhone, " +
            "  entrust.entrust_id_card_img as entrustIdCardImg, " +
            "  COUNT(DISTINCT entrust.id) as entrustCount, " +
            "  COUNT(DISTINCT entrust.entrust_trade_id) as tradeCount, " +
            "  MAX(entrust.created_time) as latestEntrustTime " +
            "from second_entrust_user entrust " +
            "left join second_trade_record trade on trade.id = entrust.entrust_trade_id " +
            "${ew.customSqlSegment} " +
            "group by entrust.entrust_user_name, entrust.entrust_id_card " +
            "order by latestEntrustTime desc")
    IPage<SecondEntrustUserResultVo> getEntrustUserPage(IPage<SecondEntrustUser> page, 
                                                         @Param(Constants.WRAPPER) QueryWrapper<SecondEntrustUser> wrapper);

    /**
     * 根据姓名和身份证号查询所有委托记录
     *
     * @param entrustUserName 姓名
     * @param entrustIdCard 身份证号
     * @return 委托记录列表
     */
    @Select("select * from second_entrust_user " +
            "where entrust_user_name = #{entrustUserName} " +
            "and entrust_id_card = #{entrustIdCard} " +
            "and delete_flag = 0 " +
            "and id = #{id} " +
            "order by created_time desc")
    List<SecondEntrustUser> getByUserNameAndIdCard(@Param("entrustUserName") String entrustUserName, 
                                                     @Param("entrustIdCard") String entrustIdCard,
                                                    @Param("id") Integer id
    );

}


