package com.ningdatech.kqapi.sso.manage;

import com.ningdatech.kqapi.common.exception.BizException;
import com.ningdatech.kqapi.sso.model.dto.ReqSsoDTO;
import com.ningdatech.kqapi.sso.model.vo.SsoTokenVO;
import com.ningdatech.kqapi.sso.model.vo.SsoUserInfoVO;
import com.ningdatech.kqapi.sso.utils.HmacAuthUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;


/**
 * @author CMM
 * @since 2024/04/07 11:17
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class SsoManage {

    //@Value("${sso.token.internet-url}")
    @Value("${sso.token.zww-url}")
    private String tokenUrl;

    //@Value("${sso.user-info.internet-url}")
    @Value("${sso.user-info.zww-url}")
    private String userInfoUrl;

    @Value("${sso.access-key}")
    private String accessKey;

    @Value("${sso.secret-key}")
    private String secretKey;

    @Value("${sso.app-id}")
    private String appId;

    private final RestTemplate restTemplate;

    /**
     * 基于单点登录票据换取请求 token
     *
     * @param reqSsoDTO \
     * @return SsoTokenVO
     */
    public SsoTokenVO getToken(ReqSsoDTO reqSsoDTO) {
        String ticketId = reqSsoDTO.getTicketId();
        if (StringUtils.isBlank(ticketId)) {
            throw new BizException("登录票据不能为空!");
        }
        Map<String, String> header = HmacAuthUtil.generateHeader(tokenUrl, "POST", accessKey, secretKey);
        MultiValueMap<String, String> multiValueMap = HmacAuthUtil.convertToMultiValueMap(header);
        reqSsoDTO.setAppId(appId);
        HttpEntity<Object> httpEntity = new HttpEntity<>(reqSsoDTO, multiValueMap);
        SsoTokenVO res = restTemplate.postForObject(tokenUrl, httpEntity, SsoTokenVO.class);
        log.info("[RestTemplateTest-基于单点登录票据换取请求token] http request :{}", res);
        return res;
    }

    /**
     * 基于 token 获取用户信息
     *
     * @param reqSsoDTO \
     * @return SsoUserInfoVO
     */
    public SsoUserInfoVO getUserInfo(ReqSsoDTO reqSsoDTO) {
        String token = reqSsoDTO.getToken();
        if (StringUtils.isBlank(token)) {
            throw new BizException("token不能为空!");
        }
        Map<String, String> header = HmacAuthUtil.generateHeader(userInfoUrl, "POST", accessKey, secretKey);
        MultiValueMap<String, String> multiValueMap = HmacAuthUtil.convertToMultiValueMap(header);
        HttpEntity<Object> httpEntity = new HttpEntity<>(reqSsoDTO, multiValueMap);
        SsoUserInfoVO res = restTemplate.postForObject(userInfoUrl, httpEntity, SsoUserInfoVO.class);
        log.info("[RestTemplateTest-基于token获取用户信息] http request :{}", res);
        return res;
    }
}
