package com.qmth.teachcloud.common.util.excel.convertor.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;

import com.qmth.teachcloud.common.util.excel.convertor.ValueConvertor;
import com.qmth.teachcloud.common.util.excel.model.FieldParam;

public class DateConvertor implements ValueConvertor<Date> {

    public static final DateConvertor instance = new DateConvertor();
    String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
    @Override
    public Date parse(String value, FieldParam param) throws Exception {
        String pattern = param.getAnnotation().pattern();
        if (StringUtils.isBlank(pattern)) {
            pattern = DEFAULT_DATE_PATTERN;
        }
        return new SimpleDateFormat(pattern).parse(value);
    }

    @Override
    public void format(Date object, FieldParam param, Cell cell) throws Exception {
        String pattern = param.getAnnotation().pattern();
        if (StringUtils.isBlank(pattern)) {
            pattern = DEFAULT_DATE_PATTERN;
        }
        cell.setCellValue(new SimpleDateFormat(pattern).format(object));
    }
}
