package com.ruoyi.logistics.util;

import cn.hutool.core.util.ObjectUtil;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

public class ExcelImportValidato {
    /**
     * 校验 Excel 是否为规定模板（校验表头行）
     */
    public static boolean isValidTemplate(MultipartFile file, String[] requireHead) {
        try (InputStream is = file.getInputStream();
             Workbook workbook = WorkbookFactory.create(is)) {

            Sheet sheet = workbook.getSheetAt(0);
            Row headRow = sheet.getRow(0);

            if (ObjectUtil.isNull(headRow)) {
                return false;
            }

            // 列数必须一致
            if (headRow.getPhysicalNumberOfCells() != requireHead.length) {
                return false;
            }

            // 逐列校验表头
            for (int i = 0; i < requireHead.length; i++) {
                Cell cell = headRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                cell.setCellType(CellType.STRING);
                String val = cell.getStringCellValue().trim();

                if (!requireHead[i].equals(val)) {
                    return false;
                }
            }
            return true;

        } catch (Exception e) {
            return false;
        }
    }
}
