package com.mmc.iuav.user.controller;

import com.alibaba.fastjson2.JSONObject;
import com.mmc.iuav.auth.JwtConstant;
import com.mmc.iuav.auth.JwtUtil;
import com.mmc.iuav.http.BizException;
import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.response.ResultEnum;
import com.mmc.iuav.user.model.dto.BaseAccountDTO;
import com.mmc.iuav.user.model.dto.LoginSuccessDTO;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

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

/**
 * @author: zj
 * @Date: 2023/5/25 18:11
 */
public abstract class BaseController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 解析token，获取用户信息
     * @param request
     * @return
     */
//    public BaseAccountDTO getUserLoginInfo(HttpServletRequest request) {
//        String token = request.getHeader("token");
//        try {
//            Claims claims = JwtUtil.parseJwt(token);
//            String userId = claims.get(JwtConstant.USER_ACCOUNT_ID).toString();
////        String roleId = claims.get("").toString();
//            String tokenType = claims.get(JwtConstant.TOKEN_TYPE).toString();
//            return BaseAccountDTO.builder().id(Integer.parseInt(userId)).tokenPort(tokenType).build();
//        }catch (Exception e){
//            throw new BizException("Invalid token");
//        }
//    }

    /**
     * 使用token从redis获取用户信息
     * @param request
     * @return
     */
    public LoginSuccessDTO getUserLoginInfoFromRedis(HttpServletRequest request){
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            throw new BizException(ResultEnum.LOGIN_ACCOUNT_STATUS_ERROR);
        }
        String json = stringRedisTemplate.opsForValue().get(token);
        if (StringUtils.isBlank(json)){
            throw new BizException(ResultEnum.LOGIN_ACCOUNT_STATUS_ERROR);
        }
        LoginSuccessDTO loginSuccessDTO = JSONObject.parseObject(json, LoginSuccessDTO.class);
        return loginSuccessDTO;
    }
}
