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.AllotSpuInboundExcelVO;
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-12-01
 */
public class AllotSpuInboundExcelListener extends AnalysisEventListener<AllotSpuInboundExcelVO> {

    List<AllotSpuInboundExcelVO> list;
    List<String> partyCodes;

    public AllotSpuInboundExcelListener(List<AllotSpuInboundExcelVO> data) {
        this.list = data;
        this.partyCodes = new ArrayList<>(Constant.INITIAL_CAPACITY);
    }

    @Override
    public void invoke(AllotSpuInboundExcelVO allotSpuInboundExcelVO, AnalysisContext analysisContext) {
        if (ObjectUtils.isEmpty(allotSpuInboundExcelVO.getPartyCode())
                || partyCodes.contains(allotSpuInboundExcelVO.getPartyCode())) {
            return;
        }
        if (Objects.isNull(allotSpuInboundExcelVO.getInboundCount())) {
            allotSpuInboundExcelVO.setInboundCount(0);
        }
        partyCodes.add(allotSpuInboundExcelVO.getPartyCode());
        list.add(allotSpuInboundExcelVO);
    }

    @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), AllotSpuInboundExcelVO.HEADER)) {
                throw new LuckException("导入模板错误，请下载最新模板！");
            }
            return;
        }
        // 表头检验
        if (Objects.equals(row, 1)) {
            if (!Objects.equals(strHeadMap.size(), AllotSpuInboundExcelVO.HEADER_ARRAY.length)) {
                throw new LuckException("导入模板错误，请下载最新模板！");
            }
            for (Map.Entry<Integer, String> entry : strHeadMap.entrySet()) {
                if (!Objects.equals(entry.getValue(), AllotSpuInboundExcelVO.HEADER_ARRAY[entry.getKey()])) {
                    throw new LuckException("导入模板错误，请下载最新模板！");
                }
            }
        }
    }
}
