package org.jeecg.modules.app.esign.comm;


import org.jeecg.modules.app.esign.exception.EsignDemoException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

/**
 * @description  文件基础信息封装类
 * @author  澄泓
 * @date  2020/10/26 14:54
 * @version JDK1.7
 */
public class EsignFileBean {
    //文件名称
    private String fileName;
    //文件大小
    private int fileSize;
    //文件内容MD5
    private String fileContentMD5;
    //文件地址
    private String filePath;


    public EsignFileBean(String filePath) throws Exception {
        this.filePath = filePath;

        if (filePath.startsWith("http")) {
            // 下载网络文件到本地临时目录
            File tempFile = downloadFromURL(filePath);
            this.filePath = tempFile.getAbsolutePath();
            this.isTemporaryFile = true;
        }

        File file = new File(this.filePath);
        if (!file.exists()) {
            throw new EsignDemoException("文件不存在");
        }

        this.fileName = file.getName();
        this.fileSize = (int) file.length();
        this.fileContentMD5 = FileTransformation.getFileContentMD5(this.filePath);
    }

    private boolean isTemporaryFile = false;

    private File downloadFromURL(String fileUrl) throws Exception  {
        // 使用 URI 构造器自动编码路径
        URI uri = new URI(fileUrl);
        URL url = uri.toURL();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // 模拟浏览器请求
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new EsignDemoException("网络文件下载失败，状态码：" + connection.getResponseCode());
        }

        String fileName = extractFileNameFromURL(url, connection);
        File targetFile = new File(getDownloadDirectory(), fileName);

        // 确保文件名唯一
        int count = 1;
        String baseName = fileName.substring(0, fileName.lastIndexOf('.'));
        String ext = fileName.substring(fileName.lastIndexOf('.'));
        while (targetFile.exists()) {
            targetFile = new File(getDownloadDirectory(), baseName + "_" + (count++) + ext);
        }

        try (InputStream in = connection.getInputStream();
             FileOutputStream out = new FileOutputStream(targetFile)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }

        return targetFile;
    }
    private String downloadDirectory = System.getProperty("user.dir") + File.separator + "esign_downloads";

    private File getDownloadDirectory() {
        File dir = new File(downloadDirectory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }
    private String extractFileNameFromURL(URL url, HttpURLConnection connection) {
        String disposition = connection.getHeaderField("Content-Disposition");
        if (disposition != null && disposition.contains("filename=")) {
            return disposition.split("filename=")[1].trim().replaceAll("\"", "");
        } else {
            String path = url.getPath();
            return path.substring(path.lastIndexOf('/') + 1);
        }
    }
    protected void finalize() throws Throwable {
        try {
            if (isTemporaryFile && new File(filePath).exists()) {
                new File(filePath).delete();
            }
        } finally {
            super.finalize();
        }
    }

    public String getFileName() {
        return fileName;
    }

    public int getFileSize() {
        return fileSize;
    }

    public String getFileContentMD5() {
        return fileContentMD5;
    }

    /**
     * 传入本地文件地址获取二进制数据
     * @return
     * @throws EsignDemoException
     */
    public byte[] getFileBytes() throws EsignDemoException {
        return FileTransformation.fileToBytes(filePath);
    }
}
