package cn.service.system.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSONObject;
import cn.common.exception.BaseException;
import cn.api.websocket.WebSocket;
import cn.constant.CommonConst;
import cn.constant.CharsetKit;
import cn.facade.constant.SysAnnmentTypeEnum;
import cn.facade.constant.WebsocketConst;
import cn.orm.abs.ISqlToyDao;
import cn.orm.sqltoy.plus.Wrappers;
import cn.orm.sqltoy.plus.query.LambdaQueryWrapper;
import cn.orm.sqltoy.plus.query.QueryWrapper;
import cn.orm.sqltoy.plus.update.LambdaUpdateWrapper;
import cn.orm.sqltoy.plus.update.UpdateWrapper;
import cn.facade.pojo.BusMessageDTO;
import cn.facade.pojo.BusTemplateMessageDTO;
import cn.facade.pojo.MessageDTO;
import cn.facade.pojo.TemplateDTO;
import cn.facade.pojo.TemplateMessageDTO;
import cn.pojo.entity.TSysAnnouncement;
import cn.pojo.entity.TSysAnnouncementSend;
import cn.pojo.entity.TSysDept;
import cn.pojo.entity.TSysPost;
import cn.pojo.entity.TSysRole;
import cn.pojo.entity.TSysRolePerm;
import cn.pojo.entity.TSysSmsTemplate;
import cn.pojo.entity.TSysUser;
import cn.pojo.vo.LoginUser;
import cn.service.system.ISysBaseAPI;
import cn.service.util.UnifyFieldsUtil;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import cn.util.core.TypeKit;
import cn.util.string.StringKit;
import cn.util.time.TimeKit;
/**
 * @Description: 底层共通业务API，提供其他独立模块调用
*/
@Service
public class SysBaseApiImpl implements ISysBaseAPI 
{
	@Autowired
    private WebSocket webSocket;
	@Autowired
	private ISqlToyDao daoService;
	
	@Override
	public String parseTemplateByCode(TemplateDTO templateDTO)
	{
		String templateCode = templateDTO.getTemplateCode();
		Map<String, String> map = templateDTO.getTemplateParam();
		
		QueryWrapper<TSysSmsTemplate> queryWrapper = Wrappers.wrapper(TSysSmsTemplate.class)
                .eq("templateCode", templateCode);
		List<TSysSmsTemplate> sysSmsTemplates = daoService.findList(queryWrapper);
		if(IsKit.isNullOrEmpty(sysSmsTemplates)){
			LogKit.info("消息模板不存在，模板编码："+templateCode);
			return "消息模板不存在";
		}
		TSysSmsTemplate sysSmsTemplate = sysSmsTemplates.get(0);
		//模板内容
		String content = sysSmsTemplate.getTemplateContent();
		if(IsKit.isNotNullOrEmpty(map)) 
		{ 
			for (Map.Entry<String, String> entry : map.entrySet()) {
				String str = "${" + entry.getKey() + "}";
				content = content.replace(str, entry.getValue());
			}
		}
		return content;
	}
	
	@Override
	public void meetingSignWebsocket(String userId) 
	{
		JSONObject obj = new JSONObject();
		obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_SIGN);
		obj.put(WebsocketConst.MSG_USER_ID,userId);
		//TODO目前全部推送，后面修改
		webSocket.sendAllMessage(obj.toJSONString());
	}
	
	@Override
	public void sendTemplateAnnouncement(TemplateMessageDTO message)  
	{
		String templateCode = message.getTemplateCode();
		String title = message.getTitle();
		Map<String,String> map = message.getTemplateParam();
		String fromUser = message.getFromUser();
		String toUser = message.getToUser();

		QueryWrapper<TSysSmsTemplate> queryWrapper = Wrappers.wrapper(TSysSmsTemplate.class)
                .eq("templateCode", templateCode);
		List<TSysSmsTemplate> sysSmsTemplates = daoService.findList(queryWrapper);
		if(IsKit.isNullOrEmpty(sysSmsTemplates)){
			LogKit.info("消息模板不存在，模板编码："+templateCode);
			return;
		}
		TSysSmsTemplate sysSmsTemplate = sysSmsTemplates.get(0);
		//模板标题
		title = IsKit.isNull(title)?sysSmsTemplate.getTemplateName():title;
		//模板内容
		String content = sysSmsTemplate.getTemplateContent();
		if(IsKit.isNotNullOrEmpty(map)) 
		{
			for (Map.Entry<String, String> entry : map.entrySet()) {
				String str = "${" + entry.getKey() + "}";
				title = title.replace(str, entry.getValue());
				content = content.replace(str, entry.getValue());
			}
		}

		TSysAnnouncement announcement = new TSysAnnouncement();
		announcement.setTitile(title);
		announcement.setMsgContent(content);
		announcement.setSender(fromUser);
		announcement.setPriority(CommonConst.PRIORITY_M);
		announcement.setMsgType(CommonConst.MSG_TYPE_UESR);
		announcement.setSendStatus(CommonConst.CHAR_NUM_1);
		announcement.setSendTime(TimeKit.getNowLocalDateTime());
		announcement.setMsgCategory(CommonConst.CHAR_NUM_2);
		announcement.setDelFlag(String.valueOf(CommonConst.CHAR_NUM_0));
		daoService.save(announcement);
		// 2.插入用户通告阅读标记表记录
		String userId = toUser;
		String[] userIds = userId.split(",");
		String anntId = announcement.getId();
		for(int i=0;i<userIds.length;i++) 
		{
			if(IsKit.isNotNullOrEmpty(userIds[i])) {
				TSysUser sysUser = this.getUserByName(userIds[i]);
				if(IsKit.isNull(sysUser)) {
					continue;
				}
				
				TSysAnnouncementSend announcementSend = new TSysAnnouncementSend();
				announcementSend.setAnntId(anntId);
				announcementSend.setUserId(sysUser.getUserName());
				announcementSend.setReadFlag(CommonConst.CHAR_NUM_0);
				daoService.save(announcementSend);
				JSONObject obj = new JSONObject();
				obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
				obj.put(WebsocketConst.MSG_USER_ID, sysUser.getUserName());
				obj.put(WebsocketConst.MSG_ID, announcement.getId());
				obj.put(WebsocketConst.MSG_TXT, announcement.getTitile());
				webSocket.sendOneMessage(sysUser.getUserName(), obj.toJSONString());
			}
		}
	}
	@Override
	public void sendBusTemplateAnnouncement(BusTemplateMessageDTO message)
	{
		String templateCode = message.getTemplateCode();
		String title = message.getTitle();
		Map<String,String> map = message.getTemplateParam();
		String fromUser = message.getFromUser();
		String toUser = message.getToUser();
		String busId = message.getBusId();
		String busType = message.getBusType();

		QueryWrapper<TSysSmsTemplate> queryWrapper = Wrappers.wrapper(TSysSmsTemplate.class)
                .eq("templateCode", templateCode);
		List<TSysSmsTemplate> sysSmsTemplates = daoService.findList(queryWrapper);
		if(IsKit.isNullOrEmpty(sysSmsTemplates)){
			LogKit.info("消息模板不存在，模板编码："+templateCode);
			return;
		}
		
		TSysSmsTemplate sysSmsTemplate = sysSmsTemplates.get(0);
		//模板标题
		title = IsKit.isNull(title)?sysSmsTemplate.getTemplateName():title;
		//模板内容
		String content = sysSmsTemplate.getTemplateContent();
		if(IsKit.isNotNullOrEmpty(map))
		{
			for (Map.Entry<String, String> entry : map.entrySet()) {
				String str = "${" + entry.getKey() + "}";
				title = title.replace(str, entry.getValue());
				content = content.replace(str, entry.getValue());
			}
		}
		TSysAnnouncement announcement = new TSysAnnouncement();
		announcement.setTitile(title);
		announcement.setMsgContent(content);
		announcement.setSender(fromUser);
		announcement.setPriority(CommonConst.PRIORITY_M);
		announcement.setMsgType(CommonConst.MSG_TYPE_UESR);
		announcement.setSendStatus(CommonConst.CHAR_NUM_1);
		announcement.setSendTime(TimeKit.getNowLocalDateTime());
		announcement.setMsgCategory(CommonConst.CHAR_NUM_2);
		announcement.setDelFlag(String.valueOf(CommonConst.CHAR_NUM_0));
		announcement.setBusId(busId);
		announcement.setBusType(busType);
		announcement.setOpenType(SysAnnmentTypeEnum.getByType(busType).getOpenType());
		announcement.setOpenPage(SysAnnmentTypeEnum.getByType(busType).getOpenPage());
		daoService.save(announcement);
		// 2.插入用户通告阅读标记表记录
		String userId = toUser;
		String[] userIds = userId.split(",");
		String anntId = announcement.getId();
		for(int i=0;i<userIds.length;i++) 
		{
			if(IsKit.isNotNullOrEmpty(userIds[i])) {
				TSysUser sysUser = this.getUserByName(userIds[i]);
				if(IsKit.isNull(sysUser)) {
					continue;
				}
				TSysAnnouncementSend announcementSend = new TSysAnnouncementSend();
				announcementSend.setAnntId(anntId);
				announcementSend.setUserId(sysUser.getUserName());
				announcementSend.setReadFlag(CommonConst.CHAR_NUM_0);
				daoService.save(announcementSend);
				JSONObject obj = new JSONObject();
				obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
				obj.put(WebsocketConst.MSG_USER_ID, sysUser.getUserName());
				obj.put(WebsocketConst.MSG_ID, announcement.getId());
				obj.put(WebsocketConst.MSG_TXT, announcement.getTitile());
				webSocket.sendOneMessage(sysUser.getUserName(), obj.toJSONString());
			}
		}
	}	
	
	@Override
	public void updateSysAnnounReadFlag(String busType, String busId) 
	{
		QueryWrapper<TSysAnnouncement> queryWrapper = Wrappers.wrapper(TSysAnnouncement.class)
                .eq("busType", busType)
                .eq("busId", busId);
		TSysAnnouncement announcement = daoService.findOne(queryWrapper);
		if(IsKit.isNotNull(announcement))
		{   //当前登录用户的账号
			String userId = UnifyFieldsUtil.getUserName();
			 LambdaUpdateWrapper<TSysAnnouncementSend> updateWrapper = Wrappers.lambdaUpdateWrapper(TSysAnnouncementSend.class)
		                .set(TSysAnnouncementSend::getReadTime, TimeKit.getNowLocalDateTime())
		                .set(TSysAnnouncementSend::getReadFlag, CommonConst.CHAR_NUM_1)
		               .eq(TSysAnnouncementSend::getAnntId,announcement.getId()) 
		               .eq(TSysAnnouncementSend::getUserId,userId);
			 daoService.update(updateWrapper);
			//TSysAnnouncementSend announcementSend = new TSysAnnouncementSend();
			//daoService.update(announcementSend, updateWrapper);
		}
	}

	@Override
	public void sendSysAnnouncement(MessageDTO message) {
		_sendSysAnnouncement(message.getFromUser(),
				message.getToUser(),
				message.getTitle(),
				message.getContent(),
				message.getCategory());
	}

    /**
	 * 发消息
	 * @param fromUser
	 * @param toUser
	 * @param title
	 * @param msgContent
	 * @param setMsgCategory
	 */
	private void _sendSysAnnouncement(String fromUser, String toUser, String title, String msgContent, String setMsgCategory) 
	{
		TSysAnnouncement announcement = new TSysAnnouncement();
		announcement.setTitile(title);
		announcement.setMsgContent(msgContent);
		announcement.setSender(fromUser);
		announcement.setPriority(CommonConst.PRIORITY_M);
		announcement.setMsgType(CommonConst.MSG_TYPE_UESR);
		announcement.setSendStatus(CommonConst.CHAR_NUM_1);
		announcement.setSendTime(TimeKit.getNowLocalDateTime());
		announcement.setMsgCategory(setMsgCategory);
		announcement.setDelFlag(String.valueOf(CommonConst.CHAR_NUM_0));
		daoService.save(announcement);
		
		// 2.插入用户通告阅读标记表记录
		String userId = toUser;
		String[] userIds = userId.split(",");
		String anntId = announcement.getId();
		for(int i=0;i<userIds.length;i++)
		{
			if(IsKit.isNotNullOrEmpty(userIds[i])) 
			{
				TSysUser sysUser = this.getUserByName(userIds[i]);
				if(IsKit.isNull(sysUser)) {
					continue;
				}
				TSysAnnouncementSend announcementSend = new TSysAnnouncementSend();
				announcementSend.setAnntId(anntId);
				announcementSend.setUserId(sysUser.getUserName());
				announcementSend.setReadFlag(CommonConst.CHAR_NUM_0);
				daoService.save(announcementSend);
				
				JSONObject obj = new JSONObject();
				obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
				obj.put(WebsocketConst.MSG_USER_ID, sysUser.getUserName());
				obj.put(WebsocketConst.MSG_ID, announcement.getId());
				obj.put(WebsocketConst.MSG_TXT, announcement.getTitile());
				webSocket.sendOneMessage(sysUser.getUserName(), obj.toJSONString());
			}
		}
	}
	@Override
	public void sendBusAnnouncement(BusMessageDTO message) 
	{
		_sendBusAnnouncement(message.getFromUser(),
				message.getToUser(),
				message.getTitle(),
				message.getContent(),
				message.getCategory(),
				message.getBusType(),
				message.getBusId());	
	}
	/**
	 * 发消息 带业务参数
	 */
	private void _sendBusAnnouncement(String fromUser, String toUser, String title, String msgContent, String setMsgCategory, String busType, String busId) 
	{
		TSysAnnouncement announcement = new TSysAnnouncement();
		announcement.setTitile(title);
		announcement.setMsgContent(msgContent);
		announcement.setSender(fromUser);
		announcement.setPriority(CommonConst.PRIORITY_M);
		announcement.setMsgType(CommonConst.MSG_TYPE_UESR);
		announcement.setSendStatus(CommonConst.CHAR_NUM_1);
		announcement.setSendTime(TimeKit.getNowLocalDateTime());
		announcement.setMsgCategory(setMsgCategory);
		announcement.setDelFlag(String.valueOf(CommonConst.CHAR_NUM_0));
		announcement.setBusId(busId);
		announcement.setBusType(busType);
		announcement.setOpenType(SysAnnmentTypeEnum.getByType(busType).getOpenType());
		announcement.setOpenPage(SysAnnmentTypeEnum.getByType(busType).getOpenPage());
		daoService.save(announcement);
		// 2.插入用户通告阅读标记表记录
		String userId = toUser;
		String[] userIds = userId.split(",");
		String anntId = announcement.getId();
		for(int i=0;i<userIds.length;i++)
		{
			if(IsKit.isNotNullOrEmpty(userIds[i])){
				TSysUser sysUser = this.getUserByName(userIds[i]);
				if(IsKit.isNull(sysUser)) {
					continue;
				}
				
				TSysAnnouncementSend announcementSend = new TSysAnnouncementSend();
				announcementSend.setAnntId(anntId);
				announcementSend.setUserId(sysUser.getUserName());
				announcementSend.setReadFlag(CommonConst.CHAR_NUM_0);
				daoService.save(announcementSend);
				
				JSONObject obj = new JSONObject();
				obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
				obj.put(WebsocketConst.MSG_USER_ID, sysUser.getUserName());
				obj.put(WebsocketConst.MSG_ID, announcement.getId());
				obj.put(WebsocketConst.MSG_TXT, announcement.getTitile());
				webSocket.sendOneMessage(sysUser.getUserName(), obj.toJSONString());
			}
		}
	}
	
	
	/**依据用户username,查用户信息*/
	@Override
	public TSysUser getUserByName(String username)
	{
		if(IsKit.isNullOrEmpty(username)) {
			return new TSysUser();
		}
		QueryWrapper<TSysUser> queryWrapper = Wrappers.wrapper(TSysUser.class)
				.eq("userName",username)
				.eq("delFlag",CommonConst.CHAR_NUM_0); 
		return daoService.findOne(queryWrapper);			
	}
	
	/**判断当前登录者是否为管理员TRUE*/
	@Override
	public Boolean isAdminByRoleId(String roleId) 
	{
		if (CommonConst.DEFAULT_ADMIN.equals(getRolekey(roleId))){
			return true;
		}
		return false;
	}

	/**查询某角色权限字符串：admin*/
	@Override
	public String getRolekey(String roleId)
	{
		LambdaQueryWrapper<TSysRole> queryWrapper = Wrappers.lambdaWrapper(TSysRole.class)
				.select(TSysRole::getRoleKey)
				.eq(TSysRole::getRoleId, roleId);
		TSysRole entity = daoService.findOne(queryWrapper);
		return entity.getRoleKey();
	}

	/**查询某角色权限表
	 * 返回格式：perm∈component△
	 */
	@Override
	public String getRoleperm(String roleId){

		QueryWrapper<TSysRolePerm> wrapper = Wrappers.wrapper(TSysRolePerm.class)
				.select("component,GROUP_CONCAT(perm SEPARATOR ',') AS perm")
				.eq("roleId",roleId); 
		List<TSysRolePerm> entityList = daoService.findList(wrapper);

		if(IsKit.isNull(entityList)) {
			return null;
		}
		StringBuilder builder = new StringBuilder();
		for(TSysRolePerm entity:entityList) {
			if(builder.length() > 0) {
				builder.append(CharsetKit.SYMBOL_SQL_TRIANGLE);	
			}
			builder.append(entity.getPerm());
			builder.append(CharsetKit.SYMBOL_SEPARATOR);
			builder.append(entity.getComponent());			
		}
		return builder.toString();
	}

	
	/**获取用户的所有角色*/
	@Override
	public List<TSysRole> getUserRole(Map<String,String> loginBody)
	{
		//获取该用户的角色信息LambdaQueryWrapper
		LambdaQueryWrapper<TSysUser> queryUserWrapper = Wrappers.lambdaWrapper(TSysUser.class)
				.select(TSysUser::getRoleIds)
				.eq(TSysUser::getUserId,loginBody.get("userId"));
		TSysUser entity = daoService.findOne(queryUserWrapper);
		if(IsKit.isNullOrEmpty(entity)) {
			return null;
		}
		//el-select multiple 字段值格式:[1,2,3],去除[和]
		String roleId =	StringKit.removeBracket(entity.getRoleIds());
		if(IsKit.isNull(roleId)) {
			return null;
		}
		LambdaQueryWrapper<TSysRole> queryRoleWrapper = Wrappers.lambdaWrapper(TSysRole.class)
				.select(TSysRole::getRoleId)
				.select(TSysRole::getRoleName)
				.in(TSysRole::getRoleId,Arrays.asList(roleId.split(",")));

		return daoService.findList(queryRoleWrapper);
	}

	/**依据username登录账号(具有唯一性)，获取用户所在部门信息*/
	@Override
	public TSysDept getDeptByName(String username)
	{
		LambdaQueryWrapper<TSysUser> queryUserWrapper = Wrappers.lambdaWrapper(TSysUser.class)
				.select(TSysUser::getDeptId)
				.eq(TSysUser::getUserName,username);
		TSysUser userEntity = daoService.findOne(queryUserWrapper);
		return this.getDeptInfo(userEntity.getDeptId());
	}

	/**依据部门Id获取部门信息*/
	@Override
	public TSysDept getDeptInfo(int deptId)
	{
		/**查询部门信息*/
		LambdaQueryWrapper<TSysDept> queryDeptWrapper = Wrappers.lambdaWrapper(TSysDept.class)
				.select(TSysDept::getDeptId)
				.select(TSysDept::getDeptName)
				.select(TSysDept::getStatus)
				.select(TSysDept::getDelFlag)
				.eq(TSysDept::getDeptId,deptId);
		return daoService.findOne(queryDeptWrapper);
	}


	/**依据用户名字,查用户信息 */
	@Override
	public List<TSysUser> getUserListByNames(String[] userNames) 
	{
		QueryWrapper<TSysUser> queryWrapper = Wrappers.wrapper(TSysUser.class)
				.eq("status",CommonConst.CHAR_NUM_0)//0true正常 1停用
				.eq("delFlag",CommonConst.CHAR_NUM_0)//0代表存在  2代表删除
				.in("userName",Arrays.asList(userNames));//2, 3, 4 TypeUtil.arrayToStr?
		List<TSysUser> sysUsers = daoService.findList(queryWrapper);
		return sysUsers;
		/*
		  List<LoginUser> loginUsers = new ArrayList<>();
		  for (TSysUser user: sysUsers) {
			LoginUser loginUser=new LoginUser();
			BeanUtils.copyProperties(user, loginUser);
			loginUsers.add(loginUser);
		}
		return loginUsers;*/
	}


	/**获取给定角色roleId的按钮权限
	 * 登录用户的全部角色roleIds；roleId本次登陆的角色
	 * */
	@Override
	public TSysRolePerm getBtnPerm(String roleIds,String roleId)
	{
		if(IsKit.isNullOrEmpty(roleId) || IsKit.isNullOrEmpty(roleIds)) {
			return null;
		}
		/**按钮权限*/
		List<TSysRolePerm> origList = _getBtnPermsGroup(roleIds);
		if (IsKit.isNullOrEmpty(origList)){
			return null;
		}
		//过滤出符合条件的数据
		List<TSysRolePerm> resultList = origList.stream()
				.filter(entity->(entity.getRoleId())==TypeKit.objToInt(roleId))
				.collect(Collectors.toList());
		if(IsKit.isNotNullOrEmpty(resultList)) {
			return resultList.get(0);
		}
		return null;
	}

	/**获取给定角色roleId的菜单权限和数据范围
	 * 登录用户的全部角色roleIds；roleId本次登陆的角色
	 * */
	@Override
	public TSysRole getMenuPerm(String roleIds,String roleId)
	{
		if(IsKit.isNullOrEmpty(roleId) || IsKit.isNullOrEmpty(roleIds)) {
			return null;
		}
		/**多角色组 格式：el-select [1,2]*/
		List<TSysRole> origList = _getUserRoleGroup(roleIds);
		if (IsKit.isNullOrEmpty(origList)){
			return null;
		}
		//过滤出符合条件的数据
		List<TSysRole> resultList = origList.stream()
				.filter(entity->(entity.getRoleId())==TypeKit.objToInt(roleId))
				.collect(Collectors.toList());
		if(IsKit.isNotNullOrEmpty(resultList)) {
			return resultList.get(0);
		}
		return null;
	}	

	/**查询用户所有角色的权限信息*/
	private List<TSysRole> _getUserRoleGroup(String sourceStr)
	{
		//el-select multiple 字段值格式:[1,2,3],去除[和]
		String targetStr = StringKit.removeBracket(sourceStr);
		LambdaQueryWrapper<TSysRole> queryWrapper = Wrappers.lambdaWrapper(TSysRole.class)
				.in(TSysRole::getRoleId,Arrays.asList(targetStr.split(",")));

		List<TSysRole> entityList = daoService.findList(queryWrapper);
		return entityList;
	}
	/**查询用户所有角色的按钮权限信息*/
	//@Override
	private List<TSysRolePerm> _getBtnPermsGroup(String sourceStr)
	{
		String targetStr = StringKit.removeBracket(sourceStr);
		LambdaQueryWrapper<TSysRolePerm> queryWrapper = Wrappers.lambdaWrapper(TSysRolePerm.class)
				.in(TSysRolePerm::getRoleId,Arrays.asList(targetStr.split(",")));

		List<TSysRolePerm> entityList = daoService.findList(queryWrapper);
		return entityList;
	}

	/**查询用户所有角色的岗位信息*/
	public List<TSysPost> _getUserPostGroup(String sourceStr)
	{
		String targetStr = StringKit.removeBracket(sourceStr);
		LambdaQueryWrapper<TSysPost> queryWrapper = Wrappers.lambdaWrapper(TSysPost.class)
				.in(TSysPost::getPostId,Arrays.asList(targetStr.split(",")));
		List<TSysPost> entityList = daoService.findList(queryWrapper);
		return entityList;
	}

	@Override
	public Boolean resetUserPwd(int userId, String password)
	{
		UpdateWrapper<TSysUser> updateWrapper = Wrappers.updateWrapper(TSysUser.class)
				.set("password",password)
				.eq("userId",userId);
		return daoService.update(updateWrapper) > 0 ? true:false;
	}
	/**
	 * 修改用户头像
	 * @param userId 用户Id
	 * @param avatar 头像地址
	 */
	@Override
	public Boolean updateUserAvatar(int userId, String avatar) 
	{
		UpdateWrapper<TSysUser> updateWrapper = Wrappers.updateWrapper(TSysUser.class)
				.set("avatar", avatar)
				.eq("userId",userId);
		return daoService.update(updateWrapper) > 0 ? true:false;
	}
	/**获取用户*/
	@Override
	public LoginUser getLoginUser() {
		try {
			return (LoginUser) getAuthentication().getPrincipal();
		} catch (Exception e) {
			throw new BaseException("获取用户信息异常");
		}
	}

	/**获取Authentication*/
	@Override
	public Authentication getAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}
}
