package com.srs.stureg.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linuxense.javadbf.DBFReader;
import org.springframework.web.multipart.MultipartFile;

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

public class TogglesDbf {

    //将dbf文件转换为对象工具类
    public static List<Map<String, Object>> uploadDBFFile(MultipartFile file) {
        try {
            // 获取上传的文件输入流
            //FileInputStream inputStream = new FileInputStream("C:\\Users\\10202\\OneDrive\\桌面\\2022年录取信息\\安徽2012\\T_KSJL.dbf");
            InputStream inputStream = file.getInputStream();
            // 创建DBFReader对象
            DBFReader reader = new DBFReader(inputStream);
            reader.setCharactersetName("GBK");
            // 获取DBF文件中的字段信息
            int numFields = reader.getFieldCount();
            List<String> fieldNames = new ArrayList<>();
            for (int i = 0; i < numFields; i++) {
                fieldNames.add(reader.getField(i).getName());
            }
            // 解析DBF文件中的数据
            List<Map<String, Object>> records = new ArrayList<>();
            Object[] row;
            while ((row = reader.nextRecord()) != null) {
                Map<String, Object> record = new HashMap<>();
                for (int i = 0; i < numFields; i++) {
                    record.put(fieldNames.get(i).trim(),row[i]);
                }
                records.add(record);
            }
            // 关闭DBFReader对象
            inputStream.close();
            //reader.close();
            // 使用Jackson将解析的数据转换为JSON格式
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(records);
            List<Map< String,Object>> personList = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {});
            // 返回JSON数据
            return personList;
        } catch (Exception e) {
            e.printStackTrace();//打印异常信息
            return null;
        }
    }
}
