package cn.service.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import cn.common.exception.BaseException;
import cn.constant.CommonConst;
import cn.orm.abs.ICommonAPI;
import cn.pojo.entity.TSysDept;
import cn.pojo.entity.TSysUser;
import cn.pojo.vo.LoginUser;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import cn.util.http.IpKit;
import cn.util.core.ServletKit;
import cn.util.string.JsonKit;
import cn.util.time.TimeKit;
import java.util.HashMap;
import java.util.Map;

/**
 * 创建用于认证的用户对象。
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService 
{
	@Autowired
	private ICommonAPI sysBaseService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 
	{
		//依据页面传来的用户账号获取该用户所在部门信息
		TSysUser entity = sysBaseService.getUserByName(username);
		
		if (IsKit.isNullOrEmpty(entity)) {
			LogKit.info("登录用户：{} 不存在.", username);
			throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
		} 
		else if (CommonConst.CHAR_NUM_1.equals(entity.getDelFlag())) {
			LogKit.info("登录用户：{} 已被删除.", username);
			throw new BaseException("对不起，您的账号：" + username + " 已被删除");
		} 
		else if (CommonConst.CHAR_NUM_1.equals(entity.getStatus())) {
			LogKit.info("登录用户：{} 已被停用.", username);
			throw new BaseException("对不起，您的账号：" + username + " 已停用");
		}
			
		return createLoginUser(entity);
	}
	private UserDetails createLoginUser(TSysUser userEntity)
	{
		Map<String, Object> userMap = new HashMap<>();
		if (IsKit.isNotNull(userEntity)){
			userMap = JsonKit.entityToMap(userEntity);
			//添加部门信息
			TSysDept deptEntity = sysBaseService.getDeptByName(userEntity.getUserName());
			userMap.put("dept", deptEntity);
			// 请求的地址
			String ip = IpKit.getIpAddr(ServletKit.getRequest());
			userMap.put("ip",ip);
			userMap.put("loginDate",TimeKit.getNowLocalDateTime());
		}
		return new LoginUser(userMap);
		/**按钮权限btnPerms
		List<Map<String, Object>> btnPermList = userSecurity.selectBtnPermsGroup(TypeUtil.objToStr(userMap.get("roleIds")));
		 */
		/**roles多角色组 格式：el-select [1,2]
		List<Map<String, Object>> rolesList = userSecurity.selectUserRoleGroup(TypeUtil.objToStr(userMap.get("roleIds")));
		*/
		/**posts多岗位：格式：el-select [1,2]
		List<Map<String, Object>> postsList = userSecurity.selectUserPostGroup(TypeUtil.objToStr(userMap.get("postIds"))); 
		return new UserDetailsImpl(userMap,btnPermList,rolesList,postsList);
		*/
	}
}
