package cn.hmsoft.helper.dbf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;

import com.linuxense.javadbf.DBFField;
import com.linuxense.javadbf.DBFReader;
import com.linuxense.javadbf.DBFWriter;

import cn.hmsoft.frame.exception.BusinessException;

/*******************
 * DBF辅助工具
 * 
 * @author zxq
 * @create 2019-07-02 09:49:16
 * @version 2.0.0
 * @email: revisit@126.com
 * @Company: www.hmsoft.cn
 */
public class DbfHelper {
	public static List<List<String>> readDbf(MultipartFile file, List<String> columnArray) {
		List<List<String>> values = new ArrayList<List<String>>();
		InputStream fis = null;
		DBFReader reader = null;
		try {
			fis = file.getInputStream();
			reader = new DBFReader(fis);
			reader.setCharactersetName("GBK");
			Object[] rowValues;

			for (int index = 0; index < reader.getFieldCount(); index++) {
				DBFField field = reader.getField(index);
				columnArray.add(field.getName());
			}

			while ((rowValues = reader.nextRecord()) != null) {
				List<String> array = new ArrayList<String>();
				for (int i = 0; i < rowValues.length; i++) {
					Object obj = rowValues[i];
					if (obj == null)
						array.add(null);
					else
						array.add(obj.toString());
				}
				values.add(array);
			}
		} catch (Exception e) {
			return null;
		} finally {
			try {
				fis.close();
			} catch (Exception e) {

			}
		}
		return values;
	}
	/*********************************
	 * 读取dbf文件
	 * 
	 * @param file
	 *            dbf文件
	 * @param columnArray
	 *            字段
	 * @return
	 */
	public static List<List<String>> readDbf(File file, List<String> columnArray) {
		List<List<String>> values = new ArrayList<List<String>>();
		InputStream fis = null;
		DBFReader reader = null;
		try {
			fis = new FileInputStream(file);
			reader = new DBFReader(fis);
			reader.setCharactersetName("GBK");
			Object[] rowValues;

			for (int index = 0; index < reader.getFieldCount(); index++) {
				DBFField field = reader.getField(index);
				columnArray.add(field.getName());
			}

			while ((rowValues = reader.nextRecord()) != null) {
				List<String> array = new ArrayList<String>();
				for (int i = 0; i < rowValues.length; i++) {
					Object obj = rowValues[i];
					if (obj == null)
						array.add(null);
					else
						array.add(obj.toString());
				}
				values.add(array);
			}
		} catch (Exception e) {
			return null;
		} finally {
			try {
				fis.close();
			} catch (Exception e) {

			}
		}
		return values;
	}

	public static void saveAsDbf(File file, Map<String, Integer> titleMap, List<Map<String, Object>> valuesMap) {
		DBFField[] fields = new DBFField[titleMap.size()];
		int index = 0;
		for (String key : titleMap.keySet()) {
			fields[index] = new DBFField();
			fields[index].setName(key.toUpperCase().trim());
			fields[index].setDataType(DBFField.FIELD_TYPE_C);
			fields[index].setFieldLength(titleMap.get(key));
			index++;
		}
		DBFWriter writer = new DBFWriter();
		OutputStream fos = null;
		try {
			writer.setCharactersetName("gbk");
			// 把字段信息写入DBFWriter实例，即定义表结构
			writer.setFields(fields);
			for (Map<String, Object> value : valuesMap) {
				Object[] rowData = new Object[titleMap.size()];
				index = 0;
				for (String key : titleMap.keySet()) {
					if (value.containsKey(key)) {
						Object obj = value.get(key);
						if (obj == null) {
							rowData[index] = null;
						} else {
							rowData[index] = obj.toString();
						}
					} else {

						rowData[index] = null;
					}
					index++;
				}
				writer.addRecord(rowData);
			}
			fos = new FileOutputStream(file);
			// 写入数据
			writer.write(fos);
		} catch (Exception e) {
			throw new BusinessException("写入dbf文件错误！");
		} finally {
			try {
				fos.close();
			} catch (Exception e) {

			}
		}
	}

	public static void saveAsDbf(File file, List<List<Object>> valuesMap, Map<String, Integer> titleMap) {
		DBFField[] fields = new DBFField[titleMap.size()];
		int index = 0;
		for (String key : titleMap.keySet()) {
			fields[index] = new DBFField();
			fields[index].setName(key.toUpperCase().trim().equals("#") ? "xh" : key.toUpperCase().trim());
			fields[index].setDataType(DBFField.FIELD_TYPE_C);
			fields[index].setFieldLength(titleMap.get(key));
			index++;
		}
		DBFWriter writer = new DBFWriter();
		OutputStream fos = null;
		try {
			writer.setCharactersetName("gbk");
			// 把字段信息写入DBFWriter实例，即定义表结构
			writer.setFields(fields);
			for (List<Object> array : valuesMap) {
				Object[] rowData = new Object[titleMap.size()];
				index = 0;
				for (int v = 0; v < array.size(); v++) {
					if (array.get(v) == null)
						rowData[index] = null;
					rowData[index] = array.get(v).toString();
					index++;
				}
				writer.addRecord(rowData);
			}
			fos = new FileOutputStream(file);
			// 写入数据
			writer.write(fos);
		} catch (Exception e) {
			throw new BusinessException("写入dbf文件错误！");
		} finally {
			try {
				fos.close();
			} catch (Exception e) {

			}
		}
	}
}
