package com.ssj.sys.controller;

import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.util.PropertiesUtil;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.AdvancedUtil;
import com.ssj.framework.weixin.util.WeixinOauth2Token;
import com.ssj.service.sys.role.service.AdminService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.sys.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

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

@RequestMapping("/login")
@Controller
public class LoginController extends BaseController {
	
	@Autowired
	private AdminService adminService;
	
	
	/**
	 * 后台登陆页面)))))
	 * @return
	 */
	 @RequestMapping(value = { "/", "" })
	 public String login(Model model,HttpSession session) {
		    session.removeAttribute("admin");
		    session.removeAttribute("adminId");
	        session.invalidate();
	        model.addAttribute("imgUrl", PropertiesUtil.getValue("STATIC_FILE_URL"));
		 return "sys/login/login";
	 }
	 /**
	  * 退出
	  * @param session
	  * @return
	  */
	 @RequestMapping(value = { "/logout" })
	 public String logout(HttpSession session) {
		 return "redirect:/login.html"; 
	 }
    /**
     * 验证账号密码
     * @param loginname
     * @param password
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
    public String login(Model model,String loginname, String password) {
    	try {
            HttpSession session = request.getSession();
            String captcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
            session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
    		if (StringUtil.isEmpty(loginname) || StringUtil.isEmpty(password)) {
    			model.addAttribute("imgUrl",PropertiesUtil.getValue("STATIC_FILE_URL"));
    			request.setAttribute("error", "用户名或密码不能为空！");
    			return "sys/login/login";
    		}
    		if(adminService.loginLocking(loginname, "SYS")) {
    			model.addAttribute("imgUrl",PropertiesUtil.getValue("STATIC_FILE_URL"));
    			request.setAttribute("error", "用户登录已锁定，已锁定30分！");
    			return "sys/login/login";
    		}
//    		String requestCaptcha = request.getParameter("captcha");
//    		if (StringUtil.isEmpty(requestCaptcha) ) {
//    			model.addAttribute("imgUrl",PropertiesUtil.getValue("STATIC_FILE_URL"));
//    			request.setAttribute("error", "验证码不能为空！");
//    			 return "sys/login/login";
//    		}
//    		if(!requestCaptcha.equalsIgnoreCase(captcha)){
//    			model.addAttribute("imgUrl",PropertiesUtil.getValue("STATIC_FILE_URL"));
//    			request.setAttribute("error", "验证码错误！");
//    			 return "sys/login/login";
//    		}
    		Admin admin=adminService.longin(loginname, password);
    		if(admin==null){
    			request.setAttribute("error", "账号密码错误！");
    			model.addAttribute("imgUrl",PropertiesUtil.getValue("STATIC_FILE_URL"));
    			return "sys/login/login";
    		}
    		request.getSession().setAttribute("admin", admin);
    		request.getSession().setAttribute("adminId", admin.getId());
    	} catch (Exception e) {
    		e.printStackTrace();
    		model.addAttribute("imgUrl",PropertiesUtil.getValue("STATIC_FILE_URL"));
    		request.setAttribute("error", "登录异常，请联系管理员！");
    		 return "sys/login/login";
    	}
    	  return "redirect:/sys/login/index.html"; 
    }
	
	
	@RequestMapping(value = "openid/before_bind", produces = "text/html; charset=utf-8")
	public String openid(Model model,String op,HttpServletRequest request,HttpServletResponse response) throws Exception {
		StringBuffer url  =  new StringBuffer(request.getRequestURL());
		String code = request.getParameter("code");
    	logger.info("从PC微信网页进来  ---code----)"+code);
    	if(code !=null){
    		WeixinOauth2Token token= AdvancedUtil.getOauth2AccessToken(code);
    		UserService userService= SystemResourceLocator.getBean(UserService.class);
    		logger.info("从从PC---WeixinOauth2Token获取  ---openid----)"+token.getOpenId());
    		User user=userService.findByAccount(token.getOpenId());
    		if(user==null){
    			if(token.getScope() !=null && token.getScope().contains("snsapi_base")){
    				response.sendRedirect(AdvancedUtil.getuserinfourl(url.toString()));
    			}else if(token.getScope() !=null && token.getScope().contains("snsapi_userinfo")){
    				user= AdvancedUtil.getUserInfo(token.getAccessToken(), token.getOpenId());
    				user=userService.insertUser(user);
    				request.getSession().setAttribute("openId",token.getOpenId());
    				request.getSession().setAttribute("user", user);
    				request.getSession().setAttribute("userId", user.getId());
    				
    				Admin admin= new Admin();
    				admin.setLoginName("admin");
    				admin.setId("1a93b656-f3d7-41d3-aaeb-2aeb8627fd72");
    				admin.setNickName("超级管理员");
    				request.getSession().setAttribute("admin", admin);
    	    		request.getSession().setAttribute("adminId", admin.getId());
    				 return "redirect:/sys/login/index.html"; 
    			}
    			
    		}else{
    			request.getSession().setAttribute("openId",token.getOpenId());
    			request.getSession().setAttribute("user", user);
    			request.getSession().setAttribute("userId", user.getId());
    			
    			Admin admin= new Admin();
				admin.setLoginName("admin");
				admin.setId("1a93b656-f3d7-41d3-aaeb-2aeb8627fd72");
				admin.setNickName("超级管理员");
				request.getSession().setAttribute("admin", admin);
	    		request.getSession().setAttribute("adminId", admin.getId());
	    		
    			 return "redirect:/sys/login/index.html"; 
    		}
    	}else{
    		logger.info("从微信网页分享进来  ---code为空snsapi_base----) 发起获取用户的基本信息");
    		response.sendRedirect(AdvancedUtil.getQrconnect(url.toString()));
    	}
    	 return "sys/login/login";
	}
    
}
