package com.ho.common.tools.util;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.util.PropertyPlaceholderHelper;

import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 动态替换表头
 */
public class TitleCellWriteHandler implements CellWriteHandler {

    private final Map<String, String> titleMap;
    private final PropertyPlaceholderHelper propertyplaceholderHelper = new PropertyPlaceholderHelper("${","}");

    public TitleCellWriteHandler(Map<String, String> titleMap){
        this.titleMap = titleMap;
    }

    @Override
    public void beforeCellCreate(WriteSheetHolder writesheetHolder, WriteTableHolder writeTableHolder,Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean){
        if(head != null){
            List<String> titleNameList =head.getHeadNameList();
            if(CollectionUtils.isNotEmpty(titleNameList)){titleMap.forEach((k,v)-> {
                Properties properties = new Properties();
                properties.setProperty(k, v);
                titleNameList.replaceAll(value -> propertyplaceholderHelper.replacePlaceholders(value, properties));
            });
            }
        }
    }
}
