package org.dromara.zhishu.util;

import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.encrypt.utils.EncryptUtils;
import org.dromara.common.oss.core.OssClient;
import org.dromara.common.oss.entity.UploadResult;
import org.dromara.common.oss.factory.OssFactory;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zhishu.domain.LocalMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.*;
import java.util.UUID;


@Component
public final class UploadUtil {

    /**
     * 上传文件
     * @param file      文件内容
     * @param name      MD5加密前的名称
     * @param isbn      ISBN
     * @param num       顺序号
     * @return
     */
    public static String upload(MultipartFile file,
                                String name,
                                String isbn,
                                String num,
                                String warehouseId,
                                String shelfId,
                                String locationId) {
        // 获取文件后缀
        String originalfileName = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());

        String path = "userShopGoodsImages/"+warehouseId+"/"+shelfId+"/"+locationId+"/"+isbn+num+suffix;
//        System.out.println("上传图片地址：" + path);
        try {
            AliOssUtils.setIamge(path,file.getBytes());
        } catch (Exception e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return "上传失败";
        }
        return path;
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    public static String upload(MultipartFile file,String folderName) {

        // 获取文件后缀
        String originalfileName = file.getOriginalFilename();
        String path = "other/"+ LoginHelper.getUserId()+"/"+folderName+"/"+originalfileName;
//        System.out.println("上传图片地址：" + path);
        try {
            AliOssUtils.setIamge(path,file.getBytes());

            return path;
        } catch (Exception e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return "上传失败";
        }
    }

    /**
     * 获取文件路径
     * @param name       名称
     * @param fileName  文件名
     * @return
     */
    public static String getFiles(String name, String fileName,String folderName,String objectName){

        String path = "";
        if(folderName.equals("bookInfoImages")){
            String result = getMd5FirstChart(name);
            path = folderName+"/"+result+"/"+fileName;
        }else{
            path = objectName;
        }
        return AliOssUtils.getImagePath(path);
    }

    /**
     * 获取文件路径
     * @param bookName  书名
     * @param fileName  文件名
     * @return
     */
    public static String getFiles(String imgVesselUrl,String bookName, String fileName){

        if(StringUtils.isEmpty(imgVesselUrl)){
            imgVesselUrl = "https://img.buzhiyushu.cn/zhishu1";

            String result = getMd5FirstChart(bookName);

            return imgVesselUrl + StringUtils.SLASH + result+StringUtils.SLASH+fileName;

        }else{
            return imgVesselUrl+fileName;
        }
    }


    /**
     * 根据MD5加密后获取大写首字母
     * @param bookName
     * @return
     */
    public static String getMd5FirstChart(String bookName){
        //书名进行md5加密
        String bookNameMd5 = EncryptUtils.encryptByMd5(bookName);
        //获取加密后打首字母大写
        return StringUtils.getFirstCharToUpper(bookNameMd5);
    }

    /**
     * 校验图片文件宽高
     * @param file
     * @return
     * @throws IOException
     */
    public static Boolean getImageDimensions(MultipartFile file)  {
        // 将 MultipartFile 转换为 BufferedImage
        BufferedImage image = null;
        try {
            image = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            return true;
        }

        if (image == null) {
            return true;
        }
        // 获取图片的长宽
        if(image.getWidth() == 800 && image.getHeight() == 800){
            return false;
        }else{
            return true;
        }
    }

    public static MultipartFile getMultipartFileFromPath(String filePath){
        // 创建 File 对象
        File file = new File(filePath);

        MultipartFile multipartFile = new LocalMultipartFile(file);

        return multipartFile;
    }

    public static MultipartFile getMultipartFileFromPathUrl(String filePath)  {
        try {
            URL url = new URL(filePath);
            // 提取文件后缀
            String fileSuffix = "";
            String path = url.getPath();
            int lastDotIndex = path.lastIndexOf(".");
            if (lastDotIndex > 0 && lastDotIndex < path.length()) {
                fileSuffix = path.substring(lastDotIndex); // 如 ".jpg"
            }

            // 创建带后缀的临时文件
            Path tempFile = Files.createTempFile("upload-"+ UUID.randomUUID(), fileSuffix);

            // 下载远程文件到本地临时文件
            try (InputStream in = url.openStream()) {
                Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING);
            }

            // 构建 MultipartFile
            return new LocalMultipartFile(tempFile.toFile());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


    /**
     * 将主图和水印图片合成一张，水印图片完美覆盖主图
     *
     * @param mainImageUrl    主图的 URL
     * @param watermarkImageUrl 水印图片的 URL
     */
    public static String mergeImages(String mainImageUrl, String watermarkImageUrl) throws IOException {
        // 从 URL 读取主图
        BufferedImage mainImage = ImageIO.read(new URL(mainImageUrl));
        // 从 URL 读取水印图片
        BufferedImage watermarkImage = ImageIO.read(new URL(watermarkImageUrl));

        // 获取主图的宽高
        int mainWidth = mainImage.getWidth();
        int mainHeight = mainImage.getHeight();

        // 将水印图片缩放到主图的尺寸
        Image scaledWatermark = watermarkImage.getScaledInstance(mainWidth, mainHeight, Image.SCALE_SMOOTH);

        // 创建一个新的 BufferedImage，类型为 ARGB（支持透明度）
        BufferedImage combined = new BufferedImage(
                mainWidth, mainHeight, BufferedImage.TYPE_INT_ARGB);

        // 获取 Graphics2D 对象
        Graphics2D g2d = combined.createGraphics();

        // 绘制主图
        g2d.drawImage(mainImage, 0, 0, null);
        // 绘制缩放后的水印图片
        g2d.drawImage(scaledWatermark, 0, 0, null);

        // 释放资源
        g2d.dispose();


        // 创建临时文件
        Path tempFile = Files.createTempFile("combined-image-", ".png");

        // 保存合成后的图片到临时文件
        ImageIO.write(combined, "PNG", tempFile.toFile());

        // 返回临时文件的路径
        return tempFile.toAbsolutePath().toString();
    }

    /**
     * 校验文件是否存在
     * @param imageUrl
     * @return
     */
    public static Boolean isImageExists(String imageUrl,String fileName) {
        File file = new File(imageUrl+fileName);
        if (file.exists()) {
            System.out.println("文件存在: " + imageUrl+fileName);
            return true;
        } else {
            System.out.println("文件不存在: " + imageUrl+fileName);
            try {
                // 将字符串路径转换为Path对象
                Path path = Paths.get(imageUrl);
                // 检查目录是否存在
                if (!Files.exists(path)) {
                    // 如果不存在，则创建目录
                    Files.createDirectories(path);
                    System.out.println("目录已创建: " + imageUrl);
                } else {
                    System.out.println("目录已存在: " + imageUrl);
                }
            }catch (Exception e) {
                System.err.println("无法创建目录: " + e.getMessage());
            }
            return false;
        }
    }

    /**
     * 校验文件是否存在
     * @param fileUrl
     * @return
     */
    public static boolean isFileExists(String fileUrl) {
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");  // 改用 GET 更可靠
            connection.setInstanceFollowRedirects(true);  // 自动处理重定向

            int responseCode = connection.getResponseCode();
            return (responseCode == HttpURLConnection.HTTP_OK);
        } catch (IOException e) {
            return false;  // 简化异常处理，直接返回 false
        }
    }

    /**
     * 校验图片是否存在
     */
    public static boolean isImageExists(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            int responseCode = connection.getResponseCode();
            return responseCode == HttpURLConnection.HTTP_OK;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据网络路径获取图片并下载到本地系统缓存目录
     *
     * @param imageUrl 图片的网络路径（URL）
     * @return 下载后的本地文件路径
     * @throws IOException 如果下载过程中发生错误
     */
    public static String downloadImageToCache(String imageUrl) throws IOException {
        // 创建 URL 对象
        URL url = new URL(imageUrl);

        // 获取系统缓存目录（例如：Windows 是 C:\Users\用户名\AppData\Local\Temp\）
        Path cacheDir = Files.createTempDirectory("image-cache-");

        // 提取图片文件名（从 URL 中提取）
        String fileName = extractFileNameFromUrl(url);

        // 定义目标文件路径
        Path targetFile = cacheDir.resolve(fileName);

        // 从网络下载图片并保存到本地缓存目录
        try (InputStream in = url.openStream()) {
            Files.copy(in, targetFile, StandardCopyOption.REPLACE_EXISTING);
        }

        // 返回下载后的文件路径
        return targetFile.toAbsolutePath().toString();
    }

    /**
     * 从 URL 中提取文件名
     *
     * @param url 图片的 URL
     * @return 文件名
     */
    private static String extractFileNameFromUrl(URL url) {
        String path = url.getPath();
        int lastSlashIndex = path.lastIndexOf('/');
        if (lastSlashIndex != -1) {
            return path.substring(lastSlashIndex + 1);
        }
        return "downloaded_file";
    }
}
