package com.yeejoin.amos.iec104.business.controller;

import java.util.HashMap;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yeejoin.amos.security.authorization.Authorization;
import com.yeejoin.amos.security.common.remote.RemoteSecurityServer;
import com.yeejoin.amos.security.entity.User;

import springfox.documentation.annotations.ApiIgnore;

/**
 * 基础控制器
 * 
 * @author 
 *
 */
@ApiIgnore
@RestController
@RequestMapping("/base")
@Authorization
public class BaseController {
	
	@Autowired
	private RemoteSecurityServer remoteSecurityServer;
	
	@Autowired
	protected HttpServletRequest request;
	
	/**
	 * 成功返回状态
	 */
	protected static final String SUCCESS = "SUCCESS";

	/**
	 * 失败返回状态
	 */
	protected static final String FAILED = "FAILED";

	/**
	 * 默认页大小
	 */
	protected static final int DEFAULT_PAGE_SIZE = 10;
	

	protected String getToken() 
	{
		/* Get token from header */
		String authToken = request.getHeader("X-Access-Token");
		/* If token not found get it from request parameter */
		if (authToken == null)
		{
			authToken = request.getParameter("token");
		}
		return authToken;
	}
	
	/**
	 * 
	 * <pre>
	 * 判断当前用户角色级别：true:主管/false:装备管理员
	 * </pre>
	 *
	 * @return
	 */
	protected boolean isDirector()
	{
		if(getUserInfo() == null){
			return false;
		}
		return getUserInfo().getRole().getRoleType() != 3;
	}
	/**
	 * 获取用户角色id
	 * @return
	 */
	protected String getRoleId()
	{
		if(getUserInfo() == null){
			return "";
		}
		return getUserInfo().getRole().getRoleType().toString();
	}
	
	/**
	 * 当前登录用户信息
	 */
	protected User getUserInfo() {
		if(getToken() == null){
			return null;
		}
		return remoteSecurityServer.loginAuthentication(getToken());
	}
	
	protected Long getUserId() 
	{
		Long userId = null;
		if (getUserInfo() != null)
		{
			userId = getUserInfo().getId();
		}
		return userId;
	}
	
	/**
	 * 获取当前用户所属公司名称
	 * @return
	 */
	protected String getCurrentCompanyNameOfUser(){
		if(getUserInfo() == null){
			return "";
		}
		return getUserInfo().getCompany().getCompanyName();
	}
	
	/**
	 * 获取请求的cookies
	 * @return
	 */
	protected HashMap<String,String> getCookInfoMap(){
		HashMap<String,String> map = new HashMap<String,String>();
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
			for(Cookie ck:cookies){
				map.put(ck.getName(), ck.getValue());
			}
		}
		return map;
	}
	/**
	 * 获取公司orgcode
	 * @return
	 */
	protected String getOrgCode(){
		if(getUserInfo() == null){
			return "";
		}
		return getUserInfo().getCompany().getCompCode(); 
	}
}
