package com.ibeetl.admin.core.web;

import com.google.code.kaptcha.Producer;
import com.ibeetl.admin.core.annotation.LogController;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.rbac.UserLoginInfo;
import com.ibeetl.admin.core.rbac.tree.MenuItem;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.CoreUserService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.DesUtilTo32;
import com.ibeetl.admin.core.util.HttpRequestLocal;
import com.ibeetl.admin.core.util.PlatformException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@Controller
public class IndexController {

	@Autowired
	CorePlatformService platformService;

	@Autowired
	CoreUserService userService;

	@Autowired
	private Producer kaptchaProducer;

	@Autowired
	HttpRequestLocal httpRequestLocal;

	@Value("${admin.encodeKey}")
	private String encodeKey;

	public static Map<String,Integer> userloginMap=new HashMap<>();
	public static Map<String,String>  logincache=new HashMap<>();

	@GetMapping("/")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("/login.html");
		view.addObject("error","0000");
		return view;
	}
	@SneakyThrows
	@GetMapping("/image/code")
	public void imagacode(HttpServletRequest request, HttpServletResponse response) {
		byte[] captcha = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		try {
			// 将生成的验证码保存在session中
			String createText = kaptchaProducer.createText();
			//获取运算式文本
			String mathStr = createText.substring(0, createText.lastIndexOf("@"));
			//获取运算式结果
			String result = createText.substring(createText.lastIndexOf("@") + 1);

			request.getSession().setAttribute("simpleCaptcha", result);

			BufferedImage bi = kaptchaProducer.createImage(mathStr);

			ImageIO.write(bi, "jpg", out);
		} catch (Exception e) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		captcha = out.toByteArray();
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 保存验证码到session

		ServletOutputStream sout = response.getOutputStream();
		sout.write(captcha);
		sout.flush();
		sout.close();
		/*try {
			OutputStream os = response.getOutputStream();
			Map<String,Object> map = PictureCheckCode.getImageCode(60, 20, os);
			String simpleCaptcha = "simpleCaptcha";
			request.getSession().setAttribute(simpleCaptcha, map.get("strEnsure").toString().toLowerCase());
			request.getSession().setAttribute("codeTime",new Date().getTime());
			ImageIO.write((BufferedImage) map.get("image"), "JPEG", os);
		} catch (IOException e) {
			e.printStackTrace();
		}*/
	}
/*	@PostMapping("/login.do")
	@LogController(content = "登录", type = "1")
	public ModelAndView login(String code, String password,String checkcode,HttpServletRequest request, HttpServletResponse response) {
		System.out.println(request.getParameter("password"));
		UserLoginInfo info;
		ModelAndView view =new ModelAndView();
		view.setViewName("redirect:/index.do");
			if(null==request.getSession().getAttribute("simpleCaptcha")||!checkcode.equals(request.getSession().getAttribute("simpleCaptcha").toString().toLowerCase())){
				view.setViewName("redirect:/");
				throw new PlatformException("验证码码错");
			}
			info = userService.login(encodeKey, code, password);
			String pw = request.getParameter("password");
			System.out.println("登录密码 = " + password);
			System.out.println("登录密码pw = " + pw);

			if (info == null) {
				view.setViewName("redirect:/");
				throw new PlatformException("用户名密码错");
			}
			CoreUser user = info.getUser();
			CoreOrg currentOrg = info.getOrgs().get(0);
			for (CoreOrg org : info.getOrgs()) {
				if (org.getId() == user.getOrgId()) {
					currentOrg = org;
					break;
				}
			}

			info.setCurrentOrg(currentOrg);
			try {
				user.setPassword(DesUtilTo32.encode(encodeKey, password));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 记录登录信息到session
			System.out.println("--------user--------" + user.toString());
			platformService.removeSession(info.getUser().getCode());
			this.platformService.setLoginUser(info.getUser(),
					info.getCurrentOrg(), info.getOrgs());
			return view;
	}*/

	@PostMapping("/login.do")
	@LogController(content = "登录", type = "1")
	public ModelAndView logined(String code, String password,String checkcode,HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("code="+ code+",password = " + password +",checkcode= " +checkcode+ "///request" + request.getParameter("password"));
		try {
			String pasw = DesUtilTo32.decode(password, DateUtil.date2String(new Date(), "yyyyMMdd"));
			password = DesUtilTo32.encode(pasw, encodeKey);
		}catch (Exception e){
			e.printStackTrace();
		}
		UserLoginInfo info = null;
		String pattern = "[A-Za-z0-9\\-]*";
		if(!Pattern.matches(pattern, code)){
			ModelAndView view =new ModelAndView("/login.html");
			view.addObject("error","用户名不正确！");
			return view;
		}
		int scodelen=10;
		Integer lognum=userloginMap.get(code);
		if(lognum!=null){
			if(lognum>=5){
				String cachedate=logincache.get(code);
				System.out.println("----"+cachedate);
				if(cachedate==null) {
					ModelAndView view = new ModelAndView("/login.html");
					logincache.put(code, DateUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
					view.addObject("error", "用户连续错误输入密码5次,已经锁定！请"+scodelen+"分钟后重试!");
					return view;
				}else if(Integer.valueOf(DateUtil.getTimeDifference(
						DateUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss"),cachedate))<=scodelen){
					ModelAndView view = new ModelAndView("/login.html");
					view.addObject("error", "用户连续错误输入密码5次,已经锁定！请"+scodelen+"分钟后重试!");
					return view;
				}else{
					logincache.remove(code);
					userloginMap.remove(code);
				}
			}
		}else{
			lognum=0;
		}
		if(null==request.getSession().getAttribute("simpleCaptcha")||!checkcode.equals(request.getSession().getAttribute("simpleCaptcha").toString().toLowerCase())){
			ModelAndView view =new ModelAndView("/login.html");
			view.addObject("error","验证码错误");
			return view;
		}
		try {
			info = userService.login(encodeKey, code, password);
		}catch (PlatformException pe){
			ModelAndView view = new ModelAndView("/login.html");
			userloginMap.put(code, lognum + 1);
			view.addObject("error", "登陆失败，请重新登陆！");
			return view;
		}catch (Exception e){
			e.printStackTrace();
		}
		if (info == null) {
			ModelAndView view = new ModelAndView("/login.html");
			userloginMap.put(code, lognum + 1);
			view.addObject("error", "登陆失败，请重新登陆！");
			return view;
		}
		ModelAndView view =new ModelAndView();
		CoreUser user = info.getUser();
		view.setViewName("redirect:/index.do");
		CoreOrg currentOrg = info.getOrgs().get(0);
		for (CoreOrg org : info.getOrgs()) {
			if (org.getId() .equals(user.getOrgId()) ) {
				currentOrg = org;
				break;
			}
		}

		info.setCurrentOrg(currentOrg);
		try {
//				user.setPassword(DesUtilTo32.encode(password, encodeKey));
//				user.setPassword(DesUtilTo32.encode(encodeKey, password));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 踢出上个登录用户，进行单一登录
		platformService.removeSession(info.getUser().getCode());
		this.platformService.setLoginUser(info.getUser(),
				info.getCurrentOrg(), info.getOrgs());

		return view;
	}
	

	
	
	@RequestMapping("/index.do")
	public ModelAndView index() throws Exception {
		ModelAndView view = new ModelAndView("/index.html");
		CoreUser currentUser = platformService.getCurrentUser();
		Long orgId = platformService.getCurrentOrgId();

		if (orgId == -1L) {
			view.setViewName("redirect:/");
		} else {
			MenuItem menuItem = platformService.getMenuItem(
					currentUser.getId(), orgId);
				view.addObject("showPwd",
						userService.ifUpUserPwd(currentUser.getCode(),currentUser.getExpiretime(),currentUser.getIfexpire()));
			view.addObject("menus", menuItem);
		}
		return view;
	}

	@RequestMapping("/uppwd.do")
	public ModelAndView upUserPwd(){
		ModelAndView view = new ModelAndView("/changePwd.html");
		return view;
	}

	@RequestMapping("/logout.do")
	public ModelAndView logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Enumeration eum = session.getAttributeNames();
		while (eum.hasMoreElements()) {
			String key = (String) eum.nextElement();
			session.removeAttribute(key);
		}
		ModelAndView view = new ModelAndView("redirect:/");
		return view;
	}

	@RequestMapping("/changeOrg.do")
	public ModelAndView changeOrg(HttpServletRequest request, Long orgId) {
		platformService.changeOrg(orgId);
		ModelAndView view = new ModelAndView("redirect:/index.do");
		return view;
	}

}
