package com.saye.hrs.controller.system;

import com.alibaba.fastjson.JSON;
import com.saye.hrs.commons.log.ExceptionDUtil;
import com.saye.hrs.commons.log.LogUtil;
import com.saye.hrs.commons.string.StringDUtil;
import com.saye.hrs.model.ResourceInfo;
import com.saye.hrs.model.StatusDefine;
import com.saye.hrs.model.Users;
import com.saye.hrs.service.OrderService;
import com.saye.hrs.service.system.MenuService;
import com.saye.hrs.service.system.ServiceParamsService;
import com.saye.hrs.service.system.UsersService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

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.*;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
public class LoginController {

	@Autowired
	private MenuService menuService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private ServiceParamsService serviceParamsService;
	@Autowired
	private OrderService orderService;
	/**
	 * @description 去登录页面
	 * @author dqzhang
	 * @created 2019年11月13日 下午4:22:48
	 * @param map
	 * @return
	 */
	@RequestMapping("/toLogin")
	public String toLogin(ModelMap map) {

		List<HashMap<Object, Object>> list = serviceParamsService.findParamValByParamCode("prj_name");
		map.addAttribute("prj_name",list.get(0).get("PARAM_VAL"));
		return "login";
	}

	/**
	 * @description 登录
	 * @author dqzhang
	 * @created 2019年11月13日 下午5:03:11
	 * @return
	 */
	@PostMapping("/login")
	@ResponseBody
	public HashMap<Object,Object> login(HttpServletRequest request,@RequestBody Map map) {

		String username = StringDUtil.removeSpaces(map.get("username"));
		String password = StringDUtil.removeSpaces(map.get("password"));
		String vercode = StringDUtil.removeSpaces(map.get("vercode"));

		String errCode = "0";
		String errMsg = "";
        try {
			String code = (String) request.getSession().getAttribute("verify_code");
			if(!code.equalsIgnoreCase(vercode)) {
				errCode = "CodeError";
				errMsg = "验证码不正确！";
			}
			if("0".equals(errCode)) {
				List<Users> list = usersService.searchByName(username);
				if(list.isEmpty()){
					errCode = "userError";
					errMsg = "用户名或密码错误！";
				}
				if("0".equals(errCode)) {
					Users user = list.get(0);
					String encryptPassword = new Md5Hash(password,"hrs",2).toString();
					if(user.getPassword().equals(encryptPassword)) {
						LogUtil.info(getClass(), "用户："+username+"登录系统");
						request.getSession().setAttribute("user",user);
					}else{
						errCode = "userError";
						errMsg = "用户名或密码错误！";
					}
				}
			}
		} catch (Exception e) {
			 errCode = e.getLocalizedMessage();
		     errMsg =  "未知异常！";
		     LogUtil.error(this.getClass(), "登录失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
        HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
        resultMap.put("errCode", errCode);
        resultMap.put("errMsg", errMsg);
        return resultMap;
	}

	/**
	 * @description 首页
	 * @author dqzhang       
	 * @created 2019年11月13日 下午5:10:21 
	 * @param request
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request,ModelMap modelMap) throws Exception {

		HashMap<Object,Object> map = new HashMap<Object,Object>();
		Users user = (Users) request.getSession().getAttribute("user");
		String user_id = user.getUserId();
		map.put("user_id", user_id);
		ResourceInfo resourceInfo=null;
		modelMap.addAttribute("expired",false);
		try {
			//上次密码修改时间
			resourceInfo = this.menuService.getMenuByRole(map);
			String userTrueName = user.getTrueName();
			String userName = user.getUserName();
			modelMap.addAttribute("userTrueName",userTrueName);
			modelMap.addAttribute("userName",userName);
			modelMap.addAttribute("userId",user_id);

			List<HashMap<Object, Object>> list = serviceParamsService.findParamValByParamCode("prj_name");
			modelMap.addAttribute("prj_name",list.get(0).get("PARAM_VAL"));
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.error(this.getClass(), "跳转首页失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
		modelMap.addAttribute("resourceInfo", resourceInfo.getChildren());
		return "index";
	}
	
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		if(request.getSession().getAttribute("user")!=null) {
			request.getSession().invalidate();
		}
		response.sendRedirect("/toLogin");
	}
	
	@RequestMapping("/home")
	public String home() throws IOException {
		return "home";
	}
	
	@RequestMapping("/findHomeData")
	@ResponseBody
	public HashMap<Object,Object> findHomeData() throws IOException {
		//String s ="{\"fwrs\":1,\"rechargeOrder\":[{\"NUM\":3,\"NOWDATE\":\"20211124\"},{\"NUM\":1,\"NOWDATE\":\"20211125\"},{\"NUM\":0,\"NOWDATE\":\"20211126\"},{\"NUM\":5,\"NOWDATE\":\"20211127\"},{\"NUM\":0,\"NOWDATE\":\"20211128\"},{\"NUM\":0,\"NOWDATE\":\"20211129\"},{\"NUM\":0,\"NOWDATE\":\"20211130\"}],\"bkrs\":1,\"yyrs\":1,\"weekOrder\":[{\"NUM\":3,\"NOWDATE\":\"20211124\"},{\"NUM\":6,\"NOWDATE\":\"20211125\"},{\"NUM\":0,\"NOWDATE\":\"20211126\"},{\"NUM\":0,\"NOWDATE\":\"20211127\"},{\"NUM\":0,\"NOWDATE\":\"20211128\"},{\"NUM\":0,\"NOWDATE\":\"20211129\"},{\"NUM\":0,\"NOWDATE\":\"20211130\"}],\"czzh\":1,\"office\":[{\"NUM\":1,\"KSMC\":null}]}";
		return this.orderService.findHomeData();
	}
	
	/**
	 * @description 获取验证码
	 * @author dqzhang       
	 * @created 2019年11月27日 下午3:15:32 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/getCode")
	public void verify(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		String name = request.getParameter("name");
		String str = request.getQueryString();
		BufferedReader bufferedReader = request.getReader();
		char[] c = new char[100];
		IOUtils.read(bufferedReader,c);

		System.out.println("bodyStr = " + new String(c));

		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
		HttpSession session = request.getSession();

		int width = 73;
		int height = 27;
		BufferedImage image = new BufferedImage(width, height, 1);

		Graphics g = image.getGraphics();

		Random random = new Random();

		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);

		g.setFont(new Font("Times New Roman", 0, 24));

		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String rand = randomInt(1).toUpperCase();
			sRand = sRand + rand;

			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(rand, 13 * i + 6, 24);
		}
		if (StringDUtil.changeNullToEmpty(name).equals(""))
			session.setAttribute("verify_code", sRand);
		else {
			session.setAttribute(name, sRand);
		}

		g.dispose();
		ServletOutputStream responseOutputStream = response.getOutputStream();

		ImageIO.write(image, "JPEG", responseOutputStream);

		responseOutputStream.flush();
		responseOutputStream.close();
	}

	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
	
	public static final String randomInt(int length) {
		if (length < 1) {
			return null;
		}
		Random randGen = new Random();
		char[] numbersAndLetters = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(36)];
		}
		return new String(randBuffer);
	}

	@RequestMapping("/toDemo")
	public String toDemo(ModelMap map) {

		return "demo";
	}
}
