package cn.iocoder.yudao.framework.excel.core.util;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class LocalTimeConverter implements Converter<LocalTime> {

    @Override
    public Class supportJavaTypeKey() {
        return LocalTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        // 明确指定支持 Excel 中的字符串类型
        return CellDataTypeEnum.STRING;
    }

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

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); // 默认格式
        String format = null;
        if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
            format = contentProperty.getDateTimeFormatProperty().getFormat();
            if (format != null && !format.isEmpty()) {
                formatter = DateTimeFormatter.ofPattern(format);
            }
        }

        String formattedTime = value.format(formatter);
        return new WriteCellData<>(formattedTime);
    }

    // convertToJavaData 方法在这个场景中可能不需要，因为我们只关心写入操作
    // 如果需要处理从 Excel 读取到 Java 的情况，则需要实现该方法
}