package com.blueland.util;

import java.util.ArrayList;
import java.util.List;

import com.blueland.bo.AreaExpEntity;
import com.blueland.service.IAreaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.fastjson.JSON;




/**
 * @author sam
 * @create 2020-01-07-15:15
 * @Desc
 */
public class AreaExcelListener extends AnalysisEventListener<AreaExpEntity> {

    private static final Logger Logger = LoggerFactory.getLogger(AreaExcelListener.class);

    private List<AreaExpEntity> data = new ArrayList<>();

    IAreaService areaService;

    public AreaExcelListener(IAreaService areaService) {
        this.areaService = areaService;
    }

    /**
     * 每一条解析过来的数据都会调用
     * @param entity
     * @param analysisContext
     */
    @Override
    public void invoke(AreaExpEntity entity, AnalysisContext analysisContext) {
        Logger.info("解析到一条数据：{}", JSON.toJSONString(entity));
        entity.setTid(entity.getTid().trim());
        entity.setAname(entity.getAname().trim());
        this.data.add(entity);
    }

    /**
     * 所有数据解析完成了 都会来调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        Logger.info("解析完成！数据量{}条", this.data.size());
        Logger.info("导入行政数据 Start ");
        areaService.importAreaData(this.data);
        Logger.info("导入行政数据 End ");
        // 操作完业务清理data
        this.data.clear();
    }

    /**
     * 异常处理
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) {
        Logger.error("解析失败，继续解析下一行，错误信息：{}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
            Logger.error("第{}行，第{}列解析失败", excelDataConvertException.getRowIndex(), excelDataConvertException.getColumnIndex());
        }
    }
}
