package com.tuoheng.config;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.mapper.ClientUserMapper;
import com.tuoheng.model.dto.LoginUser;
import com.tuoheng.model.po.UserPo;
import com.tuoheng.service.CurrentUser;
import com.tuoheng.until.EncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author chenjiandong
 * @description: TODO
 * @date 2022/10/27 11:34
 */
@Component
public class LoginUserHandler implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentUser.class) &&
                parameter.getParameterType().isAssignableFrom(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) {
        // header中获取用户token
        String token = request.getHeader("th-token");
        String oUserJson = request.getHeader("o-user-json");
        if(StringUtils.isEmpty(token) || StringUtils.isEmpty(oUserJson)){
            return new LoginUser();
        }
        String json = EncryptUtil.decodeUTF8StringBase64(oUserJson);
        JSONObject jsonObject = JSON.parseObject(json);
        String username = jsonObject.getString("username");
        Long oidcUserId = jsonObject.getLong("oUserId");
        // 这里可以自定义封装自己的用户信息
        //UserPo userPo = clientUserMapper.getUserByUserName(username);
        LoginUser user = new LoginUser()
                .setUsername(username)
                .setUserId(oidcUserId)
                .setThToken(token);
        return user;
    }
}
