package com.iamberry.wechat.handles.admin;
import java.util.List;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.wechat.core.entity.AdminUtils;
import com.iamberry.wechat.core.entity.admin.AdminChildInfo;
import com.iamberry.wechat.core.entity.admin.AdminChildPermissionErmissions;
import com.iamberry.wechat.core.entity.admin.AdminChildPermissions;
import com.iamberry.wechat.core.entity.admin.AdminInfo;
import com.iamberry.wechat.core.entity.admin.AdminLoginDTO;
import com.iamberry.wechat.face.admin.AdminLoginService;
import com.iamberry.wechat.face.mq.EfastOrderService;
import com.iamberry.wechat.filters.CSRFTokenFilter;
import com.iamberry.wechat.sendMsg.SendMessageUtil;
/**
 * description : 后台登陆handler类
 * @author 何秀刚
 * create date : 2015年12月10日
 */
@Controller
public class AdminLoginHandler {
	
	@Autowired
	private AdminLoginService adminLoginService;
	public void setAdminLoginService(AdminLoginService adminLoginService) {
		this.adminLoginService = adminLoginService;
	}
	
	@Autowired
	private AdminUtils adminUtils;
	public void setAdminUtils(AdminUtils adminUtils) {
		this.adminUtils = adminUtils;
	}
	
	@Autowired
	private SendMessageUtil sendMessageUtil;
	@Autowired
	private EfastOrderService efastOrderService;
	// 将 s 进行 BASE64 编码 
		public static String getBASE64(String s) {
			if (s == null)
				return null;
			return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
		}
	/**
	 * 用户申请后台登陆
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/loginUI")
	public ModelAndView loginUI(AdminLoginDTO dto, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("admin/main/login");
		
		// 校验用户是否登陆成功
		if (AdminUtils.getLoginAdminUser(request.getSession()) != null) {
			mv.setViewName("admin/main/index"); // 转向home页
			return mv;
		}
		// 登陆判断
		Object object = adminLoginService.selectAdminInfoByNameAndPwd(dto);
		if (object == null) {
			adminUtils.createRandom(request.getSession());
			return mv;
		}
		if (object instanceof AdminInfo) {
			AdminInfo adminInfo = (AdminInfo) object;
			if (adminInfo == null || adminInfo.getAdminId() == null) {
				adminUtils.createRandom(request.getSession());
				return mv;
			}
			// 判断用户状态
			if (adminInfo.getAdminStatus().intValue() != 1) {
				mv.addObject("title", "对不起，您的账户被封，请联系管理员!");
				mv.addObject("text", "对不起，您的账户被封，请联系管理员~");
				mv.setViewName("admin/msg/error");
				return mv;
			}
		} else if (object instanceof AdminChildInfo) {
			AdminChildInfo adminInfo = (AdminChildInfo) object;
			if (adminInfo == null || adminInfo.getAdminId() == null) {
				adminUtils.createRandom(request.getSession());
				return mv;
			}
			// 判断用户状态
			if (adminInfo.getAdminStatus().intValue() != 1) {
				mv.addObject("title", "对不起，您的账户被封，请联系管理员!");
				mv.addObject("text", "对不起，您的账户被封，请联系管理员~");
				mv.setViewName("admin/msg/error");
				return mv;
			}
			// 注册二级管理员的权限
			request.getSession().setAttribute("permission", adminLoginService.selectAdminChildHavePermissionById(adminInfo.getAdminId()));
		}
		
		// 登陆成功
		mv.setViewName("admin/main/index"); // 转向home页
		AdminUtils.addAdminUserToSession(object, request);
		// 判断是否需要注册菜单信息
		List<AdminChildPermissions> sessionMenuInfos = (List<AdminChildPermissions>) request.getSession().getAttribute("menuInfos");
		if (sessionMenuInfos == null) {
			// 重新注册
			if (object instanceof AdminInfo) {
				AdminInfo adminInfo = (AdminInfo) object;
				request.getSession().setAttribute("menuInfos", adminLoginService.selectMenusById(adminInfo.getAdminId(), true));
			} else if (object instanceof AdminChildInfo) {
				AdminChildInfo adminInfo = (AdminChildInfo) object;
				request.getSession().setAttribute("menuInfos", adminLoginService.selectMenusById(adminInfo.getAdminId(), false));
			}
		}
		// 判断是否注册
		return mv;
	}
	
	@SuppressWarnings({ "static-access", "unchecked"})
	@RequestMapping("/login")
	public ModelAndView login(AdminLoginDTO dto,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView();
		
		// 校验用户是否登陆成功
		if (adminUtils.getLoginAdminUser(request.getSession()) != null) {
			mv.setViewName("admin/main/index"); // 转向home页
			return mv;
		}
		// 回显
		mv.addObject("loginName", dto.getAdminLoginName());
		mv.addObject("loginPwd", dto.getAdminLoginPwd());
		// 校验token
		if (!adminUtils.checkLoginToken(dto.getLoginToken(), request.getSession())) {
			mv.setViewName("admin/main/login");
			mv.addObject("isShowDiv", true);
			mv.addObject("divText", "异常操作，请重试!");
			adminUtils.createRandom(request.getSession());
			return mv;
		}
		// 验证码
		if (!adminUtils.checkVerifyCode(request.getSession(), dto.getVerifyCode())) {
			mv.setViewName("admin/main/login");
			mv.addObject("isShowDiv", true);
			mv.addObject("divText", "验证码错误，请重试!");
			adminUtils.createRandom(request.getSession());
			return mv;
		}
		// 登陆判断
		Object object = adminLoginService.selectAdminInfoByNameAndPwd(dto);
		if (object == null) {
			mv.setViewName("admin/main/login");
			mv.addObject("isShowDiv", true);
			mv.addObject("divText", "账号密码错误，请重试!");
			adminUtils.createRandom(request.getSession());
			return mv;
		}
		if (object instanceof AdminInfo) {
			AdminInfo adminInfo = (AdminInfo) object;
			if (adminInfo == null || adminInfo.getAdminId() == null) {
				adminUtils.createRandom(request.getSession());
				return mv;
			}
			// 判断用户状态
			if (adminInfo.getAdminStatus().intValue() != 1) {
				mv.addObject("title", "对不起，您的账户被封，请联系管理员!");
				mv.addObject("text", "对不起，您的账户被封，请联系管理员~");
				mv.setViewName("admin/msg/error");
				return mv;
			}
		} else if (object instanceof AdminChildInfo) {
			AdminChildInfo adminInfo = (AdminChildInfo) object;
			if (adminInfo == null || adminInfo.getAdminId() == null) {
				adminUtils.createRandom(request.getSession());
				return mv;
			}
			// 判断用户状态
			if (adminInfo.getAdminStatus().intValue() != 1) {
				mv.addObject("title", "对不起，您的账户被封，请联系管理员!");
				mv.addObject("text", "对不起，您的账户被封，请联系管理员~");
				mv.setViewName("admin/msg/error");
				return mv;
			}
			List<AdminChildPermissionErmissions> list=adminLoginService.selectAdminChildHavePermissionById(adminInfo.getAdminId());
			request.getSession().setAttribute("permission", list);
		}
		// 登陆成功
		AdminUtils.addAdminUserToSession(object, request);
		CSRFTokenFilter.savesSignatureToToken(request, response);
		if(dto.getOnline() != null && dto.getOnline().equals("true")) {
			adminUtils.setCookieToResponse(response, dto.getAdminLoginName(), dto.getAdminLoginPwd());
		}
		mv.setViewName("admin/main/index"); // 转向home页
		// 判断是否需要注册菜单信息
		List<AdminChildPermissions> sessionMenuInfos = (List<AdminChildPermissions>) request.getSession().getAttribute("menuInfos");
		if (sessionMenuInfos == null) {
			// 重新注册
			if (object instanceof AdminInfo) {
				AdminInfo adminInfo = (AdminInfo) object;
				request.getSession().setAttribute("menuInfos", adminLoginService.selectMenusById(adminInfo.getAdminId(), true));
			} else if (object instanceof AdminChildInfo) {
				AdminChildInfo adminInfo = (AdminChildInfo) object;
				List<AdminChildPermissionErmissions> list=adminLoginService.selectAdminChildHavePermissionById(adminInfo.getAdminId());
				request.getSession().setAttribute("permission", list);
				request.getSession().setAttribute("menuInfos", adminLoginService.selectMenusById(adminInfo.getAdminId(), false));
			}
		}
		
		
		return mv;
	}

	/**
	 * 当前用户，执行退出登陆
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping("/exitLogin")
	public ModelAndView exitLogin(
			HttpServletRequest request,
			HttpServletResponse response
			) {
		// 初始化
		ModelAndView mv = new ModelAndView("admin/main/login");
		if (adminUtils.getLoginAdminUser(request.getSession()) != null) {
			// 清空session
			request.getSession().invalidate();
			// 清空cookie
			Cookie [] cookies = request.getCookies();
			for(Cookie cookie : cookies){
				cookie.setMaxAge(0);
				cookie.setPath("/");
				response.addCookie(cookie);
			}
		}
		HttpSession session = request.getSession(true);
		adminUtils.createRandom(session);
		return mv;
	}
}
