package com.tmerclub.cloud.order.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.order.vo.AllotSpuExcelVO;
import org.springframework.util.ObjectUtils;

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

/**
 * @author gaozijie
 * @since 2023-11-29
 */
public class AllotSpuExcelListener extends AnalysisEventListener<AllotSpuExcelVO> {

    private final List<AllotSpuExcelVO> list;
    private final List<String> partyCodes;

    public AllotSpuExcelListener(List<AllotSpuExcelVO> list) {
        this.list = list;
        partyCodes = new ArrayList<>(Constant.INITIAL_CAPACITY);
    }

    @Override
    public void invoke(AllotSpuExcelVO allotSpuExcelVO, AnalysisContext analysisContext) {
        if (ObjectUtils.isEmpty(allotSpuExcelVO.getPartyCode())
                || partyCodes.contains(allotSpuExcelVO.getPartyCode())) {
            return;
        }
        if (Objects.isNull(allotSpuExcelVO.getAllotCount())) {
            allotSpuExcelVO.setAllotCount(0);
        }
        partyCodes.add(allotSpuExcelVO.getPartyCode());
        list.add(allotSpuExcelVO);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    /**
     * 获取excel表头数据
     *
     * @param headMap 表头数据
     * @param context 上下文
     */
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        Map<Integer, String> strHeadMap = ConverterUtils.convertToStringMap(headMap, context);
        int row = context.readRowHolder().getRowIndex();
        // 合并表头检验
        if (Objects.equals(row, 0)) {
            if (!Objects.equals(strHeadMap.get(0), AllotSpuExcelVO.HEADER)) {
                throw new LuckException("导入模板错误，请下载最新模板！");
            }
            return;
        }
        // 表头检验
        if (Objects.equals(row, 1)) {
            if (!Objects.equals(strHeadMap.size(), AllotSpuExcelVO.HEADER_ARRAY.length)) {
                throw new LuckException("导入模板错误，请下载最新模板！");
            }
            for (Map.Entry<Integer, String> entry : strHeadMap.entrySet()) {
                if (!Objects.equals(entry.getValue(), AllotSpuExcelVO.HEADER_ARRAY[entry.getKey()])) {
                    throw new LuckException("导入模板错误，请下载最新模板！");
                }
            }
        }
    }
}
