package cn.report.template.poiet.policy;

import cn.report.template.poiet.NiceXSSFWorkbook;
import cn.report.template.poiet.XSSFTemplate;
import cn.report.template.poiet.template.cell.CellTemplate;
import cn.report.template.poiet.data.TextRenderData;
import cn.report.template.poiet.util.StyleUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TextRenderPolicy extends AbstractRenderPolicy<Object> {

    @Override
    public void doRender(CellTemplate cellTemplate, Object renderData, XSSFTemplate template) {
        XSSFCell cell = cellTemplate.getCell();
        Helper.renderTextCell(cell, renderData, template);
    }

    public static class Helper {

        public static void renderTextCell(XSSFCell cell, Object renderData,XSSFTemplate template) {
            renderTextCell(cell, renderData, template.getXSSFWorkbook());
        }

        public static void renderTextCell(XSSFCell cell, Object renderData, NiceXSSFWorkbook workbook) {
            if (null == renderData) {
                renderData = new TextRenderData();
            }
            // text
            TextRenderData textRenderData = renderData instanceof TextRenderData
                    ? (TextRenderData) renderData
                    : new TextRenderData(renderData.toString());

            String data = null == textRenderData.getText() ? "" : textRenderData.getText();

            StyleUtils.styleCell(workbook, cell, textRenderData.getStyle());

            if (StringUtils.isEmpty(data)) {
                cell.setCellValue(data);
            } else {
                switch (textRenderData.getDataType()) {
                    case String:
                        cell.setCellValue(data);
                        break;
                    case Double:
                        cell.setCellValue(Double.valueOf(data));
                        break;
                    default:
                        cell.setCellValue(data);
                }
            }
        }

    }

}
