package com.yifu.cloud.plus.v1.yifu.social.util;


import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
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.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

/**
 * @author hgw
 * @description easyExcel金额转换类
 * @date 2022-11-15 11:29:08
 */
public class BigDecimalConverter implements Converter<BigDecimal> {

	@Override
	public Class<BigDecimal> supportJavaTypeKey() {
		return BigDecimal.class;
	}

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

	/**
	 * 这里读的时候会调用
	 * @return
	 */
	@Override
	public BigDecimal convertToJavaData(ReadConverterContext<?> context) {
		BigDecimal value = context.getReadCellData().getNumberValue();
		if (null == value) {
			if (null != context.getReadCellData().getStringValue()) {
				value = new BigDecimal(context.getReadCellData().getStringValue());
			} else {
				return null;
			}
		}
		return value.setScale(2, BigDecimal.ROUND_HALF_UP);
	}

	@Override
	public BigDecimal convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty
			, GlobalConfiguration globalConfiguration) {
		return new BigDecimal(cellData.getStringValue()).round(new MathContext(10, RoundingMode.HALF_UP));
	}

	@Override
	public WriteCellData<String> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty
			,GlobalConfiguration globalConfiguration) {
		return new WriteCellData<>(String.valueOf(value));
	}

}

