package com.sifang.modules.sys.web;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sys.common.security.UsernamePasswordToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping(value = "${adminPath}/sys/excellentMember")
public class ExcellentMemberController extends BaseController {

    @ResponseBody
    @RequestMapping(value = "clearLoginSession")
    public String clearLoginSession(HttpServletRequest request) {
        request.getSession().removeAttribute("fromWhere");
        return "200";
    }

    //跳转优服后台
    @RequestMapping("jumpToBackStage")
    public String  jumpToBackStage(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		String userId = request.getParameter("userId");
		Record re = Db.findFirst("select login_name,password from sys_user where id=? and status='0'", userId);
        String loginName = re.getStr("login_name");
        Factory<SecurityManager> factory = new IniSecurityManagerFactory();
        //得到SecurityManager实例并绑定给SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //得到Subject及创建用户名/密码身份验证Token（即用户身份/凭证）
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(
                loginName,
                "SFUnifiedCipher!".toCharArray(),
                false,
                null,
                null);
        try{
            //登录，即身份验证
            subject.login(token);
            System.out.println("登陆成功！");
            request.getSession().setAttribute("fromWhere","system");
        }catch (Exception e){
            //登录失败
            e.printStackTrace();
            System.out.println("用户信息验证失败");
            token.clear();
            //return "error";  //这里是登录失败的页面
            return "modules/base/login2";
        }
        String site = Db.queryStr("select name from crm_site where user_id=? ",userId);

        request.getSession().setAttribute("site",site);

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


}
