package com.palmnest.application.core.util;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.palmnest.application.CodeConstants;

public class SupperAppUtils {


	private static Logger LOG = Logger.getLogger(SupperAppUtils.class);

	/**
	 * 获得点击超级app携带的 cookie(由登录返回的
	 */
	public static String getSuperDeskToten(HttpServletRequest request) {


		String token = "";
		try {

			Cookie[] Cookies = request.getCookies();
			if (null != Cookies) {
				for (int i = 0; i < Cookies.length; i++) {
					Cookie cookie = Cookies[i];
					LOG.info("getSuperDeskToten cookie " + cookie.getName() + "===:" + cookie.getValue() + "===");
					if (StringUtils.isNotEmpty(cookie.getName()) && cookie.getName().equals("superDesk")) {
						token = cookie.getValue();
						continue;
					}

				}
			}
			token = GenPass.Decrypt(URLDecoder.decode(token, "UTF-8"));
			return token;
		} catch (UnsupportedEncodingException e) {
			LOG.error(LogExceptionStackUtil.LogExceptionStack(e));
		}

		return token;

	}

	public static String getOpenIdByToken(String token) {
		LOG.info("getOpenIdByToken token ===" + token);

		String userId = "";
		if (StringUtils.isNotEmpty(token)) {
			String[] tokens = token.split("\\|");
			if (null != tokens && tokens.length >= 1) {
				userId = tokens[0];
			}
		}
		//String sso_codeData=appuser.getId()+"|"+userid +"|"+datatimeStr;		
		LOG.info("getOpenIdByToken openId ===" + userId);
		return userId;
	}
	
	
	public static String getUserIdByToken(String token) {
		LOG.info("getUserIdByToken token ===" + token);

		String userId = "";
		if (StringUtils.isNotEmpty(token)) {
			String[] tokens = token.split("\\|");
			//o9oSq05mqu2rywbH3-ai5SrGneNU|1620809658567|weChat|55748
			LOG.info("getUserIdByToken tokens.length ===" + tokens.length);
			if (null != tokens && tokens.length >= 4 ) {
				userId = tokens[3];
			}
		}
		//String sso_codeData=appuser.getId()+"|"+userid +"|"+datatimeStr;		
		LOG.info("getUserIdByToken userId ===" + userId);
		return userId;
	}

	public static String getToKenTypeByToken(String token) {
		LOG.info("getUserIdByToken token ===" + token);

		String toKenType = CodeConstants.CLIENT_PC;
		if (StringUtils.isNotEmpty(token)) {
			String[] tokens = token.split("\\|");
			if (null != tokens && tokens.length >= 1) {
				if (tokens.length >= 2) {
					toKenType = tokens[2];
				}
			}
		}
		//String sso_codeData=appuser.getId()+"|"+userid +"|"+datatimeStr;		
		LOG.info("getUserIdByToken toKenType ===" + toKenType);
		return toKenType;
	}
	
	public static void main(String[] args) {
		String s="o9oSq05mqu2rywbH3-ai5SrGneNU|1620809658567|weChat";
		String[] tokens = s.split("\\|");
		System.out.println(tokens.length);
		if (null != tokens && tokens.length >= 4 ) {
			System.out.println(tokens[3]);
		}
	}
}
