package com.yihu.wlyy.interceptors;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;

import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.SystemData;

/**
 * 公共方法，权限简单校验
 * @author George
 *
 */
public class UserInterceptor extends BaseInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		try {
			response.setCharacterEncoding("UTF-8");
			JSONObject json = getAgent(request);
			if (json == null) {
				// 未登录
				response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作！").getBytes());
				return false;
			}
			// 获取用户token
			String tokenStr = json.has("token") ? json.getString("token") : "";
			String uid = json.has("uid") ? json.getString("uid") : "";
			String imei = json.has("imei") ? json.getString("imei") : "";
			String openid = json.has("openid") ? json.getString("openid") : "";
			if (StringUtils.isEmpty(imei)) {
				imei = openid;
			}
			Token token = null;

			if (SystemData.doctorTokens.containsKey(uid)) {
				token = SystemData.doctorTokens.get(uid);
			} else if (SystemData.patientTokens.containsKey(uid)) {
				token = SystemData.patientTokens.get(uid);
			} else if (SystemData.wxPatientTokens.containsKey(uid)) {
				token = SystemData.wxPatientTokens.get(uid);
			}
			if (token == null) {
				token = tokenDao.findByToken(tokenStr);
				if (token != null) {
					switch (token.getPlatform()) {
					case 1:
						SystemData.patientTokens.put(uid, token);
						break;
					case 2:
						SystemData.doctorTokens.put(uid, token);
						break;
					case 3:
						SystemData.wxPatientTokens.put(uid, token);
						break;
					}
				}
			}
			if (token == null) {
				// 未登录
				response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作！").getBytes());
				return false;
			} else {
				if (token.getTimeout().getTime() < new Date().getTime()) {
					// 登录超时
					response.getOutputStream().write(error(SystemConf.LOGIN_TIMEOUT, "登录超时，请重新登录").getBytes());
					return false;
				} else if (!StringUtils.equals(tokenStr, token.getToken()) || !StringUtils.equals(uid, token.getUser()) || !StringUtils.equals(imei, token.getImei())) {
					// 别处登录
					response.getOutputStream().write(error(SystemConf.LOGIN_OTHER, "帐号在别处登录，请重新登录").getBytes());
					return false;
				} else {
					// 一天只更新一次
					if (DateUtil.getDays(token.getCzrq(), DateUtil.getNowDateShort()) != 0) {
						// 今天未更新，则更新缓存
						token.setCzrq(new Date());
						// 更新内存
						SystemData.doctorTokens.put(uid, token);
						// 更新数据库
						tokenDao.save(token);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

}