package com.ruoyi.common.just;

import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.log.Log;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthDefaultRequest;
import me.zhyd.oauth.utils.HttpUtils;
import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UrlBuilder;

/**
 * @author Duke_yzl
 * @date 20230619.01
 * @describe：小程序平台登录
 */
public class AuthAppletRequest extends AuthDefaultRequest {


    public AuthAppletRequest(AuthConfig config) {
        super(config, AuthCustomSource.APPLET);
    }

    public AuthAppletRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, AuthCustomSource.APPLET, authStateCache);
    }


    /**
     * 返回获取accessToken的url
     *
     * @param code 授权码
     * @return 返回获取accessToken的url
     */
    @Override
    protected String accessTokenUrl(String code) {
        return UrlBuilder.fromBaseUrl(source.accessToken())
                .queryParam("js_code", code)
                .queryParam("appid", config.getClientId())
                .queryParam("secret", config.getClientSecret())
                .queryParam("grant_type", "authorization_code")
                .build();
    }

    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        return null;
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        return null;
    }

    /**
     * 登录操作
     * @param authCallback 用于接收回调参数的实体
     * @return
     */
    @Override
    public AuthResponse login(AuthCallback authCallback) {
        try {
            checkCode(authCallback);

            String response = new HttpUtils().get(accessTokenUrl(authCallback.getCode())).getBody();
            //小程序返回的状态
            JSONObject accessTokenObject = JSONObject.parseObject(response);
            //检查异常
            checkResponse(accessTokenObject);

            String openId = accessTokenObject.getString("openid");
            //小程序用户信息小程序端传过来
            JSONObject jsonObject = JSONObject.parseObject(authCallback.getState());
            AuthUser user = AuthUser.builder()
                    .avatar(jsonObject.getString("avatarUrl"))
                    .nickname(jsonObject.getString("nickName"))
                    .uuid(openId)
                    .source(source.toString())
                    .build();
            return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(user).build();
        } catch (Exception e) {
            Log.error("Failed to login with oauth authorization.", e);
            return responseError(e);
        }
    }
    /**
     * 处理{@link AuthDefaultRequest#login(AuthCallback)} 发生异常的情况，统一响应参数
     *
     * @param e 具体的异常
     * @return AuthResponse
     */
    AuthResponse responseError(Exception e) {
        int errorCode = AuthResponseStatus.FAILURE.getCode();
        String errorMsg = e.getMessage();
        if (e instanceof AuthException) {
            AuthException authException = ((AuthException) e);
            errorCode = authException.getErrorCode();
            if (StringUtils.isNotEmpty(authException.getErrorMsg())) {
                errorMsg = authException.getErrorMsg();
            }
        }
        return AuthResponse.builder().code(errorCode).msg(errorMsg).build();
    }

    /**
     * 检查响应内容是否正确
     *
     * @param object 请求响应内容
     */
    private void checkResponse(JSONObject object) {
        // oauth/token 验证异常
        if (object.containsKey("errcode")) {
            throw new AuthException(object.getIntValue("errcode"), object.getString("errmsg"));
        }
    }

}