package com.xkrs.dao;

import com.xkrs.model.entity.SysRoleEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * SysRoleDao
 * @author tajochen
 */
public interface SysRoleDao extends JpaRepository<SysRoleEntity,Integer> {

    /**
     * 查询用户角色列表根据用户id
     * @param id
     * @return
     */
    @Query(value = "SELECT sys_role.id,sys_role.role_name,sys_role.role_name_zh,sys_role.role_desc " +
            "FROM sys_role,rel_user_role " +
            "WHERE sys_role.id = rel_user_role.role_id " +
            "AND rel_user_role.user_id = :id ", nativeQuery = true)
    List<SysRoleEntity> selectByUserId(@Param("id") Integer id);

    /**
     * 查询用户角色列表根据用户名
     * @param userName
     * @return
     */
    @Query(value = "SELECT sys_role.id,sys_role.role_name,sys_role.role_name_zh,sys_role.role_desc " +
            "FROM sys_role.ID = rel_user_role.role_id  " +
            "WHERE rel_user_role.user_id = sys_user.id " +
            "AND rel_user_role.user_id = sys_user.id " +
            "AND sys_user.user_name = :userName ", nativeQuery = true)
    List<SysRoleEntity> selectByUserName(@Param("userName") String userName);


//    /**
//     * 根据用户名修改用户角色
//     */
//    @Modifying
//    @Query(value = "UPDATE sys_user SET last_entry_time = now(), last_entry_ip = :ipAddress " +
//            "WHERE user_name = :userName ;", nativeQuery = true)
//    int updateUserRoleByUserName(@Param("userName") String userName);

    /**
     * 添加用户角色根据用户名和角色名
     * @param userName
     * @param roleName
     * @return
     */
    @Modifying
    @Query(value = "INSERT INTO rel_user_role (id,role_id, user_id) " +
            "SELECT nextval('rel_user_role_seq'),sys_role.ID,sys_user.ID FROM sys_role,sys_user " +
            "WHERE sys_role.role_name = :roleName AND sys_user.user_name = :userName ", nativeQuery = true)
    int insertRelUserRole(@Param("userName") String userName, @Param("roleName") String roleName);
}
