package cn.myapps.runtime.mobile.security.controller;

import java.util.HashMap;
import java.util.Map;

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

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.authtime.user.model.UserVO;
import cn.myapps.authtime.user.service.UserProcess;
import cn.myapps.base.web.WebUser;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.util.Security;
import cn.myapps.common.util.StringUtil;
import cn.myapps.constans.Web;
import cn.myapps.runtime.mobile.common.controller.BaseController;
import cn.myapps.util.WebCookies;
import net.sf.json.JSONObject;

@Controller(value="LoginController")
@RequestMapping(value="/runtime/app/security")
@Scope("prototype")
@Api(tags = "登录模块")
public class LoginController extends BaseController{
	
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private HttpServletResponse response;
	
	private WebCookies webCookies;
	
	public WebCookies getWebCookies() {
		return webCookies;
	}

	public void setWebCookies(WebCookies webCookies) {
		this.webCookies = webCookies;
	}
	
	@RequestMapping(value="/login.action")
	@ApiOperation(value = "用户登录", notes = "用户登录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "企业域名称",value = "domainName",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "账号",value = "username",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "密码",value = "password",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "验证码",value = "checkcode",required = true,paramType = "query",dataType = "string")
	})
	public Map<String, Object> login() throws Exception{
		Map<String, Object> jsonResult = null;
		ParamsTable params = getParams();
		String domainName = params.getParameterAsString("domainName");
		String username = params.getParameterAsString("username");
		String password = params.getParameterAsString("password");
		String checkcode = params.getParameterAsString("checkcode");
		
		Cookie pwdErrorTimes = getErrorTimes();
		int count=0;
		if(pwdErrorTimes!=null){
		String i = pwdErrorTimes.getValue();
		 count = Integer.parseInt(i);
		}
		
		try {
			HttpSession session = request.getSession();
			
			if (pwdErrorTimes != null && isExceedTimes(pwdErrorTimes)) {
				String code = (String) session.getAttribute(Web.SESSION_ATTRIBUTE_CHECKCODE);
				if (code == null) {
					throw new Exception("验证码错误");
				}
				if(code !=null && !code.equalsIgnoreCase(checkcode)){
					throw new Exception("验证码错误");
				}
			}
			UserProcess up = AuthTimeServiceManager.userRuntimeService();
			UserVO user = null;
			try {
				user = up.login(username, password, domainName, count);
			} catch (Exception e){
				if(user == null){
					password = Security.decodeBASE64(password);
					user = up.login(username, password, domainName, count);
				}
			}
			if(user != null && Security.decryptPassword(user.getLoginpwd()).equals(password)){
				getWebCooikes().destroyCookie("pwdErrorTimes");
				Map<String, String> token = new HashMap<String, String>();
				String theToken = Security.getToken(user.getId());
//				token.put("access_token", Security.encryptPassword(user.getId()+":"+System.currentTimeMillis()));
				token.put("access_token", theToken);
				token.put("userId", user.getId());
				token.put("username", user.getName());
				token.put("loginno", user.getLoginno());
				token.put("email", user.getEmail());
				token.put("mobile", user.getTelephone());
				token.put("mobile2", user.getTelephone2());
				if (StringUtil.isBlank(user.getAvatarUri())) {
					token.put("avatar", "");
				} else {
					token.put("avatar", user.getAvatarUri());
				}
				token.put("domain", user.getDomain().getName());
				token.put("department", user.getDefaultDepartment());
				token.put(Security.ACCESS_TOKEN, theToken);

//				String theToken = Security.getToken(user.getId());
				// 存放到cookie
				Cookie cookie = new Cookie(Security.ACCESS_TOKEN, theToken);
				cookie.setPath("/");
				response.addCookie(cookie);
				//设置用户
				WebUser.setWebUser(new WebUser(user), request);
				jsonResult = addActionResult(true, "登录成功", token);
			}
			return jsonResult;
		} catch (Exception e) {
			increaseErrorTimes(); // cookie中增加出错次数
			if (isExceedTimes(pwdErrorTimes)){
				request.setAttribute("showCode", Boolean.valueOf(true));
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("showCode", true);
				return addActionResult(false, e.getMessage(), map);
			}
			
			destroyLoginPassword(response, request);
			return addActionResult(false, "账号或密码错误", new JSONObject());
		}
	}
	
	private Cookie getErrorTimes() {
		WebCookies webCookies = getWebCooikes();
		Cookie pwdErrorTimes = webCookies.getCookie("pwdErrorTimes");

		return pwdErrorTimes;
	}
	
	public WebCookies getWebCooikes() {

		if (webCookies == null) {
			webCookies = new WebCookies(request, response, WebCookies.ENCRYPTION_URL);
		}

		return webCookies;
	}
	
	private void increaseErrorTimes() {
		WebCookies webCookies = getWebCooikes();
		Cookie pwdErrorTimes = webCookies.getCookie("pwdErrorTimes");

		try {
			if (pwdErrorTimes != null) {
				int times = Integer.valueOf(webCookies.getValue("pwdErrorTimes"));
				webCookies.addCookie("pwdErrorTimes", (times + 1) + "", 60 * 60 * 24);
			} else {
				webCookies.addCookie("pwdErrorTimes", "1", 60 * 60 * 24);
			}
		} catch (NumberFormatException e) {
			//LOG.warn("{}", "increaseErrorTimes", e);
		}
	}
	
	/**
	 * 检查错误次数
	 * 
	 * @param cookie
	 * @return
	 */
	public boolean isExceedTimes(Cookie cookie) {
		if (cookie != null) {
			try {
				String val = webCookies.getValue(cookie.getName());
				int errorTime = Integer.parseInt(val);
				if (errorTime >= 3) {
					return true;
				}
			} catch (NumberFormatException e) {
				//LOG.warn("{}", "isExceedTimes", e);
			}
		}
		return false;
	}
	
	/**
	 * 销毁登陆密码
	 * @param response
	 * @param request
	 */
	private void destroyLoginPassword(HttpServletResponse response, HttpServletRequest request){
		WebCookies webCookies = getWebCooikes();
		webCookies.destroyCookie("password");
	}
}
