package com.chinaweal.aiccs.common.base.controller;

import com.chinaweal.aiccs.common.base.entity.dto.login.LoginMessage;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.user.shiro.JWTToken;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * BaseController用于存储一些简单的controller层通用方法
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2020/6/1 16:29
 **/
public abstract class BaseController {

    protected static final RestResult<?> OK = RestResult.ok();

    /**
     * session存放用户信息的key
     */
    protected static final String USER_KEY = ConstantsUtil.USER_SESSION_NAME;

    /**
     * session存放用于druid识别身份的key
     */
    protected static final String DRUID_SESSION_KEY = "druidSessionKey";

    @Autowired
    public JWTToken jwtToken;

    /**
     * 获取登录信息
     *
     * @param request 前端请求
     * @return 获取结果
     */
    public LoginMessage getLoginMessage(HttpServletRequest request) {
        String token = request.getHeader(JWTToken.TOKEN);
//        Cookie[] cookies = request.getCookies();
//        if(cookies == null) return null;
//        String token = null;
//        for (Cookie cookie : cookies) {
//            if(cookie.getName().equals(JWTToken.TOKEN)){
//                token = cookie.getValue();
//            }
//        }
        if (StringUtils.isBlank(token)) return null;
        Jws<Claims> claimsJws = jwtToken.parseJWT(token);
        LoginMessage message = new LoginMessage();
        Claims chaims = claimsJws.getBody();
        message.setUserId(chaims.get("uid", String.class));
        message.setNickName(chaims.get("nick_name", String.class));
        message.setUsername(chaims.get("username", String.class));
        message.setHost(chaims.get("host", String.class));
        return message;
    }

    /**
     * 获取登录用户
     * @param request 请求信息
     * @return 获取结果
     * @author lroyia
     * @since 2021年1月20日 15:11:44
     */
    public static AICUser getLoginUser(HttpServletRequest request){
//        String token = request.getHeader(JWTToken.TOKEN);
//        return (AICUser) request.getSession().getAttribute(USER_KEY);
        return SSOUtil.getUser(request);
    }
}
