/**
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.sifang.modules.sys.web;


import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.rechargewallet.service.RechargeWalletService;
import com.sifang.modules.setting.constant.EmpRoleConstants;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.site.siteInfo.dao.SiteEmployeeDao;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.global.Global;
import com.sifang.modules.sys.common.utils.CookieUtils;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.service.SystemService;
import com.sifang.modules.sys.util.CrmSiteUtils;
import com.sifang.modules.sys.util.CrmUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Map;

/**
 * 登录Controller
 * 
 * @version 2019-11-15
 */
@Controller
public class LoginController extends BaseController {

	@Autowired
	private SessionDAO sessionDAO;
	@Autowired
	private SystemService systemService;
	@Autowired
	private RechargeWalletService rechargeWalletService;

	@Autowired
	MemberService memberService;
     @Autowired
	SiteEmployeeDao siteEmployeeDao;


	/**
	 * 管理登录
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		// 如果已经登录，则跳转到管理首页
		if (user.getId() != null) {
			return "redirect:" + Global.getAdminPath();
		}
		return "modules/base/login";
	}

	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.POST)
	public String login(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String username, HttpServletRequest request, HttpServletResponse response, Model model,
			String password) {
		String origin = request.getParameter("origin");
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
		String errMsg = String.valueOf(request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME));
		if (errMsg.indexOf("UnknownAccountException") != -1) {
			model.addAttribute("msg", "notfind");
			model.addAttribute("username", "");
			// model.addAttribute("username", username);
		} else if (errMsg.indexOf("IncorrectCredentialsException") != -1) {
			model.addAttribute("errormessage", "error");
			model.addAttribute("username", username);
		} else if (errMsg.indexOf("CaptchaException") != -1) {
			// 验证码错误
		} else if (errMsg.indexOf("NotVertifyException") != -1) {
			// 该账号正在审核中， 不允许登陆!
		} else if (errMsg.indexOf("FailVertifyException") != -1) {
			// 该账号审核未通过，不允许登陆!
		} else if (errMsg.indexOf("FailVertifyException") != -1) {
			// 该账号被禁用，不允许登陆!
		}
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(user.getId())) {
			return "redirect:" + Global.getAdminPath();
		}
		/*
		 * if("jdxh".equals(origin)){ return "modules/base/partner/login"; }
		 */
		return "modules/base/login";
	}

	/** 如果登陆成功那么进入测试文件 **/
	@RequestMapping(value = "${adminPath}")
	public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (user.getId() == null) {
			return "redirect:" + Global.getAdminPath() + "/login";
		}
		if(User.USER_TYPE_SIT.equals(user.getUserType())){
			return goLogin(model);
		}


		model.addAttribute("user",user);
		if (StringUtil.isNotBlank(siteEmployeeDao.getEmpName(user.getId()))) {
			model.addAttribute("empName",siteEmployeeDao.getEmpName(user.getId()));
		}
		String name = CrmUtils.getUserXM(user);
		model.addAttribute("name",name);
		if(User.USER_TYPE_YYS.equals(user.getUserType())){
			//平台管理员

			return "modules/base/index";// 正常登陆
		}else if(User.USER_TYPE_XXY.equals(user.getUserType())){
			//服务商
			Boolean flag=siteEmployeeDao.isAuthorize(user.getId()); //判断服务商是否被授权了
			String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
			Record rd=CrmSiteUtils.getSiteBySiteId(siteId);
			model.addAttribute("site",rd.getStr("name"));
			if(flag){
				return "modules/site/index";
			}else{

				return "modules/site/noAuthorizeIndex";
			}

		}else if(User.USER_TYPE_WXG.equals(user.getUserType())){

			HttpSession session = request.getSession();

			session.setAttribute("users",user);
			model.addAttribute("system","1");
			String type = CrmUtils.getPlatEmployeRole(user.getId());
			model.addAttribute("systemType",type);
			if(EmpRoleConstants.SYSTEM_EMGINEER.equals(type)||EmpRoleConstants.PROJECT_EMGINEER.equals(type)||EmpRoleConstants.TREASURER.equals(type) || EmpRoleConstants.BUYER.equals(type)
					|| EmpRoleConstants.MATERIAL_CLERK.equals(type)
					|| EmpRoleConstants.TRANSPORTATION_MANAGEMENT_DEPT.equals(type)
					|| EmpRoleConstants.SALEAMAN.equals(type)
					||EmpRoleConstants.SUPERVISOR.equals(type)
					||EmpRoleConstants.SUPPLY_CHAIN.equals(type)
					||EmpRoleConstants.SUPPLY_SHGCS.equals(type)
					||EmpRoleConstants.SUPPLY_GFXTZG.equals(type)
					||EmpRoleConstants.SUPPLY_XMYSGCS.equals(type)){
			model.addAttribute("counts",CrmUtils.listMessageDataCount(user.getId(),"3"));

			}
			if(user.getRoleIds().contains("2c92d2148a0d1560018a0d834d2d003a")){
				return "modules/base/sys/system";
			}

			//平台员工
			return "modules/base/index";//
		}else if(User.USER_TYPE_HUI.equals(user.getUserType())){ //服务商人员
			//判断是不是服务商中的工程师角色
          Boolean flag=siteEmployeeDao.isEngineer(user.getId());
          if(flag){
			  return goLogin(model);
		  }else{
			  return "modules/site/index";
		  }
		}else if(User.USER_TYPE_KJ.equals(user.getUserType()) || User.USER_TYPE_ADVISOR.equals(user.getUserType())){
			//代理商
			model.addAttribute("counts",CrmUtils.listMessageDataCount(user.getId(),"3"));
			return "modules/yangguang/index";
		}else if(User.USER_TYPE_SUPPLI.equals(user.getUserType())){
			//供应商
			return "modules/yangguang/index";
		}
		if("9".equals(user.getUserType())|| "a".equals(user.getUserType())){
			return "modules/base/sys/system";
		}

		systemService.updateLoginTime(user.getId());

		return "modules/base/index";// 正常登陆
	}

	/** 如果登陆成功那么进入测试文件 **/
	@RequestMapping(value = "${adminPath}/index")
	public String crmIndex(HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (user.getId() == null) {
			// return "redirect" + Global.getAdminPath() + "/login";
		}
		// 密码器清零
		// isValidateCodeLogin(user.getLoginName(), false, true);
		return "modules/sifang/index";
	}

	@RequestMapping(value = "${adminPath}/indexFrame")
	public String indexFrame() {
		return "";
	}

	@RequiresUser
	@RequestMapping(value = "${adminPath}/portal")
	public String portal() {
		return "modules/portal/portal" + UserUtils.getUser().getUserType();
	}

	/**
	 * 获取主题方案
	 */
	@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");
	}

	@SuppressWarnings("resource")
	@RequestMapping("${adminPath}/download")
	public String download(@RequestParam String filePath, HttpServletResponse response) {
		File file = new File(filePath);
		InputStream inputStream;
		try {
			inputStream = new FileInputStream(filePath);
			response.reset();
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
			OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
			byte data[] = new byte[1024];
			while (inputStream.read(data, 0, 1024) >= 0) {
				outputStream.write(data);
			}
			outputStream.flush();
			outputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "${adminPath}/redirect/logout")
	public String logout() {
		/*
		 * User user = UserUtils.getUser(); if(user != null &&
		 * StringUtils.isNotBlank(user.getId())){ Db.
		 * update(" UPDATE crm_onlines SET is_online = '0', logout_time = ? WHERE user_id = ? "
		 * , new Date(), user.getId());
		 * logger.info(" userId:"+user.getId()+" logout at:"+new Date()+"... "); }
		 */
		Session session = SecurityUtils.getSubject().getSession();
		User user =(User) session.getAttribute("users");
		sessionDAO.delete(session);
		SecurityUtils.getSubject().logout();

		return "redirect:" + Global.getAdminPath() + "/login";
	}

	//通过主页的登录按钮进入
	@RequestMapping(value = "goLogin")
	public String goLogin(Model model) {
		Session session = SecurityUtils.getSubject().getSession();
		SecurityUtils.getSubject().logout();
		sessionDAO.delete(session);
		model.addAttribute("isEmp",true);
		return "modules/base/login";
	}


	@RequestMapping(value = "${adminPath}/systemSetup", method = RequestMethod.GET)
	public String systemSetup(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/setup/setSystem";
	}

}
