package com.zcloud.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zcloud.common.utils.DateUtil;
import com.zcloud.common.utils.R;
import com.zcloud.modules.sys.dao.SysUserTokenDao;
import com.zcloud.modules.sys.entity.SysUserTokenEntity;
import com.zcloud.modules.sys.oauth2.TokenGenerator;
import com.zcloud.modules.sys.service.SysUserTokenService;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
	//shiro失效时间一星期 1800*24 12小时
	private final static int EXPIRE = 1800 * 24 * 14;


	@Override
	public R createToken(String userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

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

		//判断是否生成过token
		SysUserTokenEntity tokenEntity = this.getById(userId);
		if(tokenEntity == null){
			tokenEntity = new SysUserTokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//保存token
			this.save(tokenEntity);
		}else{
			if(tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) { // 登录失效时更新新token
				tokenEntity.setToken(token);
			}
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			this.updateById(tokenEntity);
		}

		R r = R.ok().put("token", tokenEntity.getToken()).put("expire", EXPIRE);

		return r;
	}

	@Override
	public void logout(String userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

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

	@Override
	public void refreshToken(String userId){
		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		SysUserTokenEntity tokenEntity = this.getById(userId);

		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(expireTime);

		//更新token
		this.updateById(tokenEntity);
	}
}
