package com.zjrs.appcomm.template.excel.mapper;

import org.apache.poi.ss.usermodel.Cell;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FieldCellStyler implements CellStyler {

	private Map<String, List<CellStyler>> fieldCellStylerMap = new HashMap<>();
	public static final String MUTIL_FIELD = "";
	
	public void addCellStyler(String field, CellStyler cellStyler) {
		List<CellStyler> list = fieldCellStylerMap.computeIfAbsent(field, key -> new ArrayList<>());
		list.add(cellStyler);
	}
	public int removeCellStyler(String field, CellStyler cellStyler) {
		List<CellStyler> list = fieldCellStylerMap.get(field);
		int num = 0;
		if (list != null) {
			for (int i = list.size() - 1; i >= 0; i--) {
				if (list.get(i).equals(cellStyler)) {
					list.remove(i);
					num++;
				}
			}
			if (list.isEmpty()) {
				fieldCellStylerMap.remove(field);
			}
		}
		return num;
	}
	
	@Override
	public boolean style(Cell cell, Object value, String field, int dataIndex, int rowIndex, int cellIndex, Map<?, ?> row) {
		boolean doValue = true;
		
		List<CellStyler> list = fieldCellStylerMap.get(field);
		if (list != null) {
			for (CellStyler cellStyler: list) {
				boolean tempDoValue = cellStyler.style(cell, value, field, dataIndex, rowIndex, cellIndex, row);
				doValue = doValue && tempDoValue;
			}
		}
		
		list = fieldCellStylerMap.get(MUTIL_FIELD);
		if (list != null) {
			for (CellStyler cellStyler: list) {
				boolean tempDoValue = cellStyler.style(cell, value, field, dataIndex, rowIndex, cellIndex, row);
				doValue = doValue && tempDoValue;
			}
		}
		return doValue;
	}

}
