package com.wmyun.farmwork.word.core.model.ext;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.wmyun.farmwork.word.core.enums.PictureProvideDataType;
import com.wmyun.farmwork.word.core.enums.PictureProvideNameType;
import com.wmyun.farmwork.word.core.model.AbstractExData;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.poi.xwpf.usermodel.Document;

import java.net.URL;
import java.util.Base64;

/**
 * @Description: 图片扩展数据
 * @Date: 2025/3/3 10:58
 * @Created: by ZZSLL
 */

@Data
@AllArgsConstructor
public class PictureExData extends AbstractExData {
    private Integer width;

    private Integer height;

    private String pictureName;

    private PictureProvideDataType dataType;

    private PictureProvideNameType nameType;

    private String data;

    @SneakyThrows
    public byte[] readAsByteArray() {
        if (PictureProvideDataType.BASE64.equals(dataType)) {
            return Base64.getDecoder().decode(data);
        }
        if (PictureProvideDataType.DOWNLOAD_URL.equals(dataType)) {
            return HttpUtil.downloadBytes(data);
        }
        if (PictureProvideDataType.ABSOLUTE_PATH.equals(dataType)) {
            return FileUtil.readBytes(data);
        }
        return null;
    }

    public int readPictureType() {
        // 获取文件名，假设 pictureName 已经赋值
        String name = this.pictureName;
        if (name == null || !name.contains(".")) {
            throw new IllegalArgumentException("无效的图片名称：" + name);
        }
        // 获取扩展名，转换为小写
        String ext = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
        // 根据扩展名返回对应的类型ID
        return switch (ext) {
            case "emf" -> Document.PICTURE_TYPE_EMF;
            case "wmf" -> Document.PICTURE_TYPE_WMF;
            case "pict" -> Document.PICTURE_TYPE_PICT;
            case "jpeg", "jpg" -> Document.PICTURE_TYPE_JPEG;
            case "png" -> Document.PICTURE_TYPE_PNG;
            case "dib" -> Document.PICTURE_TYPE_DIB;
            case "gif" -> Document.PICTURE_TYPE_GIF;
            case "tiff", "tif" -> Document.PICTURE_TYPE_TIFF;
            case "eps" -> Document.PICTURE_TYPE_EPS;
            case "bmp" -> Document.PICTURE_TYPE_BMP;
            case "wpg" -> Document.PICTURE_TYPE_WPG;
            default -> throw new IllegalArgumentException("不支持的图片类型: " + ext);
        };
    }
}
