package com.fdkankan.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Hb_zzZ on 2020/8/25.
 */
@Slf4j
@Component
public class RubberSheetingUtil {

    @Value("${scaling.group.id}")
    private String ScalingGroupId;

    @Value("${scaling.rule.ari}")
    private String ScalingRuleAri;

    private static String AccessKeyId = "LTAI4GKZQBM1zZZZBJK7nGjR";

    private String sign(String action, Map<String, String> parameters) throws Exception{
        final String HTTP_METHOD = "GET";

        final String ALGORITHM = "HmacSHA1";
        final String ENCODING = "UTF-8";
        String keySecret = "bo1ura8KODXASVyZ5fofy0fWFILumz&";

        // 对参数进行排序
        String[] sortedKeys = parameters.keySet().toArray(new String[]{});
        Arrays.sort(sortedKeys);

        final String SEPARATOR = "&";

        // 生成stringToSign字符串
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append(HTTP_METHOD).append(SEPARATOR);
        stringToSign.append(percentEncode("/")).append(SEPARATOR);

        StringBuilder canonicalizedQueryString = new StringBuilder();
        for(String key : sortedKeys) {
            // 这里注意对key和value进行编码
            canonicalizedQueryString.append("&")
                    .append(percentEncode(key)).append("=")
                    .append(percentEncode(parameters.get(key)));
        }
//        System.out.println("canonicalizedQueryString:" + canonicalizedQueryString.toString());

        // 这里注意对canonicalizedQueryString进行编码
        stringToSign.append(percentEncode(
                canonicalizedQueryString.toString().substring(1)));
//        System.out.println("stringToSign:" + stringToSign.toString());

        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(new SecretKeySpec(keySecret.getBytes(ENCODING), ALGORITHM));
        byte[] signData = mac.doFinal(stringToSign.toString().getBytes(ENCODING));

        String signature = new String(org.apache.commons.codec.binary.Base64.encodeBase64(signData));
        return signature;
    }

    private static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    private static String formatIso8601Date(Date date) {
        SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
        df.setTimeZone(new SimpleTimeZone(0, "GMT"));
        return df.format(date);
    }

    private static final String ENCODING = "UTF-8";

    private static String percentEncode(String value) throws UnsupportedEncodingException {
        return value != null ? URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null;
    }

    public static void main(String[] args) {

        String text = "";
        for(int i = 0, len = 100; i < len; i ++){
//            createEcs();
        }
//        System.out.println(deleteEcs("i-wz95huv20p8v6csu6q1q"));

//        try{
//            System.out.println(FileUtils.readFile("C:\\Users\\hisun\\Downloads\\hosts.txt"));
//            System.out.println(1);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
    }

    public String createEcs(){
        try {

            boolean tag = true;
            Map<String, String> parameters = null;
            while (tag){
                parameters = new HashMap<String, String>();
                // 加入请求参数
                parameters.put("Action", "ExecuteScalingRule");
                parameters.put("ScalingRuleAri", ScalingRuleAri);
                parameters.put("Version", "2014-08-28");
                parameters.put("AccessKeyId", AccessKeyId);
                parameters.put("Timestamp", formatIso8601Date(new Date()));
                parameters.put("SignatureMethod", "HMAC-SHA1");
                parameters.put("SignatureVersion", "1.0");
                parameters.put("SignatureNonce", UUID.randomUUID().toString());
                parameters.put("Format", "JSON");

                String signature = sign("AttachInstances", parameters);
                System.out.println(signature);
                if(!signature.contains("+") && !signature.contains("/")){
                    tag = false;
                }
                parameters.put("Signature", signature);
            }


            StringBuffer parameterBuffer = new StringBuffer();
            if (parameters != null) {
                Iterator iterator = parameters.keySet().iterator();
                String key = null;
                String value = null;
                while (iterator.hasNext()) {
                    key = (String) iterator.next();
                    if (parameters.get(key) != null) {
                        value = (String) parameters.get(key);
                    } else {
                        value = "";
                    }

                    parameterBuffer.append(key).append("=").append(value);
                    if (iterator.hasNext()) {
                        parameterBuffer.append("&");
                    }
                }
            }
//            System.out.println("POST parameter : " + parameterBuffer.toString());
            return OkHttpUtils.httpGet("http://ess.aliyuncs.com?" + parameterBuffer.toString());
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public String deleteEcs(String id){
        try {
            boolean tag = true;
            Map<String, String> parameters = null;
            while (tag){
                parameters = new HashMap<String, String>();
                // 加入请求参数
                parameters.put("Action", "RemoveInstances");
                parameters.put("InstanceId.1", id);
                parameters.put("ScalingGroupId", ScalingGroupId);
                parameters.put("Version", "2014-08-28");
                parameters.put("AccessKeyId", AccessKeyId);
                parameters.put("Timestamp", formatIso8601Date(new Date()));
                parameters.put("SignatureMethod", "HMAC-SHA1");
                parameters.put("SignatureVersion", "1.0");
                parameters.put("SignatureNonce", UUID.randomUUID().toString());
                parameters.put("Format", "JSON");

                String signature = sign("AttachInstances", parameters);
//            System.out.println(signature);
                if(!signature.contains("+") && !signature.contains("/")){
                    tag = false;
                }
                parameters.put("Signature", signature);
            }

            StringBuffer parameterBuffer = new StringBuffer();
            if (parameters != null) {
                Iterator iterator = parameters.keySet().iterator();
                String key = null;
                String value = null;
                while (iterator.hasNext()) {
                    key = (String) iterator.next();
                    if (parameters.get(key) != null) {
                        value = (String) parameters.get(key);
                    } else {
                        value = "";
                    }

                    parameterBuffer.append(key).append("=").append(value);
                    if (iterator.hasNext()) {
                        parameterBuffer.append("&");
                    }
                }
            }
//            System.out.println("POST parameter : " + parameterBuffer.toString());
            return OkHttpUtils.httpGet("http://ess.aliyuncs.com?" + parameterBuffer.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
