package com.sysu.admin.controller.crop.xls;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.sysu.admin.controller.crop.range.LandRangeIndex;
import com.sysu.admin.controller.crop.range.LandRangeIndexService;

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

public class PublishCropExcelListener extends AnalysisEventListener<CropExcel> {

    public PublishCropExcelListener(LandRangeIndexService landRangeIndexService){
        this.landRangeIndexService = landRangeIndexService;
    }

    private LandRangeIndexService landRangeIndexService;
    private Map<String,List<Long>> tableIdsMap = new HashMap<>();
    private List<LandRangeIndex> rangeIndexList = new ArrayList<>();

    public  Map<String,List<Long>> getTableIdsMap(){
        return tableIdsMap;
    }

    @Override
    public void invoke(CropExcel publishCropExcel, AnalysisContext analysisContext) {
        if(publishCropExcel.getId() != null) {
            String tableName = getTableName(publishCropExcel.getId());
            addId(tableName, publishCropExcel.getId());
        }
    }

    private void addId(String tableName, Long id){
        List<Long> ids = tableIdsMap.get(tableName);
        if(ids == null){
            ids = new ArrayList<>();
            tableIdsMap.put(tableName, ids);
        }
        ids.add(id);
    }

    private String getTableName(Long id){
        for(LandRangeIndex landRangeIndex : rangeIndexList){
            if(landRangeIndex.getPk().start() <= id && landRangeIndex.getPk().end() >= id){
                return landRangeIndex.getTableName();
            }
        }
        LandRangeIndex landRangeIndex = landRangeIndexService.getByCropId(id);
        rangeIndexList.add(landRangeIndex);
        return landRangeIndex.getTableName();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }
}
