package com.bailuntec.serviceImpl;

import com.bailuntec.domain.pojo.FileModel;
import com.bailuntec.service.RevenueAutomationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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 org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Service
@Slf4j
public class RevenueAutomationServiceImpl implements RevenueAutomationService {

    /**
     * 解压文件, 遍历文件夹读取文件夹
     *
     * @param file
     * @return
     */
    @Override
    public List<FileModel> unzip(MultipartFile file) {
        // 判断文件是否为zip文件
        String filename = file.getOriginalFilename();
        if (!filename.endsWith("zip")) {
            log.info("传入文件格式不是zip文件" + filename);
        }
        List<FileModel> fileModelList = new ArrayList<>();
        String zipFileName = null;
        // 对文件进行解析
        try {
            ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream(), Charset.forName("GBK"));
            BufferedInputStream bs = new BufferedInputStream(zipInputStream);
            ZipEntry zipEntry;
            byte[] bytes = null;
            while ((zipEntry = zipInputStream.getNextEntry()) != null) { // 获取zip包中的每一个zip file entry
                zipFileName = zipEntry.getName();
                if (!zipEntry.isDirectory()) {
                    Assert.notNull(zipFileName, "压缩文件中子文件的名字格式不正确");
                    FileModel fileModel = new FileModel();
                    fileModel.setFileName(zipFileName);
                    bytes = new byte[(int) zipEntry.getSize()];
                    bs.read(bytes, 0, (int) zipEntry.getSize());
                    InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                    fileModel.setFileInputstream(byteArrayInputStream);
                    fileModel.setFileType(zipFileName.substring(zipFileName.lastIndexOf(".") + 1, zipFileName.length()));
                    fileModelList.add(fileModel);
                }
            }
            bs.close();
            zipInputStream.close();
        } catch (Exception e) {
            log.error("读取压缩包文件内容失败,请确认压缩包包格式正确:" + zipFileName, e);
        }
        for (FileModel fileModel : fileModelList) {
            log.warn("文件名: " + fileModel.getFileName() + "   文件类型:" + fileModel.getFileType());
            try {
                switch (fileModel.getFileType().toLowerCase()) {
                    case "csv":
//                        handleCsvFile(fileModel);
                        break;
                    case "xls":
                    case "xlsx":
                        handleExcelFile(fileModel);
                        break;
                }
            } catch (Exception e) {
                log.error("读取文件内容失败,请确认文件格式正确:" + fileModel.getFileName(), e);
            }
        }
        return fileModelList;
    }


    private void handleExcelFile(FileModel fileModel) throws IOException {
        Workbook workbook;
        if (fileModel.getFileType().equals("xls")) {
            workbook = new HSSFWorkbook(fileModel.getFileInputstream());
        } else {
            workbook = new XSSFWorkbook(fileModel.getFileInputstream());
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
            Sheet sheet = workbook.getSheetAt(sheetNum);
            // 校验sheet是否合法
            if (sheet == null) {
                continue;
            }
            int rowStart = sheet.getFirstRowNum();
            int rowEnd = sheet.getPhysicalNumberOfRows();
            for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (null == row || rowNum == 0) {
                    continue;
                }
                short cellNum = row.getLastCellNum();
                log.warn(simpleDateFormat.format(row.getCell(0).getDateCellValue()));
                log.warn(simpleDateFormat.format(row.getCell(1)));
            }
        }

    }

    private void handleCsvFile(FileModel fileModel) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileModel.getFileInputstream(), Charset.forName("GBK")));
        String line = "";
        String[] arrs = null;
        while ((line = bufferedReader.readLine()) != null) {
            log.warn(line);
        }
    }
}
