package org.jeecg.modules.okki.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class UploadUtils {

    @Value("${OKKI.BASE_URL}")
    private static String BASE_URL;

    @Value("${OKKI.CLIENT_SECRET}")
    private static String CLIENT_SECRET;

    public static String upload(MultipartFile file) throws Exception {
        Map<String, String> query = new HashMap<>();
        query.put("sign_method", "hmac-md5"); // 签名方式
        query.put("timestamp", String.valueOf(System.currentTimeMillis())); // 时间戳
        query.put("site_id", "1000147"); // 小满站点id
        query.put("method", "upload_file"); // 上传文件
        String queryStr = HttpClientUtils.buildQueryString(query);
        query.put("signature", HttpClientUtils.generateHmacMD5(queryStr, CLIENT_SECRET)); // 签名
        String okkiUrl = BASE_URL + "?" + HttpClientUtils.buildQueryString(query);

//        String tmpName = "/tmp/test.jpg"; // 从$_FILE['file']['tmp_name']读取文件路径
//        File file = new File(tmpName);
        String fileName = file.getName(); // 从$_FILE['file']['name']获取
        String fileType = "gif"; // 从$_FILE['file']['type']获取
        byte[] fileContent = HttpClientUtils.readBytesFromFile((File) file);
        String delimiter = "-------------" + System.currentTimeMillis();
        String boundary = delimiter;
        String crlf = "\r\n";
        String twoHyphens = "--";
        System.out.println(okkiUrl);
        HttpURLConnection connection = (HttpURLConnection) new URL(okkiUrl).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        OutputStream outputStream = connection.getOutputStream();
        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
        dataOutputStream.writeBytes(twoHyphens + boundary + crlf);
        dataOutputStream
                .writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" + crlf);
        dataOutputStream.writeBytes("Content-Type: " + fileType + crlf);
        dataOutputStream.writeBytes(crlf);
        dataOutputStream.write(fileContent);
        dataOutputStream.writeBytes(crlf);
        dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens);
        dataOutputStream.flush();
        dataOutputStream.close();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }
        bufferedReader.close();
        System.out.println(response.toString());
        return response.toString();
    }

//    private static byte[] readBytesFromFile(File file) throws Exception {
//        FileInputStream fileInputStream = new FileInputStream(file);
//        byte[] fileBytes = new byte[(int) file.length()];
//        fileInputStream.read(fileBytes);
//        fileInputStream.close();
//        return fileBytes;
//    }

//    private static String buildQueryString(Map<String, String> params) {
//        StringBuilder query = new StringBuilder();
//        for (Map.Entry<String, String> entry : params.entrySet()) {
//            if (query.length() > 0) {
//                query.append("&");
//            }
//            query.append(entry.getKey()).append("=").append(entry.getValue());
//        }
//        return query.toString();
//    }
//
//    private static String generateHmacMD5(String data, String secret) throws Exception {
//        return HttpClientUtils.generateHmacMD5(data, secret);
//    }
//
//    private static String toJsonString(Object object) throws Exception {
//        com.google.gson.Gson gson = new com.google.gson.Gson();
//        return gson.toJson(object);
//    }
}
