package com.jwipc.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.util.IoUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shenyang.ou
 * @date 2024/3/1 15:54
 * @desc 读取动态excel数据
 */
public class EasyExcelImportUtils {
    /**
     * 动态获取全部列和数据体
     * [stream, parseRowNumber]
     * @return 列表
     */
    public static List<Map<String,String>> parseExcelToData(InputStream inputStream, Integer parseRowNumber) {
        EasyExcelListener readListener = new EasyExcelListener();
        EasyExcelFactory.read(inputStream).registerReadListener(readListener).headRowNumber(parseRowNumber).sheet(0).doRead();
        List<Map<Integer, String>> headList = readListener.getHeadList();
        if(CollectionUtils.isEmpty(headList)){
            throw new RuntimeException("Excel表头不能为空");
        }
        List<Map<Integer, String>> dataList = readListener.getDataList();
        if(CollectionUtils.isEmpty(dataList)){
            throw new RuntimeException("Excel数据内容不能为空");
        }
        //获取头部,取最后一次解析的列头数据
        Map<Integer, String> excelHeadIdxNameMap = headList.get(headList.size() -1);
        //封装数据体
        List<Map<String,String>> excelDataList = Lists.newArrayList();
        for (Map<Integer, String> dataRow : dataList) {
            Map<String,String> rowData = new LinkedHashMap<>();
            excelHeadIdxNameMap.entrySet().forEach(columnHead -> {
                rowData.put(columnHead.getValue(), dataRow.get(columnHead.getKey()));
            });
            excelDataList.add(rowData);
        }
        return excelDataList;
    }

    /**
     * 文件导入测试
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        //属性项
//        FileInputStream inputStream = new FileInputStream(new File("C:\\Users\\hp\\Downloads\\报价列表-2024-03-01 (40).xlsx"));
//        List<Map<String,String>> dataList = parseExcelToData(inputStream, 2);//动态获取全部列和数据体，默认从第一行开始解析数据
//        List<String> objects = new ArrayList<>();
//        dataList.forEach(d->{
//            objects.addAll(d.keySet());
//        });
//        System.out.println("属性项:"+objects);
//        System.out.println("值:"+dataList);
//        inputStream.close();

//        LocalDateTimeUtil.parse("2023/3/26","yyyy/MM/dd");
        LocalDateTimeUtil.of(DateUtil.parse("2023/3/26","yyyy/MM/dd"));
    }
}
