package com.iamberry.wechat.utils;
import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.iamberry.jwt.AES;
import com.iamberry.sys.Admin;
import com.iamberry.wechat.utils.token.TokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统管理员工具类
 * @author 献
 * @company 深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @tel 18271840547
 * @date 2017/5/16
 */
public class AdminUtils {

    private static final Logger logger = LoggerFactory.getLogger(AdminUtils.class);

    /**
     * 保存cookie
     * @param adminId
     * @param name
     * @param response
     */
    public static void saveAdminToCookie(Integer adminId, String name, String pwd, HttpServletResponse response) {
        String ticket = TokenUtil.getToken().substring(0, 8);
        String token = getToken(adminId, name, ticket, pwd);
        token = ticket + token;
        Cookie cookie = new Cookie("NEXT_LOGIN", token);
        cookie.setMaxAge((60 * 60 * 24 * 3) * 30 - 60);
        cookie.setPath("/");
        cookie.setHttpOnly(true);

        response.addCookie(cookie);
    }

    /**
     * 解析Cookie中的信息
     * @param request
     * @return
     */
    public static Admin getAdminCookie(HttpServletRequest request) {
        Cookie [] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            return null;
        }
        for (Cookie cooky : cookies) {
            if ("NEXT_LOGIN".equals(cooky.getName())) {
                String token = cooky.getValue();
                String ticket = token.substring(0, 8);
                return verifier(token, ticket);
            }
        }

        return null;
    }

    /**
     * return:
     * 	1:token过期，失效						    <br>
     * 	2:token正常								<br>
     * 		可以通过get("userid")获取userid		<br>
     * 		可以通过get("WC_OPENID")获取openid	<br>
     * @param userToken
     * @return
     */
    private static Admin verifier(String userToken, String key) {
        JWTVerifier verifier = new JWTVerifier(key);
        Map<String, Object> claims = null;
        try {
            // 解析TOKEN
            claims = verifier.verify(userToken.substring(8));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        String temp = AES.decrypt(claims.get("userid").toString());
        Assert.notNull(temp, "校验失败，请确认!");
        // 解析userid
        Integer userid = Integer.parseInt(temp);
        String username = claims.get("WC_OPENID").toString();
        String password = claims.get("pwd").toString();

        Admin admin = new Admin();
        admin.setAdminId(userid);
        admin.setAdminAccount(username);
        admin.setAdminPassword(password);

        return admin;
    }

    /**
     * 根据secretToken加密用户id、openid，生成json web token
     * @param userid		用户id
     * @param openId		openid
     * @param secretToken	token，限制为8位
     * @return
     * @author 献
     * @Time   2016年11月24日
     */
    private static String getToken(Integer userid, String openId, String secretToken, String pwd) {
        JWTSigner signer = new JWTSigner(secretToken);
        // 当前时间
        long iat = System.currentTimeMillis() / 1000L;
        // 过期时间,设置为三月以后，需要重新获取token
        long exp = iat + (259200L * 10 * 3);
        // 创建对象
        HashMap<String, Object> claims = new HashMap<String, Object>();
        claims.put("exp", exp);
        claims.put("iat", iat);
        claims.put("userid", AES.encrypt(userid.toString()));
        claims.put("WC_OPENID", openId);
        claims.put("pwd", pwd);
        return signer.sign(claims);
    }

    /**
     * 根据管理员登录账户，获取管理员id
     * @return
     */
    public static Integer getLoginAdminId() {
        // 获取当前用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Admin admin = (Admin) currentUser.getPrincipal();
        return admin.getAdminId();
    }

    public static Admin getLoginAdmin() {
        // 获取当前用户信息
        Subject currentUser = SecurityUtils.getSubject();
        return (Admin) currentUser.getPrincipal();
    }
}
