package com.blueland.bpm.manage.web;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.blueland.bpm.application.model.ApplicationEntity;
import com.blueland.bpm.application.service.ApplicationManager;
import com.blueland.bpm.common.base.BaseSpringController;
import com.blueland.bpm.identity.UserService;
import com.blueland.bpm.identity.model.User;
import com.blueland.bpm.manage.util.BaseUser;
import com.blueland.bpm.manage.util.MyContants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Slf4j
@Controller
@RequestMapping(value = "/")
public class UserLoginController extends BaseSpringController{
	protected static final String LOGIN_JSP = "redirect:/login.jsp";
	protected static final String INDEX_JSP = "redirect:/index.jsp";
	protected static final String SSO_INDEX_JSP = "redirect:/index.jsp";
	@Autowired
	private UserService userService;
	@Autowired
	private ApplicationManager applicationManager;
	private static final String bpaUrl = "http://192.168.1.199/bpm";
	//"http://192.168.1.4/bpm";
	/**
	 * 执行搜索 
	 **/
	@ResponseBody
	@RequestMapping(value="/pages/user/login", produces="text/plain; charset=UTF-8")
	public String login(User query,HttpServletRequest request,HttpServletResponse response) {
//		String userId=request.getHeader("iv-user");
//		boolean isPortalAccess=false;
//		if(StringUtils.isEmpty(userId)){
//			userId=query.getUserId();
//		}else{
//			isPortalAccess=true;
//		}
		User user = userService.getUserById(query.getUserId());
		BaseUser bUser = BaseUser.getInstance();
		System.out.println("用户登录返回的用户信息===>" + JSONUtil.toJsonStr(user));
		System.out.println("BaseUser===>" + bUser);
		if(user!=null && StrUtil.isNotEmpty(user.getUserId())){
			if(user.getUserPwd()==null||!user.getUserPwd().equals(request.getParameter("password"))) {
				return  "密码错误！";
			}
			else {
				bUser.cleanCookieUser(request, response);
				bUser.setCookieUser(response, BaseUser.toUpperCase(user.getUserId()));
				List<ApplicationEntity> list=null;
				if(bUser.isEbpmAdmin(user)) {
					ApplicationEntity appQuery=new ApplicationEntity();
					appQuery.setAppType("inner");
					list = applicationManager.findByExample(appQuery);
				}else {
					list = applicationManager.selectByUserId(user.getUserId());
				}
				filter(list,"task");
				if(list.size() == 0) {
					return  "您没有需要管理的应用！";
				}else {
					bUser.saveUserToSession(request,user, list);

					//记录操作日志
					MyContants.saveUserOperate(request,"userId",true,"登陆成功",
							MyContants.LOGIN_SESSION_USER,MyContants.APPLICATION);
					return ACTION_SUCCESS;
				}
			}
		}else{
			return "帐号不存在，请您重新登陆！";
		}
	}

	@RequestMapping(value="/index")
	public String index(HttpServletRequest request,HttpServletResponse response) {
		String userId=request.getHeader("iv-user");
		BaseUser bUser = BaseUser.getInstance();
		this.dealFlowBpa(request);
		if(!StringUtils.isEmpty(userId)) {
			User user=userService.getUserById(userId);
			List<ApplicationEntity> list=null;
			if(bUser.isEbpmAdmin(user)) {
				ApplicationEntity query=new ApplicationEntity();
				query.setAppType("inner");
				list = applicationManager.findByExample(query);
			}else {
				list = applicationManager.selectByUserId(userId);
			}
			filter(list,"task");
			if(list.size() == 0) {
				return "redirect:/login.jsp";
			}else {
				bUser.saveUserToSession(request,user, list);
			}
		}else {
			bUser = BaseUser.getInstance();
			try {
				if(bUser.getSessionUser(request)==null){
					return "redirect:/login.jsp";
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return "redirect:/index.jsp";
	}
	/**
	 * 拼写流程梳理地址
	 * @param request
	 */
	private void dealFlowBpa(HttpServletRequest request) {
		HttpSession session=request.getSession(true);
		String token = "sa";
		Date date=new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String timestamp = formatter.format(date);
		String secretkey = "2wersd99f81fl09ad13abcRT";
		String noncestr = GenerateRandomNumber(6);
		String str = noncestr+token+timestamp+secretkey;
		String signature =DigestUtils.md5DigestAsHex(str.getBytes()).toUpperCase();
		String bpaUrl = this.bpaUrl+"/?token=" + token+ "&timestamp="+ timestamp+ "&noncestr="+ noncestr+ "&signature=" + signature;
		String bpmUrl = this.bpaUrl+"/?StartApp=2020/BPM&token=" + token+ "&timestamp="+ timestamp+ "&noncestr="+ noncestr+ "&signature=" + signature;
		session.setAttribute("bpaUrl",bpaUrl);
		session.setAttribute("bpmUrl",bpmUrl);

	}
	private static char[] constant ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
	public  String GenerateRandomNumber(int Length)
	{
		StringBuilder newRandom = new StringBuilder(62);
		Random rd = new Random();
		for (int i = 0; i < Length; i++)
		{
			newRandom.append(constant[rd.nextInt(62)]);
		}
		return newRandom.toString();
	}

	/**
	 * 执行搜索 
	 **//*
	@ResponseBody
	@RequestMapping(value="login", produces="text/plain; charset=UTF-8")
	public String login(User query,HttpServletRequest request,HttpServletResponse response) {
		User user=userService.getUserById(query.getUserId());
		BaseUser bUser = BaseUser.getInstance();
		if(user!=null){
			if(!user.getUserPwd().equals(request.getParameter("password"))) {
				return  "密码错误！";
			}
			else {
				bUser.cleanCookieUser(request, response);
				bUser.setCookieUser(response, BaseUser.toUpperCase(user.getUserId()));
				List<ApplicationEntity> list = applicationManager.selectByUserId(query.getUserId());
				if(list.size() == 0) {
					return  "您没有需要管理的应用！";
				}else {
					bUser.saveUserToSession(request,user, list);
					return ACTION_SUCCESS;
				}
			}
		}else{
			return "帐号不存在，请您重新登陆！";
		}
	}*/

	/**
	 * 执行搜索 
	 **/
	@RequestMapping(value="/pages/user/ssologin")
	public ModelAndView ssologin(User query,HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes) {
		ModelAndView result = new ModelAndView();
		User user=userService.getUserById(query.getUserId());
		BaseUser bUser = BaseUser.getInstance();
		if(user!=null && StrUtil.isNotEmpty(user.getUserId())){
			bUser.cleanCookieUser(request, response);
			bUser.setCookieUser(response, BaseUser.toUpperCase(user.getUserId()));
			List<ApplicationEntity> list = applicationManager.selectByUserId(query.getUserId());
			filter(list,"task");
			bUser.saveUserToSession(request,user,list);
			result.setViewName(SSO_INDEX_JSP);
		}else{
			redirectAttributes.addFlashAttribute("login_msg","登陆失败，请您重新登陆！");
			result.setViewName(LOGIN_JSP);
		}
		return result;
	}

	@RequestMapping(value="/custom/sso")
	public ModelAndView customSso(User query, HttpServletRequest request, HttpServletResponse response,
								  RedirectAttributes redirectAttributes) {
		ModelAndView result = new ModelAndView();
		User user = userService.getUserById(query.getUserId());
		BaseUser bUser = BaseUser.getInstance();
		if(user != null && StrUtil.isNotEmpty(user.getUserId())){
			bUser.cleanCookieUser(request, response);
			bUser.setCookieUser(response, BaseUser.toUpperCase(user.getUserId()));
			List<ApplicationEntity> list = applicationManager.selectByUserId(query.getUserId());
			filter(list,"task");
			bUser.saveUserToSession(request,user,list);
			HttpSession session=request.getSession(true);
			session.setAttribute("customSso", true);
			result.setViewName(SSO_INDEX_JSP);
		}else{
			redirectAttributes.addFlashAttribute("login_msg","登陆失败，请您重新登陆！");
			result.setViewName(LOGIN_JSP);
		}
		return result;
	}



	/**
	 * 执行搜索
	 **/
	@RequestMapping(value = "/pages/user/ssobacklogin")
	public void ssologin(String userId, HttpServletRequest request,
						 HttpServletResponse response) {
		try {
			response.setHeader("P3P","CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
			User user = userService.getUserById(userId);
			BaseUser bUser = BaseUser.getInstance();
			if (user != null && StrUtil.isNotEmpty(user.getUserId())) {
				bUser.cleanCookieUser(request, response);
				bUser.setCookieUser(response,
						BaseUser.toUpperCase(user.getUserId()));
				bUser.saveUserToSession(request, user, new ArrayList(0));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 改变系统
	 **/
	@RequestMapping(value="/pages/user/changeApp")
	@ResponseBody
	public void changeApp(String appId,HttpServletRequest request,HttpServletResponse response) {
		BaseUser bUser = BaseUser.getInstance();
		ApplicationEntity application = applicationManager.getById(appId);
		bUser.saveLoginUserAppId(application, request);
		/*try {
			response.setCharacterEncoding("utf-8");
			response.getWriter().write("操作成功");
		} catch (IOException e) {
			
			e.printStackTrace();
		}*/
	}


	/**
	 * 执行搜索 
	 **/
	@RequestMapping(value="/pages/user/logout")
	public ModelAndView logout(HttpServletRequest request,HttpServletResponse response) {
		ModelAndView result = new ModelAndView();
		BaseUser bUser = BaseUser.getInstance();
		bUser.cleanCookieUser(request, response);
		bUser.removeUserToSession(request);
		result.setViewName(LOGIN_JSP);
		return result;
	}
	public void filter(List<ApplicationEntity> list,String task){
		for (int i=0;i<list.size();i++) {
			if(list.get(i).getAppType()==null||list.get(i).getAppType().equals(task)){
				list.remove(i);
				i--;
			}
		}
	}
}
