package com.ylcm.sys.excel.converter;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

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

public class LocalTimeConverter implements Converter<LocalTime> {

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

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

    @Override
    public LocalTime convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
    	BigDecimal cellDataValue = cellData.getNumberValue();
    	if (cellDataValue == null) {
			return null;
		}
    	return LocalTime.parse(getPOIDate(true, cellDataValue.doubleValue()).substring(11, 19), DateTimeFormatter.ISO_LOCAL_TIME);
    }
    

    
	private String getPOIDate(boolean use1904windowing, double value) {
    	int wholeDays = (int) Math.floor(value);
    	int millisecondsInDay = (int) ((value - (double) wholeDays) * 8.64E7D + 0.5D);
    	Calendar calendar = new GregorianCalendar();
    	short startYear = 1900;
    	byte dayAdjust = -1;
    	if (use1904windowing) {
	    	startYear = 1904;
	    	dayAdjust = 1;
    	} else if (wholeDays < 61) {
    		dayAdjust = 0;
    	}
    	calendar.set(startYear, 0, wholeDays + dayAdjust, 0, 0, 0);
    	calendar.set(Calendar.MILLISECOND, millisecondsInDay);
    	if (calendar.get(Calendar.MILLISECOND) == 0) {
    		calendar.clear(Calendar.MILLISECOND);
    	}
    	Date date = calendar.getTime();
    	SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	return s.format(date);
    }

    @Override
    public CellData convertToExcelData(LocalTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
            return new CellData(value.format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        } else {
            return new CellData(value.format(DateTimeFormatter.ofPattern(contentProperty.getDateTimeFormatProperty().getFormat())));
        }

    }


}
