package cn.gintone.utils;

import cn.gintone.dto.PtExportDevice;
import cn.gintone.dto.PtExportDeviceType;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

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

public class PtExportDeviceUtils {
    public static List<PtExportDevice> readDevicesFromExcel(String filePath) throws IOException {
        List<PtExportDevice> devices = new ArrayList<>();
        try {
            InputStream inputStream = new FileInputStream(filePath);
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

            Iterator<Row> rowIterator = sheet.iterator();

            // 跳过表头行（如果需要）
            if (rowIterator.hasNext()) {
                rowIterator.next(); // 跳过第一行（标题行）
            }

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                PtExportDevice device = createDeviceFromRow(row);
                if (device != null) {
                    devices.add(device);
                }
            }

            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return devices;
    }

    private static PtExportDevice createDeviceFromRow(Row row) {
        // 检查行是否为空
        if (isRowEmpty(row)) {
            return null;
        }

        PtExportDevice device = new PtExportDevice();

        // 读取每一列的数据
        device.setDeviceSerialNo(getCellValue(row.getCell(0))); // Device Serial No
        device.setDeviceName(getCellValue(row.getCell(1)));     // Device Name
        device.setModelCode(getCellValue(row.getCell(2)));      // Model Code
        device.setDescription(getCellValue(row.getCell(3)));    // Description
        device.setLabel(getCellValue(row.getCell(4)));          // Label
        device.setDeviceSec(getCellValue(row.getCell(5)));      // Device Sec
        device.setClassification(getCellValue(row.getCell(6))); // Classification

        return device;
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 防止科学计数法
                    return String.valueOf((long) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    private static boolean isRowEmpty(Row row) {
        if (row == null) {
            return true;
        }
        if (row.getLastCellNum() <= 0) {
            return true;
        }
        for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
            Cell cell = row.getCell(cellNum);
            if (cell != null && cell.getCellType() != CellType.BLANK &&
                    !getCellValue(cell).isEmpty()) {
                return false;
            }
        }
        return true;
    }



    public static List<PtExportDeviceType> readDevicesTypeFromExcel(String filePath) throws IOException {
        List<PtExportDeviceType> deviceTypes = new ArrayList<>();
        try {
            InputStream inputStream = new FileInputStream(filePath);
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

            Iterator<Row> rowIterator = sheet.iterator();

            // 跳过表头行（如果需要）
            if (rowIterator.hasNext()) {
                rowIterator.next(); // 跳过第一行（标题行）
            }

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                PtExportDeviceType deviceType = createDeviceTypeFromRow(row);
                if (deviceType != null) {
                    deviceTypes.add(deviceType);
                }
            }

            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return deviceTypes;
    }

    private static PtExportDeviceType createDeviceTypeFromRow(Row row) {
        // 检查行是否为空
        if (isRowEmpty(row)) {
            return null;
        }

        PtExportDeviceType deviceType = new PtExportDeviceType();

        // 读取每一列的数据
        deviceType.setName(getCellValue(row.getCell(0))); // Device Serial No
        deviceType.setModelCode(getCellValue(row.getCell(1)));     // Device Name
        deviceType.setManufacturer(getCellValue(row.getCell(2)));      // Model Code
        deviceType.setIntegratedApplicationOwnership(getCellValue(row.getCell(3)));    // Description

        return deviceType;
    }
}
