package com.yunzhupaas.permission.util.implicit.request;

import com.alibaba.fastjson.JSONObject;
import com.yunzhupaas.permission.util.implicit.ImplicitDefaultSource;
import com.yunzhupaas.permission.util.implicit.ImplicitLoginRequest;
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;

public class ImplicitQywxRequest extends AuthDefaultRequest implements ImplicitLoginRequest {

    public ImplicitQywxRequest(AuthConfig config) {
        super(config, ImplicitDefaultSource.WECHAT_ENTERPRISE);
    }

    @Override
    public String getAuthLoginLink() {
        return UrlBuilder.fromBaseUrl(this.source.authorize())
                .queryParam("appid", this.config.getClientId())
                .queryParam("redirect_uri", this.config.getRedirectUri())
                .queryParam("response_type", "code")
                .queryParam("scope", "snsapi_privateinfo")
                .queryParam("agentid", this.config.getAgentId())
                .queryParam("state", "STATE#wechat_redirect")
                .build();
    }

    @Override
    public AuthResponse getUserId(AuthCallback authCallback) {
        try {
            this.checkCode(authCallback);
            AuthToken authToken = this.getAccessToken(authCallback);
            AuthUser user = this.getUserInfo(authToken);
            return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(user).build();
        } catch (Exception var4) {
            Exception e = var4;
            Log.error("Failed to login with oauth authorization.", e);
            return this.responseError(e);
        }
    }

    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();
    }

    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        try {
            String response = this.doGetAccessToken();
            JSONObject object = this.checkResponse(response);
            AuthToken authToken = AuthToken.builder()
                    .accessToken(object.getString("access_token"))
                    .code(authCallback.getCode())
                    .expireIn(object.getIntValue("expires_in")).build();
            return authToken;
        } catch (Exception var5) {
            Exception e = var5;
            throw new AuthException("企业微信获取token失败", e);
        }
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        String response = this.doGetUserInfo(authToken);
        JSONObject object = this.checkResponse(response);
        if (!object.containsKey("userid")) {
            throw new AuthException(AuthResponseStatus.UNIDENTIFIED_PLATFORM, this.source);
        } else {
            return AuthUser.builder().rawUserInfo(object).uuid(object.getString("userid")).token(authToken).source(this.source.toString()).build();
        }
    }

    protected String doGetAccessToken() {
        return (new HttpUtils(this.config.getHttpConfig())).get(this.accessTokenUrl()).getBody();
    }

    protected String accessTokenUrl() {
        return UrlBuilder.fromBaseUrl(this.source.accessToken())
                .queryParam("corpid", this.config.getClientId())
                .queryParam("corpsecret", this.config.getClientSecret())
                .build();
    }

    protected String doGetUserInfo(AuthToken authToken) {
        return (new HttpUtils(this.config.getHttpConfig())).get(this.userInfoUrl(authToken)).getBody();
    }

    protected String userInfoUrl(AuthToken authToken) {
        return UrlBuilder.fromBaseUrl(this.source.userInfo())
                .queryParam("access_token", authToken.getAccessToken())
                .queryParam("code", authToken.getCode())
                .build();
    }

    private JSONObject checkResponse(String response) {
        JSONObject object = JSONObject.parseObject(response);
        if (object.containsKey("errcode") && object.getIntValue("errcode") != 0) {
            throw new AuthException(object.getString("errmsg"), this.source);
        } else {
            return object;
        }
    }


}

