package com.zhongdao.jlr.customer.interceptor;

import java.util.HashMap;
import java.util.List;

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

import org.apache.http.util.TextUtils;
import org.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;



import com.zhongdao.jlr.customer.dao.CustomerDao;
import com.zhongdao.jlr.customer.service.CustomerService;
import com.util.RequestUtil;

public class UserInterceptor implements HandlerInterceptor {

	public final String LOGINTOKEN = "logintoken";
	public final String SYSACCOUNT = "sysaccount";
	public final String ORDERKEY = "orderkey";
	public final String CUSTOMKEY = "customkey";
	private CustomerDao dao;

	public CustomerDao getDao() {
		return dao;
	}

	public void setDao(CustomerDao dao) {
		this.dao = dao;
	}
	// 拦截前处理
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object obj) throws Exception {
		String logintoken = request.getHeader(LOGINTOKEN);
		String sysaccount = request.getHeader(SYSACCOUNT);
		String customkey = request.getHeader(CUSTOMKEY);
		String orderkey = request.getParameter(ORDERKEY);
		JSONObject error = new JSONObject();
		
		if (logintoken != null && sysaccount != null) {
			
			String hql = "select * from tabusertoken t where t.token ='"
					+ logintoken + "' and t.sysaccount ='"+ sysaccount + "'";
			List list = dao.getRsBySql(hql);
			if (list != null && list.size() > 0) {
				System.out.println("已经登录！");
				if(!TextUtils.isEmpty(orderkey)){
					String orderhql = "select * from taborder where customkey ='"+customkey+"' and orderkey ='"+orderkey+"'";
					 list = dao.getRsBySql(orderhql);
					 if (list != null && list.size() > 0) {
						 return true;
					 }else{
						 	System.out.println("订单权限已变！");
							error.put("errormsg", "订单权限已变！");
							RequestUtil.responseResult4Json(response, error.toString());
							return false; 
					 }
				}else{
					return true;
				}
			
				
			}else{
				System.out.println("没有登录！");
				error.put("errormsg", "没有登录！");
				RequestUtil.responseResult4Json(response, error.toString());
				return false;
			}
			
		}
		 return true;
	}

	// 拦截后处理
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object obj, ModelAndView mav)
			throws Exception {
	}

	// 全部完成后处理
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object obj, Exception e)
			throws Exception {
	}
}
