package com.quantgroup.asset.distribution.config.web.interceptor;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.quantgroup.asset.distribution.enums.response.AuthorityResponse;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
import com.quantgroup.asset.distribution.service.authority.IAuthorityService;
import com.quantgroup.asset.distribution.service.jpa.entity.AuthorityConfig;
import com.quantgroup.asset.distribution.service.jpa.repository.IAuthorityRepository;

import lombok.extern.slf4j.Slf4j;

/**
 * 权限认证
 * @author liwenbin
 *
 */
@Slf4j
@Component
public class AuthorityInterceptor implements HandlerInterceptor{
	
	@Autowired
	private IAuthorityService authorityService; 
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		GlobalResponse globalResponse = authoriity(request);
        if(globalResponse!=null){
            log.info("系统校验失败，原因 : {} ",globalResponse.getMsg());
            globalResponse.writeJson(response);
            return false;
        }
		return true;
	}
	
	/**
	 * 权限验证
	 * @param request
	 * @return
	 */
	private GlobalResponse authoriity(HttpServletRequest request) {
		String key = request.getHeader("as_auth_key");
		if (StringUtils.isEmpty(key)) { return GlobalResponse.create(AuthorityResponse.AS_AUTH_KEY_IS_EMPTY); }
		String pass = request.getHeader("as_auth_pass");
		if (StringUtils.isEmpty(pass)) { return GlobalResponse.create(AuthorityResponse.AS_AUTH_PASS_IS_EMPTY); }
		AuthorityConfig authorityConfig = authorityService.findByAuthKeyAndAuthPass(key, pass);
		if (authorityConfig == null) { return GlobalResponse.create(AuthorityResponse.AS_AUTH_KEY_AND_PASS_IS_NOT_EXIST); }
		return null;
	}
}
