package org.dromara.system.listener;

import com.alibaba.excel.EasyExcelFactory;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 学生成绩导入
 * @Author: tjf
 * @Date: 2023/8/31 10:36
 * @Describe:
 */
public class XiaoYuanPayUtil {

    /**
     * 动态表头导入功能
     *
     * @param file 文件
     * @return
     */
    public static List<Map<String, String>> importExcel(MultipartFile file) {
        try {
            // 首先校验传入文件是否为空
            if (file == null) {
                throw new RuntimeException("传入数据为空");
            }
            // 引入监听器（此处需注意，监听器不可被Spring管理）
            XiaoYuanPayListener readListener = new XiaoYuanPayListener();
            // 开始处理excel
            EasyExcelFactory.read(file.getInputStream(), readListener)
                .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);
           if (!excelHeadIdxNameMap.containsValue("姓名")){
               throw new RuntimeException("表头不能缺少姓名");
           }
            if (!excelHeadIdxNameMap.containsValue("手机号")){
                throw new RuntimeException("表头不能缺少手机号");
            }
            if (!excelHeadIdxNameMap.containsValue("发放时间")){
                String faTime = excelHeadIdxNameMap.get("发放时间");
                String[] split = faTime.split("-");
                if (split.length < 1){
                    throw new RuntimeException("发放时间格式需要是yyyy-MM");
                }
                throw new RuntimeException("表头不能缺少发放时间");
            }
            //封装数据体
            List<Map<String, String>> excelDataList = new ArrayList<Map<String, String>>();
            for (Map<Integer, String> dataRow : dataList) {
                HashMap<String, String> rowData = new HashMap<>();
                excelHeadIdxNameMap.entrySet().forEach(columnHead -> {
                    rowData.put(columnHead.getValue(), dataRow.get(columnHead.getKey()));
                });
                excelDataList.add(rowData);
            }
            return excelDataList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导入失败");
        }
    }
}
