package com.fuyuanshen.equipment.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author: 默苍璃
 * @date: 2025-06-0618:56
 */

public class IgnoreFailedImageConverter implements Converter<URL> {
    private static final Logger logger = LoggerFactory.getLogger(IgnoreFailedImageConverter.class);

    @Override
    public Class<?> supportJavaTypeKey() {
        return URL.class;
    }

    // @Override
    // public CellDataTypeEnum supportExcelTypeKey() {
    //     return CellDataTypeEnum.STRING;
    // }

    @Override
    public WriteCellData<?> convertToExcelData(URL value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (value == null) {
            return null;
        }

        try {
            URLConnection conn = value.openConnection();
            conn.setConnectTimeout(2000);  // 2秒超时
            conn.setReadTimeout(3000);     // 3秒超时

            try (InputStream inputStream = conn.getInputStream()) {
                // byte[] bytes = FileUtils.readInputStream(inputStream, value.toString());
                // 替代 FileUtils.readInputStream 的自定义方法
                byte[] bytes = readInputStream(inputStream);
                return new WriteCellData<>(bytes);
            }
        } catch (Exception e) {
            // 静默忽略错误，只记录日志
            logger.debug("忽略图片加载失败: {}, 原因: {}", value, e.getMessage());
            // return null;  // 返回null表示不写入图片
            return new WriteCellData<>(new byte[0]); // 返回空数组而不是 null
        }
    }

    /**
     * 替代 FileUtils.readInputStream 的自定义方法
     *
     * @param inputStream 输入流
     * @return 字节数组
     * @throws Exception 读取异常
     */
    private byte[] readInputStream(InputStream inputStream) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int bytesRead;

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        return outputStream.toByteArray();
    }
}