package com.foreverwin.mesnac.dataimport.reader;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mesnac.dataimport.util.AppUtil;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class XlsFileReader extends AbstractFileReader {

    private Workbook workBook;

    static Logger log4j = Logger.getLogger(XlsFileReader.class);

    @Override
    public int read(InputStream inputStream, Map<String, String> cvsheads) throws IOException {

        int updated = 0;
        String fileEncode = "";

        //String[] header = this.visitor.getHeader();
        workBook = new HSSFWorkbook(inputStream);

        try {
            Sheet sheet = workBook.getSheetAt(0); //默认只读取第一个sheet

            //header
            Row headerRow = sheet.getRow(0);
            String[] header = new String[headerRow.getPhysicalNumberOfCells()];

            for (int cellIndex = 0; cellIndex < headerRow.getPhysicalNumberOfCells(); cellIndex++) {
                Cell cell = headerRow.getCell(cellIndex);
                if(cell!=null){
                   // System.out.println(cell.getStringCellValue());
                    header[cellIndex] = cell.getStringCellValue().replace("\n","");
                }else{
                    header[cellIndex] = "";
                }

            }
            //end


            for (int rowIndex = 1; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) {
                Row r = sheet.getRow(rowIndex);
                JSONObject row = new JSONObject();
                for (int cellIndex = 0; cellIndex < r.getPhysicalNumberOfCells() && cellIndex < header.length; cellIndex++) {
                    Cell cell = r.getCell(cellIndex);
                    String value = "";
                    if (cell != null) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_NUMERIC:
                                value = String.valueOf(cell.getNumericCellValue());
                                break;
                            case Cell.CELL_TYPE_STRING:
                                value = cell.getStringCellValue();
                                break;
                            case Cell.CELL_TYPE_BOOLEAN:
                                value = String.valueOf(cell.getBooleanCellValue());
                                break;
                            default:
                                value = "";
                        }
                    }

                    String newKey = AppUtil.mapKeyFinder(cvsheads, header[cellIndex]);
                    if (newKey != null) {
                        //AppUtils.getUTFStringByEncoding(value)
                        row.put(newKey, value);

                    } else {
                        //String _name=headNames[index++];

                        if (header[cellIndex] != null && header[cellIndex].trim().length() > 0 && header[cellIndex].startsWith("自定义-")) {
                            String cust = header[cellIndex].substring("自定义-".length());
                           // cust=cust.replace(10,"");
                            //String value=data.get(name);
                            JSONObject customObject = new JSONObject();
                            customObject.put("attribute", cust);
                            customObject.put("value", value);

                            JSONArray customArray = null;
                            if (row.containsKey("customData")) {

                                customArray = row.getJSONArray("customData");
                                customArray.add(customObject);
                            } else {
                                customArray = new JSONArray();
                                customArray.add(customObject);
                                row.put("customData", customArray);
                            }
                        }
                    }

                    //row.put( header[cellIndex], value );
                }

                log4j.info("get row info->" + row);

                updated += this.visitor.visit(rowIndex + 2, row); //行下标默认从0开始，跳过Header
            }
        } finally {
            inputStream.close();
        }
        return updated;
    }

}
