package com.jeeplus.modules.filePreview;

import org.apache.commons.codec.binary.Base64;

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

public class OssUpload {
    private String ossAccessId = "LTAIi7VuxcgfJR2x";  // 你的访问AK信息
    private String ossAccessKey = "Q9xF9V7tcnCI28ttUsP8H4GyAhZta7";  // 你的访问AK信息
    private String ossEndpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    public void sendPost() throws ParseException {
        try{
            final String HTTP_METHOD = "GET";
            Map<String, String> parameters = new HashMap<String, String>();
            // 加入请求参数
            parameters.put("Action", "DescribeRegions");
            parameters.put("Version", "2014-05-26");
            parameters.put("AccessKeyId", ossAccessId);
            parameters.put("TimeStamp", formatIso8601Date(new Date())); //TimeStamp
            parameters.put("SignatureMethod", "HMAC-SHA1");
            parameters.put("SignatureVersion", "1.0");
            parameters.put("SignatureNonce", UUID.randomUUID().toString());
            parameters.put("Format", "XML");

//            parameters.put("CanonicalizedResource", "/attachment-file/workProjectRemote/12177742302292375/abc7dedc12c0773e866cb3add0ee67ac.pdf?uploads");
//            parameters.put("Authorization","OSS LTAIi7VuxcgfJR2x:Q9xF9V7tcnCI28ttUsP8H4GyAhZta7=");

            // 对参数进行排序
            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)));
            }

            // 这里注意对canonicalizedQueryString进行编码
            stringToSign.append(percentEncode(
                    canonicalizedQueryString.toString().substring(1)));

            System.out.println(stringToSign+"----");
            System.out.println(canonicalizedQueryString+"----");
            final String ALGORITHM = "HmacSHA1";
            final String ENCODING = "UTF-8";
            String key = "Q9xF9V7tcnCI28ttUsP8H4GyAhZta7&";

            Mac mac = null;
            mac = Mac.getInstance(ALGORITHM);
            mac.init(new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM));
            byte[] signData = mac.doFinal(stringToSign.toString().getBytes(ENCODING));
            String signature = new String(Base64.encodeBase64(signData));
            System.out.println(signature);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 格式化时间
     */
    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 url = "http://ecs.aliyuncs.com/?Signature=nlP6EzL3p7z/UzFSkhcB8lD/iWw=&AccessKeyId=LTAIi7VuxcgfJR2x&Action=DescribeRegions&Format=XML&SignatureMethod=HMAC-SHA1&SignatureNonce=1d320cb5-c794-450b-86ec-68681bb01685&SignatureVersion=1.0&TimeStamp=2017-12-21T02%3A46%3A02Z&Version=2014-05-26";
        try {
            new OssUpload().sendPost();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String data = formatIso8601Date(new Date());
        System.out.println(data);

    }
}
