package com.bcxin.sync.controller;

import com.bcxin.sync.common.utils.HuaweiIvmUtil;
import com.bcxin.sync.configs.SyncConfig;
import com.bcxin.sync.dtos.request.EmptyRequest;
import com.bcxin.sync.dtos.response.result.RespResult;
import com.bcxin.sync.service.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义Oauth2获取令牌接口
 */
@Slf4j
@Api(tags = "授权接口")
@RestController
public class AuthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Autowired
    private SyncConfig syncConfig;
    @Autowired
    private RedisCache redisCache;

    @ApiOperation(value = "Oauth2登录认证", hidden = true)
    @RequestMapping(value = "/oauth/token")
    public OAuth2AccessToken postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException, HttpRequestMethodNotSupportedException {
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        return oAuth2AccessToken;
    }


    @ApiOperation(value = "获取华为云IVM的access_token")
    @ApiImplicitParam(name = "accessToken（v5职员的token）", required = true, paramType = "header",dataType = "String")
    @PostMapping("/api/hw/ivm/get-access-token")
    public RespResult ivmGetAccessToken(EmptyRequest request) {
        log.info("获取华为云IVM的access_token");
        String accessToken = HuaweiIvmUtil.getAccessToken(syncConfig.getHuaweiIvm().getHost(), syncConfig.getHuaweiIvm().getUserId(), syncConfig.getHuaweiIvm().getAk(), syncConfig.getHuaweiIvm().getSk(), redisCache);
        log.info("获取华为云IVM的access_token，成功");
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("accessToken", accessToken);
        resultMap.put("userId", syncConfig.getHuaweiIvm().getUserId());
        return RespResult.successful("获取成功", resultMap);
    }
}
