package com.yunzhupaas.permission.util.implicit;

import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.exception.LoginException;
import com.yunzhupaas.permission.util.implicit.request.ImplicitDingTalkRequest;
import com.yunzhupaas.permission.util.implicit.request.ImplicitQywxRequest;
import com.yunzhupaas.permission.util.socials.AuthCallbackNew;
import com.yunzhupaas.permission.util.socials.SocialsConfig;
import com.yunzhupaas.util.StringUtil;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;

/**
 * 免登工具类
 *
 * @author 云筑产品开发平台组
 * @version v5.0.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2024/5/23 11:09:26
 */
@Component
public class ImplicitLoginUtil {
    @Autowired
    private SocialsConfig socialsConfig;
    @Autowired
    private ConfigValueUtil configValueUtil;

    public String getAuthLink(String source) {
        ImplicitLoginRequest authRequest = this.getAuthRequest(source, null, null);
        return authRequest.getAuthLoginLink();
    }

    public String loginByCode(String source, String code, String state) {
        //获取第三方请求
        AuthCallbackNew callback = new AuthCallbackNew();
        callback.setAuthCode(code);
        callback.setAuth_code(code);
        callback.setAuthorization_code(code);
        callback.setCode(code);
        callback.setState(state);
        ImplicitLoginRequest authRequest = this.getAuthRequest(source, null, null);
        AuthResponse<AuthUser> res = authRequest.getUserId(callback);
        if (AuthResponseStatus.FAILURE.getCode() == res.getCode()) {
            throw new LoginException("连接失败！");
        } else if (AuthResponseStatus.SUCCESS.getCode() != res.getCode()) {
            throw new LoginException("授权失败:" + res.getMsg());
        }
        //登录用户第三方id
        return getSocialUuid(res);
    }

    private String getSocialUuid(AuthResponse<AuthUser> res) {
        String uuid = res.getData().getUuid();
        if (res.getData().getToken() != null && StringUtil.isNotEmpty(res.getData().getToken().getUnionId())) {
            uuid = res.getData().getToken().getUnionId();
        }
        return uuid;
    }

    /**
     * 根据配置信息获取请求对象
     *
     * @param
     * @return
     * @copyright 深圳市乐程软件有限公司
     * @date 2024/7/21
     */
    public ImplicitLoginRequest getAuthRequest(String source, String userId, String tenantId) {
        ImplicitLoginRequest authRequest = null;
        String url = configValueUtil.getApiDomain() + "/api/oauth/Login/implicit";
        SocialsConfig.Config socialConfig;
        switch (source.toLowerCase()) {
            case "dingtalk":
                socialConfig = socialsConfig.getSocialMap().get("dingtalk");
                authRequest = new ImplicitDingTalkRequest(AuthConfig.builder()
                        .clientId(socialConfig.getClientId())
                        .clientSecret(socialConfig.getClientSecret())
                        .redirectUri(URLEncoder.encode(url))
                        .build());
                break;
            case "wechat_enterprise":
                socialConfig = socialsConfig.getSocialMap().get("wechat_enterprise");
                authRequest = new ImplicitQywxRequest(AuthConfig.builder()
                        .clientId(socialConfig.getClientId())
                        .clientSecret(socialConfig.getClientSecret())
                        .redirectUri(URLEncoder.encode(url))
                        .agentId(socialConfig.getAgentId())
                        .build());
                break;
            default:
                break;
        }
        if (null == authRequest) {
            throw new AuthException(MsgCode.OA024.get());
        }
        return authRequest;
    }
}

