package xiaoqu.home.open.utils;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import xiaoqu.home.open.constant.Constants;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.service.db1.UserService;

/**************
 * 获取当前用户信息
 * 
 * @author wh 2019年3月7日
 */
@Component
public class UserUtils {
	private static RedisTemplate<String, String> redisTemplate4;
	private static RedisTemplate<String, String> redisTemplate5;
	private static UserService userService;
	@Autowired
	public void setUserService(UserService userService) {
		UserUtils.userService = userService;
	}


	@Autowired
	public void setRedisTemplate4(RedisTemplate<String, String> redisTemplate4) {
		UserUtils.redisTemplate4 = redisTemplate4;
	}
	@Autowired
	public void setRedisTemplate5(RedisTemplate<String, String> redisTemplate5) {
		UserUtils.redisTemplate5 = redisTemplate5;
	}

	/*****************
	 * 得到App端客户信息
	 * 
	 * @param request
	 * @return
	 */
	public static User getUser(HttpServletRequest request) {
		String uuid = request.getHeader("uuid");
		// 从redis拿出缓存信息
		String userString = redisTemplate4.opsForValue().get(Constants.pcUuidToUser + uuid);
		if (userString != null) {
			User user = JSON.parseObject(userString, User.class);
			if(user!=null){
				User userRedis = userService.getById(user.getId());
				return userRedis;
			}
			return null;
		} else {
			return null;
		}
	}

	/**********
	 * 删除登录用的uuid
	 * 
	 * @param mobile/账号
	 */
	public static void deleteUUID(String mobile) {
		Object uuid = redisTemplate4.opsForValue().get(Constants.pcMobileToUuid + mobile);
		if (uuid != null) {
			// 如果存在清除掉
			redisTemplate4.delete(Constants.pcUuidToUser + uuid);
			redisTemplate4.delete(Constants.uuidToPcMobile + uuid);
			redisTemplate4.delete(Constants.pcMobileToUuid + mobile);
		}
	}

	/**********
	 * 登录用的uuid
	 * 
	 * @param uuid
	 * @param mobile/账号
	 */
	public static void addUUID(String uuid, String mobile, User sysUser) {
		redisTemplate4.opsForValue().set(Constants.pcUuidToUser + uuid, JSON.toJSONString(sysUser),30,TimeUnit.DAYS);
		redisTemplate4.opsForValue().set(Constants.uuidToPcMobile + uuid, mobile,30,TimeUnit.DAYS);
		redisTemplate4.opsForValue().set(Constants.pcMobileToUuid + mobile, uuid,30,TimeUnit.DAYS);
	}
	
}
