package com.pqs9900.util.csv;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * system
 *
 * @author cdf
 * @date 2021/12/14
 */
public class ReadCsvUtil {
    private static final String FIX="\uFEFF";
    /**
     * 获取csv文件内容
     * @return 对象list
     */
    public static List<Map<String,Object>> getResource(byte[] bate) throws IOException {
        List<Map<String,Object>> allString = new ArrayList();
        Map<String,Object> callLogInfo;
        List<String> list = new ArrayList();
        // 获取文件内容
        list = getSource(bate);
        // 获取文件表头
        List<String> title = Arrays.asList(list.get(0).split(","));
        //此处可用一循环去获取文件表头
        String customerName = title.get(0).trim();

        // 头部会带有"\uFEFF"值
        if(customerName.startsWith(FIX)){
            customerName = customerName.replace(FIX, "");
        }
        callLogInfo = new HashMap();
        //此处可用一循环遍历所有列
        callLogInfo.put("列名",customerName);
        //将当前列处理完后加入list中
        allString.add(callLogInfo);
        //去掉表头行
        list.remove(0);
        // 循环内容
        for(int i = 0; i<list.size();i++){
            List<String> content = Arrays.asList(list.get(i).split(","));
            if(content!=null){
                callLogInfo = new HashMap();
                //此处可根据需要遍历所有列添加
                callLogInfo.put("列名",content.get(0));

                allString.add(callLogInfo);
            }
        }
        return allString;
    }

    /**
     * 读文件数据
     */
    public static List<String> getSource(byte[] bate) throws IOException {
        BufferedReader br = null;
        ByteArrayInputStream fis=null;
        InputStreamReader isr = null;
        try {
            fis = new ByteArrayInputStream(bate);
            //指定以当前文件编码读取
            isr = new InputStreamReader(fis,GetByteEncode.getEncoding(bate));
            br = new BufferedReader(isr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String line;
        String everyLine ;
        List<String> allString = new ArrayList<>();
        try {
            //读取到的内容给line变量
            while ((line = br.readLine()) != null){
                everyLine = line;
                allString.add(everyLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fis != null){
                fis.close();
            }
            if(isr != null){
                isr.close();
            }
        }
        return allString;
    }

}
