package com.fastbee.data.controller.printer.yilianyun;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class YiLianYunAuthorizationService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private  String clientId = "1044721086";
    private String clientSecret = "dfb761fb75768df0066f9614dc507531";

    private  String grantType = "client_credentials";

    private  String sign;

    private  String scope = "all";
    private  Long timestamp;
    private String id = "550e8400-e29b-41d4-a716-446655440000";
    private  String endpoint = "https://open-api.10ss.net/v2/oauth/oauth";


    public String getAccessToken() {
        String cacheToken = stringRedisTemplate.opsForValue().get("yilianyun:user:token");
        if (!Objects.isNull(cacheToken)){
            System.err.println("缓存中获取token:"+cacheToken);
            return cacheToken;
        }
        String token = getAuth();
//        System.err.println("从服务器获取token:"+token);
//        return token;
        stringRedisTemplate.opsForValue().set("yilianyun:user:token",token,3600*24*20, TimeUnit.MILLISECONDS);
        return stringRedisTemplate.opsForValue().get("yilianyun:user:token");
    }

    public String getAuth() {
        timestamp = System.currentTimeMillis();
        sign=YiLianYunUtil.getSign(timestamp);
        //构建请求体
        Map<String,Object> param= new HashMap<>();
        param.put("client_id",clientId);
        param.put("grant_type",grantType);
        param.put("sign",sign);
        param.put("scope",scope);
        param.put("timestamp",timestamp);
        param.put("id",id);
        YiLianYunBaseService yiLianYunBaseService = new YiLianYunBaseService();
        JSONObject resp = yiLianYunBaseService.baseRequest(endpoint, param);
        System.err.println(resp);
        return resp.getStr("access_token");
    }





    public static void main(String[] args) {
       YiLianYunPrintService yiLianYunPrintService = new YiLianYunPrintService();
//        yiLianYunPrintService.print("<FS2>您好</FS2>");
    }
}
