package io.renren.modules.dataSet.upload;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 直接用map接收数据
 *
 * @author Jiaju Zhuang
 */
@Data
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(NoModelDataListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    List<Map<Integer, String>> list = new ArrayList<Map<Integer, String>>();

    private  Integer needDataIndex;
    //用headList集合保存解析到的表头
    private List< String> headList = new LinkedList<String>();

    // allDataList 保存前BATCH_COUNT 条数据  用于前台单击预览
    private List<Map<String,String>> allDataList = new LinkedList<>();


    public NoModelDataListener() {
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
//        LOGGER.info("解析到一条头数据：{}, currentRowHolder: {}", headMap.toString(), context.readRowHolder().getRowIndex());
//        System.out.println(context.readSheetHolder().getSheetNo());
//        System.out.println(context.readSheetHolder().getSheetName());
//        {0=日期标题, 1=字符串标题, 2=数字标题}
        for (String value : headMap.values()) {
            headList.add(value);
        }


    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
//        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        Map<String,String> newData = new LinkedHashMap<String, String>();

        for (Integer i =0;i< (data.values().toArray().length);i++) {
            newData.put(headList.get(i),data.get(i)); // 重构key标题
        }
        allDataList.add(newData);
//        System.out.println(data.get(1));
//        if (list.size() >= BATCH_COUNT) {
//            saveData();
////            list.clear();
//        }

    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
//        LOGGER.info("{}条数据，开始存储数据库！", list.size());
//        for (Map<Integer, String> integerStringMap : list) {
//
//            needList.add(integerStringMap.get(this.needDataIndex));
//        }
//        LOGGER.info("存储数据库成功！");
    }
}
