package admin.service.syncToken.impl;


import admin.model.syncToken.GetTokenRep;
import admin.model.syncToken.VerifyRep;
import admin.model.syncToken.VerifyReq;
import admin.service.syncToken.SyncTokenService;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class SyncTokenServiceImpl implements SyncTokenService {
    @Override
    public GetTokenRep getToken() {
        String url="http://36.212.226.237:5065/oauth/token";
        //入参
        String grantType = "client_credentials";
        String scope = "all";
        String clientId = "SJKHKJEDKEGA";
        String clientSecret = "2384944274";
        log.info("门户免密获取token,url:{},入参:grantType:{},scope:{},clientId:{},clientSecret:{}",url,grantType,scope,clientId,clientSecret);
        // 发送POST请求，使用form-data格式
        HttpResponse response = HttpRequest.post(url)
                .form("grant_type", grantType)
                .form("scope", scope)
                .form("client_id", clientId)
                .form("client_secret", clientSecret)
                .execute();
        GetTokenRep rep = new GetTokenRep();
        if(response!=null){
            String body = response.body();
            rep = JSONUtil.toBean(body, GetTokenRep.class);
        }
        return rep;
    }

    @Override
    public VerifyRep verify(String syncToken, String token) {
        // 门户接口URL
        String url = "http://36.212.226.237:5065/oauth/verify"; // 请替换为你的门户接口实际URL
        // 请求头
        String authorizationHeader = "Bearer " + syncToken; // 请替换为你的客户端token
        String contentTypeHeader = "application/json";
        // 请求体
        VerifyReq verifyReq = new VerifyReq();
        verifyReq.setUnifiedUserToken(token);
        log.info("门户检验token合法性,url:{},入参:verifyReq:{}",url,verifyReq);
        HttpResponse response = HttpRequest.post(url)
                .header("Authorization", authorizationHeader)
                .header("Content-Type", contentTypeHeader)
                .body(JSONUtil.toJsonStr(verifyReq))
                .execute();
        VerifyRep verifyRep = new VerifyRep();
        verifyRep=JSONUtil.toBean(response.body(), VerifyRep.class);
        return verifyRep;
    }
}
