package com.mosquito.project.permission;

import com.mosquito.project.permission.entity.SysUserEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 系统用户Repository
 */
@Repository
public interface UserRepository extends JpaRepository<SysUserEntity, Long> {

    Optional<SysUserEntity> findByUsername(String username);

    boolean existsByUsername(String username);

    List<SysUserEntity> findByStatus(String status);

    Page<SysUserEntity> findByStatus(String status, Pageable pageable);

    @Query("SELECT u FROM SysUserEntity u WHERE " +
           "(:status IS NULL OR u.status = :status) AND " +
           "(:keyword IS NULL OR u.realName LIKE %:keyword% OR u.email LIKE %:keyword% OR u.phone LIKE %:keyword%)")
    Page<SysUserEntity> searchUsers(
            @Param("status") String status,
            @Param("keyword") String keyword,
            Pageable pageable);

    /**
     * 数据权限过滤查询 - 根据用户ID和部门ID列表查询
     */
    @Query("SELECT u FROM SysUserEntity u WHERE " +
           "(:status IS NULL OR u.status = :status) AND " +
           "(:keyword IS NULL OR u.realName LIKE %:keyword% OR u.email LIKE %:keyword% OR u.phone LIKE %:keyword%) AND " +
           "(:userId IS NULL OR u.id = :userId OR u.departmentId IN :departmentIds)")
    Page<SysUserEntity> searchUsersWithDataScope(
            @Param("status") String status,
            @Param("keyword") String keyword,
            @Param("userId") Long userId,
            @Param("departmentIds") List<Long> departmentIds,
            Pageable pageable);

    /**
     * 查询指定部门下的用户（排除已禁用的）
     */
    List<SysUserEntity> findByDepartmentIdAndStatusNot(Long departmentId, String status);

    /**
     * 分页查询黑名单用户
     */
    Page<SysUserEntity> findByIsBlacklisted(Boolean isBlacklisted, Pageable pageable);

    /**
     * 分页查询黑名单用户（带关键词搜索）
     */
    @Query("SELECT u FROM SysUserEntity u WHERE " +
           "u.isBlacklisted = true AND " +
           "(:keyword IS NULL OR u.realName LIKE %:keyword% OR u.email LIKE %:keyword% OR u.phone LIKE %:keyword%)")
    Page<SysUserEntity> searchBlacklist(
            @Param("keyword") String keyword,
            Pageable pageable);
}
