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

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

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

/**
 * String 到 LocalTime 的 Excel 转换器
 */
public class StringToLocalTimeConverter implements Converter<LocalTime> {

    // 定义时间格式的字符串，可以根据实际情况调整
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

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

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

    @Override
    public LocalTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                       GlobalConfiguration globalConfiguration) throws Exception {
        // 读取单元格数据
        String stringValue = cellData.getStringValue();
        // 尝试解析为 LocalTime
        try {
            return LocalTime.parse(stringValue, formatter);
        } catch (DateTimeParseException e) {
            throw new UnsupportedOperationException("转换失败，无法将字符串 " + stringValue + " 转换为 LocalTime");
        }
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalTime value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) throws Exception {
        // 将 LocalTime 转换回字符串（如果需要写回 Excel）
        if (value == null) {
            return new WriteCellData<>("");
        }
        return new WriteCellData<>(value.format(formatter));
    }
}