package com.xjrsoft.module.system.controller;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaCookie;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.context.model.SaResponse;
import cn.dev33.satoken.oauth2.config.SaOAuth2Config;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Handle;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.config.CommonPropertiesConfig;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.service.IUserService;
import com.xjrsoft.module.organization.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * Oauth2
 */
@Api(tags = "Oauth2")
@RestController
@AllArgsConstructor
public class Oauth2Controller {

    @Autowired
    private CommonPropertiesConfig commonPropertiesConfig;

    private final RedisUtil redisUtil;

    private final IUserService userService;

    @RequestMapping("/oauth2/*")
    @ApiOperation(value = "处理所有OAuth相关请求")
    public Object request() {
        return SaOAuth2Handle.serverRequest();
    }

    @GetMapping("/oauth2/user/info")
    @ApiOperation(value = "获取当前用户信息")
    public RT<UserVo> userInfo() {
        //获取用户id
        Long userId =  StpUtil.getLoginIdAsLong();
        User user = userService.getById(userId);
        if (user == null) {
            return RT.error("找不到此用户！");
        }
        return RT.ok(BeanUtil.toBean(user, UserVo.class));
    }

    // Sa-OAuth2 定制化配置
    @Autowired
    public void setSaOAuth2Config(SaOAuth2Config cfg) {
        // 配置：未登录时返回的View
        cfg.setNotLoginView(() -> {
                SaRequest req = SaHolder.getRequest();
                Map<String, String> paramMap = req.getParamMap();
                StringBuilder param = new StringBuilder();
                paramMap.forEach((k, v) -> {
                    param.append("&").append(k).append("=").append(v);
                });
                param.deleteCharAt(0);
                String callBackUrl = String.format("%s/oauth2/authorize?%s", commonPropertiesConfig.getDomainApi(), param);

                String key = GlobalConstant.OAUTH2 + IdUtil.simpleUUID();
                redisUtil.set(key, callBackUrl, 86400);

                SaResponse res = SaHolder.getResponse();
                SaCookie cookie = new SaCookie()
                        .setName("Oauth2Info")
                        .setValue(key);

                res.addCookie(cookie);

                res.redirect(String.format("%s/#/login", commonPropertiesConfig.getDomainWeb()));
                return null;
            }).
            // 配置：确认授权时返回的View
            setConfirmView((clientId, scope) -> {
                Map<String, Object> map = new HashMap<>();
                map.put("clientId", clientId);
                map.put("scope", scope);
                return new ModelAndView("confirm.html", map);
        });
    }
}
