package com.yihu.wlyy.interceptors;

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

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;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

/**
 * 医生权限校验
 * @author George
 *
 */
public class DoctorInterceptor extends BaseInterceptor {

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

			if (StringUtils.isEmpty(tokenStr) || StringUtils.isEmpty(imei) || StringUtils.isEmpty(uid)) {
				response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作！").getBytes());
				return false;
			}

			Token token = SystemData.doctorTokens.get(uid);
			if (token == null) {
				token = tokenDao.findByPatient(uid, 2);
				if (token != null) {
					// 加入缓存
					SystemData.doctorTokens.put(uid, token);
				}
			}
			if (token == null || token.getPlatform() != 2) {
				// 未登录
				response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作！").getBytes());
				flag = false;
			} else {
				if (token.getTimeout().getTime() < new Date().getTime()) {
					// 登录超时
					response.getOutputStream().write(error(SystemConf.LOGIN_TIMEOUT, "登录超时，请重新登录").getBytes());
					flag = 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());
					flag = 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 flag;
	}

	@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 {

	}
}