package com.ruoyi.common.utils.converter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;

import java.math.BigDecimal;

/**
 * @Package_Name
 * @Author Leslie Lee
 * @TIME
 * @Version
 */
public class BigDecimalConvert implements Converter<BigDecimal> {
    @Override
    public Class<?> supportJavaTypeKey() {
        return Converter.super.supportJavaTypeKey();
    }

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

    @Override
    public BigDecimal convertToJavaData(ReadConverterContext<?> context) throws Exception {
        return Converter.super.convertToJavaData(context);
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<BigDecimal> context) throws Exception {
        String val = context.getValue().toString();
        if (!StrUtil.isEmpty(val)) {
            if (!val.contains(".")) {//没有小数点 加 . 并补零
                val = val + ".00";
            } else if (val.indexOf(".") == val.length() - 2) {//一位小数 补零
                val = val + "0";
            }
            int decimalIndex = val.indexOf('.');// 假设val为 19569.12
            String integerPart = val.substring(0, decimalIndex);// 19569
            String decimalPart = val.substring(decimalIndex);// .12
            StringBuilder formattedNum = new StringBuilder();
            int count = 0;
            for (int i = integerPart.length() - 1; i >= 0; i--) {// 循环前部分加入千分位
                formattedNum.insert(0, integerPart.charAt(i));
                count++;
//                if (count % 3 == 0 && i != 0) {// 三个字符一加
//                    formattedNum.insert(0, ",");
//                }
            }
            formattedNum.append(decimalPart);
            return new WriteCellData<>(formattedNum.toString());

        }
        return new WriteCellData<>(val);
    }
}
