package com.fastbee.data.controller.userRecharge.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;


/**
 * @author mijiupro
 */
@Component("zhanlianAuthorizationService1")
@AllArgsConstructor
@Builder
@NoArgsConstructor
@Data
public class ZhanLianAuthorizationService {

    private  String ak = "nanyang";

    private  String sk = "VMSMSV4D";

    private  String authId  = "25";

    private  String endpoint = "https://plat.developlink.cloud/prod-api/iot/data/forward";

    public String getAuthEndpoint(){
        return endpoint + getDefaultAuth();
    }


    /**
     * 鉴权参数生成
     */
    public String getDefaultAuth(){
        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();
//            System.err.println("result:"+sign);
        } catch (Exception e) {
            throw new RuntimeException("签名生成失败！ : " + e.getMessage(), e);
        }
      return "?ak="+ak+"&time="+time+"&sign="+sign+"&authId="+authId;
    }

    public String getAuth(ZhanLianConfig zhanLianConfig){
        String ak = zhanLianConfig.getAk();
        String sk = zhanLianConfig.getSk();
        String authId = zhanLianConfig.getAuthId();
        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 "?ak="+ak+"&time="+time+"&sign="+sign+"&authId="+authId;
    }


    public static void main(String[] args) {
        ZhanLianAuthorizationService de = new ZhanLianAuthorizationService();
        System.out.println("完整请求路径："+de.getAuthEndpoint());

    }
}
