package org.dromara.wflow.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.dromara.wflow.bean.do_.DeptDo;
import org.dromara.wflow.bean.do_.UserDo;
import org.dromara.wflow.bean.entity.SysUser;
import org.dromara.wflow.bean.vo.OrgTreeVo;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Set;

/**
 * @author : willian fu
 * @date : 2022/6/27
 */
@Mapper
public interface WflowSysUserMapper extends BaseMapper<SysUser> {
    /**
     * 查询该部门下的所有用户
     * @param deptId 部门ID
     * @return 用户列表 type为固定值user
     */
    @Select("SELECT user_id id, nick_name `name`, 'user' AS 'type', avatar " +
            "FROM sys_user WHERE del_flag = 0 AND dept_id = #{deptId}")
    List<OrgTreeVo> selectUsersByDept(@Param("deptId") String deptId);
    /**
     * 通过用户名搜索用户，名称,昵称模糊搜索
     * @param userName
     * @return 搜索的用户列表 type为固定值user
     */
    @Select("SELECT ou.user_id id, ou.user_name `name`, 'user' AS 'type', ou.avatar FROM sys_user ou " +
            "WHERE ou.user_name LIKE '%${userName}%' or ou.nick_name LIKE '%${userName}%' ")
    List<OrgTreeVo> selectUsersByPy(@Param("userName") String userName);



    /**
     * 通过用户名搜索用户，名称,昵称模糊搜索
     * @param userName
     * @return 搜索的用户列表 type为固定值user
     */
    @Select("SELECT user_id FROM sys_user ou " +
            "WHERE ou.user_name LIKE '%${userName}%' or ou.nick_name LIKE '%${userName}%' ")
    List<Long> selectUsersLike(@Param("userName") String userName);

    /**
     * 查询指定用户所在的部门，一个用户可能同时在多个部门下
     *
     * @param userId 用户ID
     * @return 用户所在的部门列表
     */
    @Select("SELECT su.dept_id id, sd.dept_name FROM sys_user su, sys_dept sd " +
            "WHERE su.del_flag = 0 AND sd.del_flag = 0 AND su.dept_id = sd.dept_id AND su.user_id = #{userId}")
    List<DeptDo> getUserDepts(@Param("userId") String userId);


    /**
     * 查询该部门下的所有用户
     * @param deptId 部门ID
     * @return 用户列表 type为固定值user
     */
//    @Select("SELECT user_id FROM sys_user  WHERE del_flag = 0 AND dept_id = #{deptId} and ")
    @Select("<script>" +
            " SELECT u.user_id " +
            " FROM sys_user u right join sys_user_role ur on u.user_id = ur.user_id " +
            " left join sys_role r on ur.role_id = r.role_id " +
            " WHERE u.del_flag = 0 AND u.dept_id = #{deptId} and r.role_key in " +
            "<foreach item = 'roleid' collection = 'roles' index = 'index' open = '(' separator = ',' close = ')'>" +
            "#{roleid}" +
            "</foreach>" +
            "</script>")
    Set<String> selectUsersByDeptRoles(@Param("deptId") String deptId, @Param("roles") List<String> roles);
}
