package com.trade.common.utils.file;

import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ValidatorException;
import com.trade.common.utils.LoggerUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @description: Excel导入工具类
 * @Author: wanglang
 * @Date: 2024/9/7 14:39
 * @Version: 1.0
 */
public class ExcelImportUtils {

    private static final Logger log = LoggerUtil.logger(LoggerUtil.LogFileNameEnum.SERVICES_LOG);;
    /** 文件 **/
    private MultipartFile file;
    /** excel工作本对象 **/
    private Sheet sheet;
    private Workbook workbook;

    public ExcelImportUtils(MultipartFile file){
        this.file = file;
    }

    public ExcelImportUtils(){
    }

    public Sheet readFile() {
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.endsWith(MimeTypeUtils.XLSX_TYPE) && !fileName.endsWith(MimeTypeUtils.XLS_TYPE)) {
                throw new ValidatorException(HttpStatus.ERROR, "只支持.xls或.xlsx文件");
            }
            InputStream inputStream = file.getInputStream();
            if (fileName.toLowerCase().endsWith(MimeTypeUtils.XLSX_TYPE)) {
                workbook = new XSSFWorkbook(inputStream);
            } else if (fileName.toLowerCase().endsWith(MimeTypeUtils.XLS_TYPE)) {
                workbook = new HSSFWorkbook(inputStream);
            }
            sheet = workbook.getSheetAt(0);
            return sheet;
        } catch (IOException e) {
            log.error("文件读取失败", e);
            throw new ValidatorException(HttpStatus.ERROR, "文件读取失败");
        }
    }
}
