package com.iformall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.domain.po.SysUserToken;
import com.iformall.mapper.MallUserInfoMapper;
import com.iformall.mapper.SysUserTokenMapper;
import com.iformall.service.SysUserTokenService;
import com.iformall.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;


@Service("sysUserTokenService")
public class SysUserTokenServiceImpl implements SysUserTokenService {

	@Autowired
	SysUserTokenMapper sysUserTokenMapper;

	@Autowired
	MallUserInfoMapper mallUserInfoMapper;


	@Override
	public SysUserToken createToken(long userId, String tenantId) {
		//生成一个token
		String token = UUID.randomUUID().toString();

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + Constant.EXPIRE);

		//判断是否生成过token
		SysUserToken q = new SysUserToken();
		q.setUserId(userId);
		q.setTenantId(tenantId);
		SysUserToken tokenEntity = sysUserTokenMapper.selectOne(new QueryWrapper<>(q));
		if(tokenEntity == null){
			tokenEntity = new SysUserToken();
			tokenEntity.setUserId(userId);
			tokenEntity.setTenantId(tenantId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//保存token
			sysUserTokenMapper.insert(tokenEntity);
		}else{
			if (tokenEntity.getExpireTime().before(now)) {
				tokenEntity.setToken(token);
				tokenEntity.setUpdateTime(now);
				tokenEntity.setExpireTime(expireTime);
				//更新token
				sysUserTokenMapper.updateById(tokenEntity);
			}
		}
		return tokenEntity;
	}

	@Override
	public void logout(long userId) {
		//生成一个token
		String token = UUID.randomUUID().toString();

		//修改token
		SysUserToken tokenEntity = new SysUserToken();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		sysUserTokenMapper.updateById(tokenEntity);
	}

	@Override
	public SysUserToken queryByToken(String token) {
		return sysUserTokenMapper.queryByToken(token);
	}

	@Override
	public SysUserToken queryByUserId(long userId) {
		return sysUserTokenMapper.queryByUserId(userId);
	}

	@Override
	public MallUserInfo queryUser(Long userId) {
		return mallUserInfoMapper.selectById(userId);
	}
}
