package com.ruoyi.web.controller.system;

import cn.hutool.core.date.DateException;
import com.ruoyi.common.constant.JustAuthConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.SysAuthService;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Duke_yzl
 * @date 20230617.01
 * @describe：
 */
@RestController
@RequestMapping("/oauth")
public class SysAuthController {


    @Resource
    private SysAuthService authService;


    @Resource(name = "weChatMpAuthRequest")
    private AuthRequest weChatMpAuthRequest;

    @Resource(name = "dingTalkAuthRequest")
    private AuthRequest dingTalkAuthRequest;

    @Resource(name = "aliyunAuthRequest")
    private AuthRequest aliyunAuthRequest;
    @Resource(name = "weChatAppletAuthRequest")
    private AuthRequest weChatAppletAuthRequest;

    @RequestMapping("/render/{type}")
    public AjaxResult renderAuth(@PathVariable String type) {
        AuthRequest authRequest = geAuthRequest(type);
        return AjaxResult.success("",authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback/{type}")
    public AjaxResult login(@PathVariable String type, AuthCallback callback) {
        AuthRequest authRequest = geAuthRequest(type);
        AuthUser authUser = (AuthUser) authRequest.login(callback).getData();
        return authService.callbackLogin(authUser);
    }

    private AuthRequest geAuthRequest(String type) {
        AuthRequest authRequest = null;
        switch (type){
            case JustAuthConstants.WECHATMP:
                authRequest = weChatMpAuthRequest;
                break;
            case JustAuthConstants.DINGTALK:
                authRequest = dingTalkAuthRequest;
                break;
            case JustAuthConstants.ALIYUN:
                authRequest = aliyunAuthRequest;
                break;
            case JustAuthConstants.WECHATAPPLET:
                authRequest = weChatAppletAuthRequest;
                break;
            default:
                throw new DateException("不支持的登录方式");
        }
        return authRequest;
    }

}