package com.yeejoin.amos.boot.module.common.api.excel;

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

import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;

public class TemplateDynamicCellWriteHandlerDate implements SheetWriteHandler{
	 /**
     * 构造器注入
     */
   
    private List<Map<Integer, String[]>> explicitListConstraintMap = new ArrayList<Map<Integer, String[]>>();
    public TemplateDynamicCellWriteHandlerDate(List<Map<Integer, String[]>> explicitListConstraintMap) {
        this.explicitListConstraintMap = explicitListConstraintMap;
    }
    /**
     * 避免生成的导入模板下拉值获取不到
     */
    private static final Integer LIMIT_NUMBER = 0;
   

		
	/**
     * 返回excel列标A-Z-AA-ZZ
     *
     * @param num 列数
     * @return java.lang.String
     */
    private String getExcelLine(int num) {
        String line = "";
        int first = num / 26;
        int second = num % 26;
        if (first > 0) {
            line = (char) ('A' + first - 1) + "";
        }
        line += (char) ('A' + second) + "";
        return line;
    }

	@Override
	public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
		if(explicitListConstraintMap!=null) {
			 // 这里可以对cell进行任何操作
	        Sheet sheet = writeSheetHolder.getSheet();
	        DataValidationHelper helper = sheet.getDataValidationHelper();
	        for(int index =0 ; index < explicitListConstraintMap.size() ;index++ ) {
	        	int startIndex = index+1;
	        	explicitListConstraintMap.get(index).forEach((k, v)->{
	        		 // 设置下拉单元格的首行 末行 首列 末列
		            CellRangeAddressList rangeList = new CellRangeAddressList(startIndex, startIndex, k, k);
		            // 如果下拉值总数大于100，则使用一个新sheet存储，避免生成的导入模板下拉值获取不到
		            if (v.length > LIMIT_NUMBER) {
		                //定义sheet的名称
		                //1.创建一个隐藏的sheet 名称为 hidden + k+随机数防止数据过多造成的名字重复
						Random random = new Random();
						String sheetName = "hidden" +startIndex + k+random.nextInt(1000);
		                Workbook workbook = writeWorkbookHolder.getWorkbook();
		                Sheet hiddenSheet = workbook.createSheet(sheetName);
		                for (int i = 0, length = v.length; i < length; i++) {
		                    // 开始的行数i，列数k
		                    hiddenSheet.createRow(i).createCell(k).setCellValue(v[i]);
		                }
		                Name category1Name = workbook.createName();
		                category1Name.setNameName(sheetName);
		                String excelLine = getExcelLine(k);
		                // =hidden!$H:$1:$H$50  sheet为hidden的 H1列开始H50行数据获取下拉数组
		                String refers = "=" + sheetName + "!$" + excelLine + "$1:$" + excelLine + "$" + (v.length + 1);
		                // 将刚才设置的sheet引用到你的下拉列表中
		                DataValidationConstraint constraint = helper.createFormulaListConstraint(refers);
		                DataValidation dataValidation = helper.createValidation(constraint, rangeList);
		                if(dataValidation instanceof XSSFDataValidation){
		                	dataValidation.setSuppressDropDownArrow(true);
							dataValidation.setShowErrorBox(true);
						}else{
							dataValidation.setSuppressDropDownArrow(false);
						}
		                writeSheetHolder.getSheet().addValidationData(dataValidation);
		                // 设置存储下拉列值得sheet为隐藏
		                int hiddenIndex = workbook.getSheetIndex(sheetName);
		                if (!workbook.isSheetHidden(hiddenIndex)) {
		                    workbook.setSheetHidden(hiddenIndex, true);
		                }
		            }
	        	});
	        }
		}
	}

}
