package com.erp.user.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.user.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 用户数据访问接口
 */
@Mapper
public interface UserRepository extends BaseMapper<User> {
    
    /**
     * 根据租户ID和用户名查询用户列表
     */
    @Select("SELECT id, tenant_id AS tenantId, username, email, phone, password_hash AS passwordHash, real_name AS realName, " +
            "status, created_at AS createdAt, updated_at AS updatedAt, deleted_at AS deletedAt " +
            "FROM users WHERE tenant_id = #{tenantId} AND username LIKE CONCAT('%', #{username}, '%') AND deleted_at IS NULL ORDER BY id DESC LIMIT #{limit} OFFSET #{offset}")
    List<User> findByTenantIdAndUsername(@Param("tenantId") Long tenantId, 
                                         @Param("username") String username,
                                         @Param("offset") Long offset,
                                         @Param("limit") Integer limit);
    
    /**
     * 根据用户名查找用户
     */
    @Select("SELECT id, tenant_id AS tenantId, username, email, phone, password_hash AS passwordHash, real_name AS realName, " +
            "status, created_at AS createdAt, updated_at AS updatedAt, deleted_at AS deletedAt " +
            "FROM users WHERE username = #{username} AND deleted_at IS NULL")
    User findByUsername(@Param("username") String username);
    
    /**
     * 根据邮箱查找用户
     */
    @Select("SELECT id, tenant_id AS tenantId, username, email, phone, password_hash AS passwordHash, real_name AS realName, " +
            "status, created_at AS createdAt, updated_at AS updatedAt, deleted_at AS deletedAt " +
            "FROM users WHERE email = #{email} AND deleted_at IS NULL")
    User findByEmail(@Param("email") String email);
    
    /**
     * 根据手机号查找用户
     */
    @Select("SELECT id, tenant_id AS tenantId, username, email, phone, password_hash AS passwordHash, real_name AS realName, " +
            "status, created_at AS createdAt, updated_at AS updatedAt, deleted_at AS deletedAt " +
            "FROM users WHERE phone = #{phone} AND deleted_at IS NULL")
    User findByPhone(@Param("phone") String phone);
    
    /**
     * 统计用户数量
     */
    @Select("SELECT COUNT(*) FROM users WHERE tenant_id = #{tenantId} AND deleted_at IS NULL")
    Long countByTenantId(@Param("tenantId") Long tenantId);
}
