package org.springblade.auth.thirdparty.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
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.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springblade.auth.model.ThirdPartyAuthCallback;
import org.springblade.auth.model.ThirdPartyLogin;
import org.springblade.auth.thirdparty.ThirdPartyAuthRequest;
import org.springblade.auth.utils.ThirdPartyAuthUtil;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ThirdPartyAuthRequestImpl implements ThirdPartyAuthRequest {

    @Override
    public String getAuthorizeUrl(ThirdPartyLogin login) {
        AuthRequest authRequest = ThirdPartyAuthUtil.getAuthRequest(login);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        log.info("获取二维码路径成功! ");
        return authorizeUrl;
    }

    @Override
    public String login(ThirdPartyLogin login, ThirdPartyAuthCallback authCallback) {
        AuthCallback callback = new AuthCallback();
        BeanUtil.copyProperties(authCallback,callback);
        AuthRequest authRequest = ThirdPartyAuthUtil.getAuthRequest(login);
        AuthResponse<AuthUser> response = authRequest.login(callback);
        log.info("response："+response);
        log.info("response.getCode()："+response.getCode());
        log.info("response.getMsg()："+response.getMsg());
        if (response.getData() != null){
            log.info("response.getData().getUuid() ：" + response.getData().getUuid());
            log.info("response.getData().getRawUserInfo() ：" + response.getData().getRawUserInfo());
            log.info("response.getData().getRawUserInfo() ：" + response.getData().getGender().getCode());
        }
        if (response.ok()){
            log.info("获取回调信息成功！");
            if (response.getData().getToken() != null) {
                AuthToken token = response.getData().getToken();
                log.info("token: " + token.toString());
                if (StrUtil.isNotEmpty(token.getOpenId())) {
                    return token.getOpenId();
                } else {
                    return token.getCode();
                }
            } else {
                if (StrUtil.isNotEmpty(response.getData().getGender().getCode())){
                    return response.getData().getGender().getCode();
                }
            }
        }
        return null;
    }
}
