package com.fastbee.iot.zhanlian;

import com.fastbee.deviceData.api.devlink.service.ZhanLianConfig;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;



@AllArgsConstructor
@Builder

@Data
public class ZhanLianAuthorizationService {


    public static String getAuthEndpoint(ZhanLianConfig zhanLianConfig){
        String ak = zhanLianConfig.getAk();
        String sk = zhanLianConfig.getSk();
        String authId = zhanLianConfig.getAuthId();
        String endpoint = zhanLianConfig.getEndpoint();
        String sign;
        long time = System.currentTimeMillis();
        String message = "ak=" + ak + "&authId=" + authId + "&time=" + time;
        try {
            SecretKeySpec keySpec = new SecretKeySpec(
                    sk.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(keySpec);
            byte[] rawHmac = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
            sign = DatatypeConverter.printHexBinary(rawHmac).toLowerCase();
        } catch (Exception e) {
            throw new RuntimeException("签名生成失败！ : " + e.getMessage(), e);
        }
        return endpoint+"?ak="+ak+"&time="+time+"&sign="+sign+"&authId="+authId;
    }


    public static void main(String[] args) {

    }
}
