package cn.wise.sc.acquisition.business.service.impl;

import cn.wise.im.common.http.R;
import cn.wise.sc.acquisition.business.constant.Rcode;
import cn.wise.sc.acquisition.business.entity.*;
import cn.wise.sc.acquisition.business.mapper.TSysDeptMapper;
import cn.wise.sc.acquisition.business.mapper.TSysPowerMapper;
import cn.wise.sc.acquisition.business.mapper.TSysRoleMapper;
import cn.wise.sc.acquisition.business.mapper.TSysUserMapper;
import cn.wise.sc.acquisition.business.model.LoginUser;
import cn.wise.sc.acquisition.business.service.ITSysUserService;
import cn.wise.sc.acquisition.business.util.JwtUtil;
import cn.wise.sc.acquisition.business.util.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ztw
 * @since 2021-04-22
 */
@Service
public class TSysUserServiceImpl extends ServiceImpl<TSysUserMapper, TSysUser> implements ITSysUserService {

	@Resource
	private TSysUserMapper userMapper;

	@Resource
	private TSysRoleMapper roleMapper;
	@Resource
	private TSysDeptMapper deptMapper;
	@Resource
	private TSysPowerMapper powerMapper;


	@Resource
	private HttpServletRequest request;
	@Autowired
	RedisUtil redisUtil;

	/**
	 * 当前登录用户
	 *
	 * @return
	 */
	@Override
	public R getLoginUser() {
		String token = request.getHeader("Authorization");
		System.out.println("==================当前登录用户的Authorization===================");
		System.out.println(token);
		Map map = null;
		try {
			map = JwtUtil.parserToken(token);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Object obj = redisUtil.getString(map.get("id").toString());
		Rcode.NOT_REDIS.assertNotNull(obj);
		TSysUser sysUser = userMapper.selectById(Integer.valueOf(map.get("id").toString()));
		LoginUser loginUser = new LoginUser();
		BeanUtils.copyProperties(sysUser, loginUser);
		//角色
		TSysRole role = roleMapper.selectById(sysUser.getRoleID());
		Rcode.NOT_FOUND.assertNotNull(role);
		loginUser.setRoleName(role.getName());
		//部门
		TSysDept dept = deptMapper.selectById(sysUser.getDeptID());
		Rcode.NOT_FOUND.assertNotNull(dept);
		loginUser.setDeptName(dept.getName());
		//功能权限
		List<TSysPower> powerList = powerMapper.getPowerByRole(role.getId());
		loginUser.setPowerList(powerList);
		return R.ok(loginUser);
	}





}
