package cn.com.ctop.common.module.utils;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yumeng
 * 2019年11月12日10:04:00
 */
@Slf4j
public class CsvUtils {
    public static void checkandCreateFile(String outPath) {
        File file = new File(outPath);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public static List<String[]> readCsv(String inPath, String charset) throws IOException {
        List<String[]> list = new ArrayList<>();
        CsvReader reader = new CsvReader(inPath, ',', Charset.forName(charset));
        reader.readHeaders();
        while (reader.readRecord()) {
            list.add(reader.getValues());
        }
        reader.close();
        return list;
    }

    public static void writeCsv(String outPath, List<String[]> data) throws IOException {
        CsvUtils.checkandCreateFile(outPath);
        CsvWriter wr = new CsvWriter(outPath, ',', Charset.forName("gb2312"));
        String[] header = {"Name", "Province", "City", "Address", "Tel", "Website", "Server_content", "Jigou_cengji", "Type", "Parent_level1", "Parent_level2", "Branch_level"};
        wr.writeRecord(header);
        for (int i = 0; i < data.size(); i++) {
            String[] dataString = data.get(i);
            wr.writeRecord(dataString);
        }
        wr.close();
    }
}
