package org.jeecg.modules.okki.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.okki.utils.HttpClientUtils;
import org.jeecg.modules.okki.common.service.IUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UploadServiceImpl implements IUploadService {

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

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

    @Override
    public String upload(MultipartFile mf) 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 encoder = URLEncoder(url, "UTF-8");
////第二步
//        String decoder = URLDecoder(encoder, "UTF-8");
//
//        URL url = new URL (decoder);

//        String tmpName = mf.getName(); // 从$_FILE['file']['tmp_name']读取文件路径
//        File file = new File(tmpName);
        String fileName = mf.getOriginalFilename(); // 从$_FILE['file']['name']获取
        String fileType = mf.getContentType(); // 从$_FILE['file']['type']获取
        byte[] fileContent = mf.getBytes();
        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();
        JSONObject jsonObject = JSONObject.parseObject(response.toString());
        if ("0".equals(jsonObject.get("code").toString())) {
            return JSONObject.parseObject(jsonObject.get("data").toString()).get("url").toString();
        }else {
            throw new RuntimeException(jsonObject.get("msg").toString());
        }

//        System.out.println(response.toString());
//        return response.toString();
//        String res = HttpClientUtils.doPost(okkiUrl, body);
    }


}
