/**
 * Copyright &copy; 2013-2017 <a href="http://www.rhcncpa.com/">瑞华会计师事务所</a> All rights reserved.
 */
package com.jeeplus.modules.sys.web;

import com.google.common.collect.Maps;
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.utils.*;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.iim.entity.MailBox;
import com.jeeplus.modules.iim.entity.MailPage;
import com.jeeplus.modules.iim.service.MailBoxService;
import com.jeeplus.modules.oa.entity.OaNotify;
import com.jeeplus.modules.oa.service.OaNotifyService;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
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.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import com.jeeplus.modules.utils.ErrorCode;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workcalendar.entity.WorkCalendar;
import com.jeeplus.modules.workcalendar.service.WorkCalendarService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import net.sf.json.JSONObject;
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.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 登录Controller
 * @author jeeplus
 * @version 2013-5-31
 */
@Controller
public class LoginController extends BaseController{

	@Autowired
	private SessionDAO sessionDAO;
	@Autowired
	private  SystemService systemService;
	@Autowired
	private UserofficeService userofficeService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private OaNotifyService oaNotifyService;
	@Autowired
	private WorkBidProjectService workBidProjectService;
	@Autowired
	private MailBoxService mailBoxService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkCalendarService workCalendarService;

	/**
	 * 管理登录
	 * @throws IOException
	 */
	@RequestMapping(value = "${adminPath}/login")
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		Principal principal = UserUtils.getPrincipal();


//		// 默认页签模式
//		String tabmode = CookieUtils.getCookie(request, "tabmode");
//		if (tabmode == null){
//			CookieUtils.setCookie(response, "tabmode", "1");
//		}

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

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

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


		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);
			}
		}
		UserUtils.saveSelectCompany();
		return "modules/sys/sysLogin";

	}


	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.POST)
	public String loginFail(HttpServletRequest request, HttpServletResponse response, Model model) {
		Jedis jedis = null;
		try {
			Principal principal = UserUtils.getPrincipal();

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

			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);

			if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")){
				if(SecurityUtils.getSubject().getSession()!=null){
					SecurityUtils.getSubject().logout();
				}
				message = "您的登录信息过期，请重新登录!";
			}

			model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
			model.addAttribute(FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
			model.addAttribute(FormAuthenticationFilter.DEFAULT_MOBILE_PARAM, mobile);
			model.addAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
			model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);

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

			// 非授权异常，登录失败，验证码加1。
			if (!UnauthorizedException.class.getName().equals(exception)){
				model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(username, true, false));
			}

			// 验证失败清空验证码
			//request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());
			jedis = JedisUtils.getResource();
			jedis.set(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());

			// 如果是手机登录，则返回JSON字符串
			if (mobile){
				AjaxJson j = new AjaxJson();
				j.setSuccess(false);
				j.setMsg(message);
				j.put("username", username);
				j.put("name","");
				j.put("mobileLogin", mobile);
				j.put("JSESSIONID", "");
				return renderString(response, j.getJsonStr());
			}
			//return "redirect:" + adminPath+"/login";
			return "modules/sys/sysLogin";
		} catch (Exception e) {
			//logger.error("getActiveSessions", e);
			return null;
		} finally {
			JedisUtils.returnResource(jedis);
		}
	}

	/**
	 * 管理登录
	 * @throws IOException
	 */
	@RequestMapping(value = "${adminPath}/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		Principal principal = UserUtils.getPrincipal();
		// 如果已经登录，则跳转到管理首页
		if(principal != null){
			UserUtils.getSubject().logout();

		}
		// 如果是手机客户端退出跳转到login，则返回JSON字符串
		String ajax = request.getParameter("__ajax");
		if(	ajax!=null){
			model.addAttribute("success", "1");
			model.addAttribute("msg", "退出成功");
			return renderString(response, model);
		}
		return "redirect:" + adminPath+"/login";
	}

	/**
	 * 登录成功，进入管理首页
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "${adminPath}")
	public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = UserUtils.getPrincipal();
		try {

			/**
			 *  切换用户时更新用户的company，office
			 */
			String companyName = principal.getCompanyName();
			if (StringUtils.isNotBlank(companyName) && UserUtils.getCache("selectCompany") != null && UserUtils.getCache("selectOffice") != null && !UserUtils.getCache("selectCompany").equals("1")) {
				String companyId= UserUtils.getCache("selectCompany").toString();
				Office com = officeService.get(companyId);
				if (!UserUtils.getUser().getComId().equals(companyId)) {
					Useroffice useroffice = new Useroffice();
					useroffice.setCompanyId(companyId);
					useroffice.setUserId(principal.getId());
					List<Useroffice> userofficeList = userofficeService.findList(useroffice);
					if(userofficeList!=null && userofficeList.size()!=0){
						Office company = officeService.get(userofficeList.get(0).getCompanyId());
						companyName = company.getName();
						systemService.saveCurrentCompanyById(principal.getId(), userofficeList.get(0).getCompanyId(),userofficeList.get(0).getOfficeId());
					}
				}else if(!com.getName().equals(companyName)){
					companyName = com.getName();
				}
			}
			model.addAttribute("JSESSIONID", principal.getSessionid());

			// 登录成功后，验证码计算器清零
			isValidateCodeLogin(principal.getLoginName(), false, true);
			//boolean flag = false;

			//logger.info("-----principal="+principal.getCompanyName());
			if (logger.isDebugEnabled()){
				//logger.debug("show index, active session size: {}", sessionDAO.getActiveSessions(false).size());
			}

			// 如果已登录，再次访问主页，则退出原账号。
			if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))){
				String logined = CookieUtils.getCookie(request, "LOGINED");
				if (StringUtils.isBlank(logined) || "false".equals(logined)){
					CookieUtils.setCookie(response, "LOGINED", "true");
				}else if (StringUtils.equals(logined, "true")){
					UserUtils.getSubject().logout();
					return "redirect:" + adminPath + "/login";
				}
			}

			// 如果是手机登录，则返回JSON字符串
			if (principal.isMobileLogin()){
				if (request.getParameter("login") != null){
					return renderString(response, principal);
				}
				if (request.getParameter("index") != null){
					return "modules/sys/sysIndex";
				}
				return "redirect:" + adminPath + "/login";
			}

			//		// 登录成功后，获取上次登录的当前站点ID
			//		UserUtils.putCache("siteId", StringUtils.toLong(CookieUtils.getCookie(request, "siteId")));

			//		System.out.println("==========================a");
			//		try {
			//			byte[] bytes = com.jeeplus.common.utils.FileUtils.readFileToByteArray(
			//					com.jeeplus.common.utils.FileUtils.getFile("c:\\sxt.dmp"));
			//			UserUtils.getSession().setAttribute("kkk", bytes);
			//			UserUtils.getSession().setAttribute("kkk2", bytes);
			//		} catch (Exception e) {
			//			e.printStackTrace();
			//		}
			////		for (int i=0; i<1000000; i++){
			////			//UserUtils.getSession().setAttribute("a", "a");
			////			request.getSession().setAttribute("aaa", "aa");
			////		}
			//		System.out.println("==========================b");
			//
			// 默认风格
			String indexStyle = "default";
			Cookie[] cookies = request.getCookies();
			for (Cookie cookie : cookies) {
				if (cookie == null || StringUtils.isEmpty(cookie.getName())) {
					continue;
				}
				if (cookie.getName().equalsIgnoreCase("theme")) {
					indexStyle = cookie.getValue();
				}
			}
			///临时，给首页显示当前公司
			model.addAttribute("companyName", companyName);
			/*User user = UserUtils.getUser();
			List<Office> offices = officeService.findByUserId(user.getId());
			for (Office office : offices){
				if (office.getId().equals(user.getComId())){

					break;
				}
			}*/
			//////

			// 要添加自己的风格，复制下面三行即可
			if (StringUtils.isNotEmpty(indexStyle)
					&& indexStyle.equalsIgnoreCase("ace")) {
				return "modules/sys/sysIndex-ace";
			}
            model.addAttribute("firstFlag",principal.isFirstFlag());
			return "modules/sys/sysIndex";
			/*if(UserUtils.getCache("selectRole")!=null){
				return "modules/sys/sysIndex";
			}else{
				return "modules/sys/sysLogin";
			}*/
		}catch (Exception e) {
			UserUtils.getSubject().logout();
			return "modules/sys/sysLogin";
		}
	}

	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request, HttpServletResponse response){
		if (StringUtils.isNotBlank(theme)){
			CookieUtils.setCookie(response, "theme", theme);
		}else{
			theme = CookieUtils.getCookie(request, "theme");
		}
		return "redirect:"+request.getParameter("url");
	}

	/**
	 * 是否是验证码登录
	 * @param useruame 用户名
	 * @param isFail 计数加1
	 * @param clean 计数清零
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean){
		Map<String, Integer> loginFailMap = (Map<String, Integer>)CacheUtils.get("loginFailMap");
		if (loginFailMap==null){
			loginFailMap = Maps.newHashMap();
			CacheUtils.put("loginFailMap", loginFailMap);
		}
		Integer loginFailNum = loginFailMap.get(useruame);
		if (loginFailNum==null){
			loginFailNum = 0;
		}
		if (isFail){
			loginFailNum++;
			loginFailMap.put(useruame, loginFailNum);
		}
		if (clean){
			loginFailMap.remove(useruame);
		}
		return loginFailNum >= 10;
	}


	/**
	 * 首页
	 * @throws IOException
	 */
	@RequestMapping(value = "${adminPath}/home")
	public String home(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		User user = UserUtils.getUser();
		OaNotify oaNotify = new OaNotify();
		oaNotify.setSelf(true);
		oaNotify.setNowDate(new Date());
		Page<OaNotify> page = oaNotifyService.findMyself(new Page<OaNotify>(request, response), oaNotify);
		model.addAttribute("page", page.getList());
		model.addAttribute("count", page.getList().size());//未读通知条数
		model.addAttribute("count1", page.getCount());//未读通知条数
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setUser(user);
		workProjectNotify.setCompanyId(user.getComId());
		workProjectNotify.setRemarks("待审批");
		Page<WorkProjectNotify> notifyPage = workProjectNotifyService.findPage(new Page<WorkProjectNotify>(request, response), workProjectNotify);
		model.addAttribute("notifyPage", notifyPage.getList());
		model.addAttribute("notifyCount", notifyPage.getList().size());//未读通知条数
		model.addAttribute("notifyCount1", notifyPage.getCount());//未读通知条数
		workProjectNotify.setStatus("0");
		workProjectNotify.setRemarks("待通知");
		Page<WorkProjectNotify> notifyPageShow = workProjectNotifyService.findPage(new Page<WorkProjectNotify>(request, response), workProjectNotify);
		model.addAttribute("notifyShowPage", notifyPageShow.getList());
		model.addAttribute("notifyShowCount", notifyPageShow.getList().size());//未读通知条数
		model.addAttribute("notifyShowCount1", notifyPageShow.getCount());//未读通知条数

        WorkCalendar workCalendar = new WorkCalendar();
        Page<WorkCalendar> workCalendars=workCalendarService.findHomePage(new Page<WorkCalendar>(request, response), workCalendar);
		model.addAttribute("calendarCount", workCalendars.getList());
		model.addAttribute("calendarPage", workCalendars.getList().size());
		model.addAttribute("calendarSize", workCalendars.getCount());
		MailBox mailBox = new MailBox();
		mailBox.setReceiver(user);
		mailBox.setReadstatus("0");//筛选未读
		Page<MailBox> mailPage = mailBoxService.findPage(new MailPage<MailBox>(request, response), mailBox);
		model.addAttribute("noReadCount", mailBoxService.getCount(mailBox));
		model.addAttribute("mailPage", mailPage.getList());
		model.addAttribute("firstFlag", request.getParameter("firstFlag"));
		return "modules/sys/sysHome";

	}

	/**
	 * 快速登录
	 * 获取验证码
	 * @param request
	 * @param mobile
	 * @return
	 */
	@RequestMapping(value = "${adminPath}/login/getRandomCode",method = RequestMethod.GET)
	@ResponseBody
	public AjaxJson getRandomCode(HttpServletRequest request, String mobile,String type) {
		AjaxJson j = new AjaxJson();
		//验证手机号是否已经注册
		if(userDao.findUniqueByProperty("login_name", mobile) != null){
			String randomCode = String.valueOf((int) (Math.random() * 9000 + 1000));
			System.err.println(randomCode);
			// String result = UserUtils.sendRandomCode(config.getSmsName(),config.getSmsPassword(), mobile, randomCode);
			HashMap<String,Object> result = null;
			try{
					//调用工具类返回结果
					result = UserUtils.sendRandomCodes(mobile, randomCode);
					String statusCode = (String) result.get("statusCode");
					if (("000000").equals(statusCode)) {
						j.setSuccess(true);
						j.setErrorCode("-1");
						j.setMsg("短信发送成功!");
						Jedis jedis = null;
						try {
							jedis = JedisUtils.getResource();
							jedis.set(mobile, randomCode);
							jedis.set("type",type);
							jedis.setex(mobile, 300, randomCode);
						} catch (Exception e) {
							//logger.error("getActiveSessions", e);
						} finally {
							JedisUtils.returnResource(jedis);
						}
					}else if(statusCode.equals("160040")){
						j.setSuccess(false);
						j.setErrorCode("2");
						j.setMsg("号码获取验证码次数已达每日上限！");
					}else{
						j.setSuccess(false);
						j.setErrorCode("2");
						//j.setMsg("短信发送失败，错误代码："+result+"，请联系管理员。");
						j.setMsg("短信发送失败，错误代码：101，请联系管理员。");
						j.put("ErrorXml",result);
					}

			}catch (Exception e){
				e.printStackTrace();
				logger.info("5");
				j.setSuccess(false);
				j.setErrorCode("101");
				j.setMsg("短信发送失败!");
			}
			return j;
		}else{
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_1003);
			j.setMsg("该用户未注册!");
			return j ;
		}
	}



}
