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

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

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class UploadServiceImpl implements IUploadService {

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

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

    @Override
    public String uploadImage(String fileUrl, String siteId) throws Exception {
//        URL url = new URL(fileUrl);
//        URLConnection connection1 = url.openConnection();
//        InputStream inputStream = connection1.getInputStream();
//        File tempFile = File.createTempFile("temp", ".tmp");
//        OutputStream outputStream1 = new FileOutputStream(tempFile);
//        byte[] buffer = new byte[1024];
//        int length;
//        while ((length = inputStream.read(buffer)) != -1) {
//            outputStream1.write(buffer, 0, length);
//        }
        int HttpResult;
        byte[] bytes = new byte[204800];
        URL url = new URL(fileUrl); // 创建URL
        URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
        urlconn.connect();
        HttpURLConnection httpconn = (HttpURLConnection) urlconn;
        HttpResult = httpconn.getResponseCode();
        if (HttpResult != HttpURLConnection.HTTP_OK) {
            log.error("获取文件失败，无法连接到文件资源");
        } else {
            int filesize = urlconn.getContentLength(); // 取数据长度
            log.info("取数据长度:{}", filesize);
            urlconn.getInputStream();
            InputStream inputStream = urlconn.getInputStream();
            //如果这里只需要返回stream，则直接返回 不需要转byte[]

            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            int ch;
            while ((ch = inputStream.read()) != -1) {
                swapStream.write(ch);
            }
            bytes = swapStream.toByteArray();
        }

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

//        return uploadImage2(fileUrl, okkiUrl);
//        File tempFile = new File(url.getPath());
//        String fileName = tempFile.getName(); // 从$_FILE['file']['name']获取
//        System.out.println(fileName);
//        String fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);; // 从$_FILE['file']['type']获取
//        System.out.println(fileType);
//        byte[] fileContent = HttpClientUtils.readBytesFromFile(tempFile);
        URI uri = new URI(fileUrl);
//        URL url1 = uri.toURL();

        String path = uri.getPath(); // 获取路径部分
        String fileName = path.substring(path.lastIndexOf('/') + 1); // 获取文件名
        String fileType = getFileType(fileName); // 获取文件类型

        System.out.println("Filename: " + fileName);
        System.out.println("Filetype: " + fileType);
        byte[] fileContent = bytes;
        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();
        //{"code":0,"msg":"success","now":"2024-06-25 15:33:14","data":{"url":"https:\/\/okki-shop-dev.oss-cn-hangzhou.aliyuncs.com\/1000147\/upload\/custom\/e132e613b00d8448acf9cf18bc7e4b6affc7bd305c68f9747d529f9580647376.jpg"}}
        JSONObject jsonObject = JSONObject.parseObject(response.toString());
        if ("0".equals(jsonObject.get("code").toString())) {
            final JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("data").toString());
            return jsonObject1.get("url").toString();
        }else {
            throw new Exception(jsonObject.get("msg").toString());
        }
    }

    private static String getFileType(String filename) {
        Pattern pattern = Pattern.compile("\\.(\\w+)$");
        Matcher matcher = pattern.matcher(filename);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return ""; // 如果没有匹配到文件类型，则返回空字符串
    }

    public static String uploadImage2(String imageUrl, String uploadUrl) throws IOException {
        String boundary = Long.toHexString(System.currentTimeMillis());
        String CRLF = "\r\n"; // 换行符
        URL url = new URL(uploadUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (
                OutputStream output = connection.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
        ) {
            // 发送文件数据
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"").append(CRLF);
            writer.append("Content-Type: image/jpeg").append(CRLF);
            writer.append(CRLF).flush();

            // 写入文件内容
            try (InputStream inputStream = new URL(imageUrl).openStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }
                output.flush(); // 确保图片数据发送完毕
            }

            // 结束标志
            writer.append(CRLF).flush();
            writer.append("--" + boundary + "--").append(CRLF);
        }

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        connection.disconnect();
        return connection.getContent().toString();
    }
}
