package cn.hanghui.outapi.platform.common.controller;

import cn.hanghui.outapi.platform.common.config.JwtConfig;
import cn.hanghui.outapi.platform.common.entity.po.Account;
import cn.hanghui.outapi.platform.common.entity.rest.RespCodeEnum;
import cn.hanghui.outapi.platform.common.entity.rest.RestCode;
import cn.hanghui.outapi.platform.common.exception.BusinessException;
import cn.hanghui.outapi.platform.common.exception.CommonException;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.common.controller
 * @class BaseController
 * @date 2023/5/10 下午3:10
 * @description
 */
public class BaseController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取登录用户名
     *
     * @param request
     * @return
     */
    public String getUserName(HttpServletRequest request) {
        String token = request.getHeader(JwtConfig.JWT_HEADER);
        try {
            JWT jwt = JWTUtil.parseToken(token);
            JWTPayload payload = jwt.getPayload();
            return payload.getClaim("name").toString();
        } catch (Exception e) {
            throw new CommonException(RestCode.UNAUTHORIZED.getMsg());
        }
    }

    /**
     * 获取token
     *
     * @return
     */
    public String getToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            throw new BusinessException(RestCode.FORBIDDEN);
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader(JwtConfig.JWT_HEADER);
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(RestCode.FORBIDDEN);
        }
        return token;
    }

    /**
     * 获取账号信息
     *
     * @return
     */
    public Account getAccount() {
        // 执行认证
        String token = getToken();
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(RestCode.FORBIDDEN);
        }
        String session = redisTemplate.opsForValue().get(JwtConfig.SESSION_PREFIX + token);
        Account account = JSON.parseObject(session, Account.class);
        if (Preconditions.isBlank(account)) {
            throw new BusinessException(RestCode.FORBIDDEN);
        }
        return account;
    }


}
