package com.jeeplus.modules.warehouse.materialtype.utils;

import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.warehouse.materialtype.entity.MaterialType;
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 org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class InitMaterialType {

    public static List<MaterialType> initType(String filePath, String sheetName, String parentId, String parentIds) {
        List<MaterialType> resultList = new ArrayList<>();

        InputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            Workbook workbook = null;
            if (filePath.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (filePath.endsWith(".xls") || filePath.endsWith(".et")) {
                workbook = new HSSFWorkbook(fis);
            }
            fis.close();
            /* 读EXCEL文字内容 */
            // 获取第一个sheet表，也可使用sheet表名获取
            Sheet sheet = workbook.getSheet(sheetName);
            // 获取行
            Iterator<Row> rows = sheet.rowIterator();
            Row row;
            Cell cell;

            int sort = 1;
            while (rows.hasNext()) {
                row = rows.next();
                cell = row.getCell(0);
                String cellValue = POIUtil.getCellValue(cell);

                cell = row.getCell(1);
                String cellValue1 = POIUtil.getCellValue(cell);
                MaterialType type = new MaterialType();
                if (StringUtils.isBlank(cellValue)) {
                    continue;

                }
                if ("main".equals(sheetName)) {

                    type.setId(sort + "");
                }
                type.setCode(cellValue);
                type.setName(cellValue1);
                type.setParent(new MaterialType(parentId));
                type.setParentIds(parentIds);
                type.setSort(sort);
                resultList.add(type);
                sort++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return resultList;
    }
}
