package com.sf.oauth.request;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.sf.common.constant.HttpStatus;
import com.sf.common.core.domain.AjaxResult;
import com.sf.oauth.config.AuthConfig;
import com.sf.oauth.enums.AuthDefaultSource;
import com.sf.oauth.enums.AuthUserGender;
import com.sf.oauth.enums.scope.AuthHuaweiScope;
import com.sf.oauth.exception.AuthException;
import com.sf.oauth.domain.AuthCallback;
import com.sf.oauth.domain.AuthToken;
import com.sf.oauth.domain.AuthUser;
import com.sf.oauth.utils.AuthScopeUtils;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;


/**
 * 华为授权登录
 *
 * @author zkun
 */
@Slf4j
public class AuthHuaweiRequest extends AuthDefaultRequest {

    public AuthHuaweiRequest(AuthConfig config) {
        super(config, AuthDefaultSource.HUAWEI);
    }


    /**
     * 获取access token
     *
     * @param authCallback 授权成功后的回调参数
     * @return token
     * @see AuthDefaultRequest#authorize()
     * @see AuthDefaultRequest#authorize(String)
     */
    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        Map<String, Object> form = new HashMap<>(8);
        form.put("grant_type", "authorization_code");
        form.put("code", authCallback.getCode());
        form.put("client_id", config.getClientId());
        form.put("client_secret", config.getClientSecret());
        form.put("redirect_uri", config.getRedirectUri());
        String response = HttpUtil.post(source.accessToken(), form);
        return getAuthToken(response);
    }

    /**
     * 使用token换取用户信息
     *
     * @param authToken token信息
     * @return 用户信息
     * @see AuthDefaultRequest#getAccessToken(AuthCallback)
     */
    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        Map<String, Object> form = new HashMap<>(8);
        form.put("nsp_ts", System.currentTimeMillis() + "");
        form.put("access_token", authToken.getAccessToken());
        form.put("nsp_svc", "GOpen.User.getInfo");
        form.put("getNickName", "1");
        String response = HttpUtil.post(source.userInfo(), form);
        log.info(response);

        JSONObject object = JSONObject.parseObject(response);
        this.checkResponse(object);
        AuthUserGender gender = getRealGender(object);
        return AuthUser.builder()
                .rawUserInfo(object)
                .uuid(object.getString("unionID"))
                .username(object.getString("displayName"))
                .nickname(object.getString("displayName"))
                .gender(gender)
                .avatar(object.getString("headPictureURL"))
                .mobileNumber(object.getString("mobileNumber"))
                .email(object.getString("email"))
                .token(authToken)
                .source(source.toString())
                .build();
    }

    /**
     * 刷新access token （续期）
     *
     * @param authToken 登录成功后返回的Token信息
     * @return AuthResponse
     */
    @Override
    public AjaxResult refresh(AuthToken authToken) {
        Map<String, Object> form = new HashMap<>(8);
        form.put("client_id", config.getClientId());
        form.put("client_secret", config.getClientSecret());
        form.put("refresh_token", authToken.getRefreshToken());
        form.put("grant_type", "refresh_token");
        String response = HttpUtil.post(source.refresh(), form);
        return AjaxResult.success(getAuthToken(response));
    }

    private AuthToken getAuthToken(String response) {
        JSONObject object = JSONObject.parseObject(response);

        this.checkResponse(object);

        return AuthToken.builder()
                .accessToken(object.getString("access_token"))
                .expireIn(object.getIntValue("expires_in"))
                .refreshToken(object.getString("refresh_token"))
                .scope(object.getString("scope"))
                .tokenType(object.getString("token_type"))
                .idToken(object.getString("id_token"))
                .build();
    }

    /**
     * 返回带{@code state}参数的授权url，授权回调时会带上这个{@code state}
     *
     * @param state state 验证授权流程的参数，可以防止csrf
     * @return 返回授权地址
     */
    @Override
    public String authorize(String state) {
        Map<String, Object> form = new HashMap<>(8);
        form.put("client_id", config.getClientId());
        form.put("client_secret", config.getClientSecret());
        form.put("redirect_uri", config.getRedirectUri());
        form.put("state", getRealState(state));
        form.put("response_type", "code");
        form.put("access_type", "offline");
        form.put("scope", this.getScopes(" ", true, AuthScopeUtils.getDefaultScopes(AuthHuaweiScope.values())));
        return HttpUtil.get(source.authorize(), form);
    }


    /**
     * 获取用户的实际性别。华为系统中，用户的性别：1表示女，0表示男
     *
     * @param object obj
     * @return AuthUserGender
     */
    private AuthUserGender getRealGender(JSONObject object) {
        int genderCodeInt = object.getIntValue("gender");
        String genderCode = genderCodeInt == 0 ? "0" : (genderCodeInt == 1) ? "1" : genderCodeInt + "";
        return AuthUserGender.getRealGender(genderCode);
    }

    /**
     * 校验响应结果
     *
     * @param object 接口返回的结果
     */
    private void checkResponse(JSONObject object) {
        if (object.containsKey("NSP_STATUS")) {
            throw new AuthException(object.getString("error"));
        }
        if (object.containsKey("error")) {
            throw new AuthException(object.getString("sub_error") + ":" + object.getString("error_description"));
        }
    }
}
