package com.jeeplus.modules.API.sys;

import java.io.IOException;

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

import com.jeeplus.common.utils.*;
import com.jeeplus.modules.utils.ErrorCode;
import com.jeeplus.modules.workfullmanage.entity.WorkFullDesign;
import com.jeeplus.modules.workfullmanage.service.WorkFullDesignService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.security.shiro.session.SessionDAO;
import com.jeeplus.common.servlet.ValidateCodeServlet;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.iim.entity.MailBox;
import com.jeeplus.modules.iim.entity.MailPage;
import com.jeeplus.modules.oa.entity.OaNotify;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.security.FormAuthenticationFilter;
import com.jeeplus.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import redis.clients.jedis.Jedis;

/**
 * 登录Controller
 *
 * @author mengxy
 * @version 2017-5-17
 */
@Controller
public class LoginMobileController extends BaseController {

	@Autowired
	private SessionDAO sessionDAO;

	@Autowired
	private WorkFullDesignService workFullDesignService;

	// @RequestMapping(value = "${frontPath}/login")
	// public AjaxJson login(HttpServletRequest request, HttpServletResponse
	// response, Model model){
	//
	//
	// AjaxJson j=new AjaxJson();
	// return j;
	//
	// }
	/**
	 * 管理登录
	 *
	 * @throws IOException
	 */
	@RequestMapping(value = "${frontPath}/login")
	@ResponseBody
	public AjaxJson login(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		response.setHeader("Access-Control-Allow-Origin","*");
		response.setHeader("Access-Control-Allow-Method","POST,GET");
		Principal principal = UserUtils.getPrincipal();
		AjaxJson j = new AjaxJson();

		if (logger.isDebugEnabled()) {
			//logger.debug("login, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}

		if (principal != null && CacheUtils.get("selectRole") != null) {
			j.setSuccess(false);
			j.setMsg("已经登录！");
			j.setErrorCode(ErrorCode.code_1006);
			return j;
		}

		j.setSuccess(false);
		j.setMsg("会话失效");
		j.setErrorCode(ErrorCode.code_1001);
		return j;

		/*
		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
			CookieUtils.setCookie(response, "LOGINED", "false");
		}

		// 如果已经登录，则跳转到管理首页
		if (principal != null && !principal.isMobileLogin()) {
			return "redirect:" + frontPath;
		}

		SavedRequest savedRequest = WebUtils.getSavedRequest(request);// 获取跳转到login之前的URL
		// 如果是手机没有登录跳转到到login，则返回JSON字符串
		if (savedRequest != null) {
			String queryStr = savedRequest.getQueryString();
			if (queryStr != null && (queryStr.contains("__ajax") || queryStr.contains("mobileLogin"))) {
				AjaxJson j = new AjaxJson();
				j.setSuccess(false);
				j.setErrorCode("0");
				j.setMsg("没有登录!");
				return renderString(response, j);
			}
		}

		return "modules/sys/sysLogin";*/

	}

	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "${frontPath}/login", method = RequestMethod.POST)
    @ResponseBody
	public AjaxJson loginFail(HttpServletRequest request, HttpServletResponse response) {
		Principal principal = UserUtils.getPrincipal();
		AjaxJson j = new AjaxJson();
		// 如果已经登录，则跳转到管理首页
		if (principal != null && CacheUtils.get("selectRole") != null) {
			j.setSuccess(false);
			j.setMsg("已经登录！");
			j.setErrorCode(ErrorCode.code_1006);
			return j;
		}

		String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
		boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
		boolean mobile = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
		String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String message = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);
		String companyName = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_COMPANY_PARAM);
		if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")) {
			if(SecurityUtils.getSubject().getSession()!=null){
				SecurityUtils.getSubject().logout();
			}
			message = "您的登录信息过期，请重新登录!";
			j.setErrorCode(ErrorCode.code_1002);
		}else if (message.equals("用户或密码错误, 请重试.")){
            j.setErrorCode(ErrorCode.code_1002);
        }else if (message.equals("登录失败, 该用户未注册.")){
			j.setErrorCode(ErrorCode.code_1003);
		}

		if (logger.isDebugEnabled()) {
			//logger.debug("login fail, active session size: {}, message: {}, exception: {}",sessionDAO.getActiveSessions(false).size(), message, exception);
		}
        UserUtils.saveSelectCompany();
		j.setSuccess(false);
		j.setMsg(message);
		return j;
	}


	/**
	 * 管理登录
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "${frontPath}/logout", method = RequestMethod.GET)
	public AjaxJson logout(HttpServletRequest request, HttpServletResponse response) {
		Principal principal = UserUtils.getPrincipal();
		System.out.println("mobile logout");
		AjaxJson j = new AjaxJson();
		// 如果已经登录，则跳转到管理首页
		Jedis jedis = null;
		try {
			jedis = JedisUtils.getResource();
			String userId = jedis.get(UserUtils.getUser().getId());
			if (StringUtils.isNotBlank(userId)){
				jedis.del(userId);
			}
		} catch (Exception e) {
			logger.error("getActiveSessions", e);
		} finally {
			JedisUtils.returnResource(jedis);
		}
		if (principal != null) {
			UserUtils.getSubject().logout();
		}

		j.setSuccess(true);
		j.setMsg("退出成功");
		j.setErrorCode(ErrorCode.code_1004);
		return j;
	}

//	@Transactional
//	@RequestMapping("${frontPath}/testSw")
//	@ResponseBody
//	public AjaxJson testSw(){
//		AjaxJson j = new AjaxJson();
//		WorkFullDesign w = new WorkFullDesign();
//		w.setLinkPhone("1");
//		w.setUnitName("2");
//		w.setUnitLinkMan("3");
//		workFullDesignService.save(w);
//		WorkFullDesign w1 = new WorkFullDesign();
//		w1.setLinkPhone("1122");
//		w1.setUnitName("21");
//		w1.setUnitLinkMan("31");
//		workFullDesignService.save(w1);
//
//		j.setSuccess(true);
//		j.setMsg("退出成功");
//		j.setErrorCode("-1");
//		return j;
//	}

}
