package com.cab.service;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.cab.controller.SpringBeanUtils;
import com.cab.controller.UserController;
import com.cku.core.ZAException;
import com.cku.util.ServletUtils;
import com.google.gson.Gson;
import com.sys.model.MultiUserProfile;
import com.sys.util.TokenUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class UserService {
	
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	public static String verifyUserId(HttpServletRequest request) throws Exception
	{
		return UserService.verifyTokenObj(request).getUserId();
	}
	
	public static String verifyThirdUserId(HttpServletRequest request) throws Exception
	{
		return UserService.verifyTokenObj(request).getCurrentClubUserId();
	}
	/**
	 * 
	 * @Description：验证token有效性，返回token对象
	 * @author: zhuoHeng
	 * @version: 2017年4月19日 下午4:19:46
	 */
	private static final Gson GSON = new Gson();
	public static MultiUserProfile verifyTokenObj(HttpServletRequest request) throws Exception
	{
		String token = ServletUtils.getParameter(request, "token");
		String club = ServletUtils.getHeader(request, "club");
		if(StringUtils.isBlank(club)) {
			club = ServletUtils.getParameter(request, "club");
		}
		if(StringUtils.isBlank(token)) {
			token = ServletUtils.getHeader(request, "token");
		}
		MultiUserProfile userProfile = new MultiUserProfile();
		try {
			String subject = TokenUtil.parseJwt(token).getSubject();
			logger.info("解析token数据"+subject);
			userProfile = GSON.fromJson(subject,MultiUserProfile.class);
			if("org".equals(userProfile.getClientName())) {
				throw new ZAException(10001,"登录超时，请稍后再试");
			}
			userProfile.setClub(club);
		}
		catch(TokenExpiredException ex) {
			logger.info("================解析token失败，Token过期================" + ex.getMessage());
			throw new ZAException(10001,"登录超时，请稍后再试");
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		if(!"org".equals(userProfile.getClientName())) {
			//查看token有没有被强制失效
			String redisKey = "token_userid_" + userProfile.getUserId()+ "_" + "system" + "_" + userProfile.getMobile();
			if(!exists(redisKey)) {
				throw new ZAException(10001,"登录超时，请稍后再试");
			}
		}
		return userProfile;
	}
	

	
	public static boolean exists(String key) {
		JedisPool jedisPool = SpringBeanUtils.getBean(JedisPool.class);
		boolean b = false;
		try (Jedis jedis = jedisPool.getResource()) {
			b =  jedis.exists(key);
	    } catch (Exception e) {
	        throw new RuntimeException(e.getMessage(), e);
	    }
		return b;
	}
	
}
