package com.dsk.system.service.impl;

import com.dsk.system.domain.business.dto.BusinessExcelDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author lxl
 * @Description:
 * @Date 2023/6/1 下午 4:30
 **/
@Slf4j
@Service
public class ReadBusinessInfoExcel {

    // 总行数
    private int totalRows = 0;
    // 总条数
    private int totalCells = 0;

    public int getTotalRows() {
        return totalRows;
    }

    public void setTotalRows(int totalRows) {
        this.totalRows = totalRows;
    }

    public int getTotalCells() {
        return totalCells;
    }

    public void setTotalCells(int totalCells) {
        this.totalCells = totalCells;
    }

    /**
     * 读EXCEL文件，获取信息集合
     *
     * @param mFile
     * @return
     */
    public List<BusinessExcelDto> getExcelInfo(MultipartFile mFile) {
        String fileName = mFile.getOriginalFilename();// 获取文件名
        try {
            // 验证文件名是否合格
            if (!validateExcel(fileName)) return null;
            // 根据文件名判断文件是2003版本还是2007版本
            boolean isExcel2003 = true;
            if (isExcel2007(fileName)) isExcel2003 = false;
            return createExcel(mFile.getInputStream(), isExcel2003);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据excel里面的内容读取信息
     *
     * @param is          输入流
     * @param isExcel2003 excel是2003还是2007版本
     * @return
     */
    public List<BusinessExcelDto> createExcel(InputStream is, boolean isExcel2003) {
        try {
            Workbook wb = null;
            // 当excel是2003时,创建excel2003
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                // 当excel是2007时,创建excel2007
                wb = new XSSFWorkbook(is);
            }
            return readExcelValue(wb);// 读取Excel里面客户的信息
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 读取Excel内容
     *
     * @param wb
     * @return
     */
    private List<BusinessExcelDto> readExcelValue(Workbook wb) {
        //得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        //得到Excel的行数
        this.totalRows = sheet.getPhysicalNumberOfRows();
        //得到Excel的列数(前提是有行数)
        if (totalRows > 1 && sheet.getRow(0) != null) {
            this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
//        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        ArrayList<BusinessExcelDto> list = new ArrayList<>();
        //循环Excel行数
        //
        for (int r = 3; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            //循环Excel的列
//            Map<String, Object> map = new HashMap<String, Object>();
            BusinessExcelDto businessExcelDto = new BusinessExcelDto();
            for (int c = 0; c < this.totalCells; c++) {
                Cell cell = row.getCell(c);
                if (null != cell) {
                    //项目名称
                    if (c == 0) {
                        //如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
                        if (cell.getCellType() == CellType.NUMERIC) {
                            String name = String.valueOf(cell.getNumericCellValue());
                            businessExcelDto.setProjectName(name.substring(0, name.length() - 2 > 0 ? name.length() - 2 : 1));
                        } else {
                            businessExcelDto.setProjectName(cell.getStringCellValue());
                        }
                        //业主单位
                    } else if (c == 1) {
                        if (cell.getCellType() == CellType.NUMERIC) {
                            String company = String.valueOf(cell.getNumericCellValue());
                            businessExcelDto.setOwnerCompany(company.substring(0, company.length() - 2 > 0 ? company.length() - 2 : 1));
                        } else {
                            businessExcelDto.setOwnerCompany(cell.getStringCellValue());
                        }
                        //投资估算（万元）
                    } else if (c == 2) {
                        if (cell.getCellType() == CellType.NUMERIC) {
                            String amount = String.valueOf(cell.getNumericCellValue());
//                            businessExcelDto.setInvestmentAmount(amount.substring(0, amount.length() - 2 > 0 ? amount.length() - 2 : 1));
                            businessExcelDto.setInvestmentAmount(amount);
                        } else {
                            businessExcelDto.setInvestmentAmount(cell.getStringCellValue());
                        }
                    }
                }
            }
            //添加到list
            list.add(businessExcelDto);
        }
        log.info("项目批量导入Excel数据,{}",list);
        return list;
    }

    /**
     * 验证EXCEL文件
     * @param filePath
     * @return
     */
    public boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            log.info("文件不是excel格式");
            return false;
        }
        return true;
    }

    // @描述：是否是2003的excel，返回true是2003
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    // @描述：是否是2007的excel，返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
}
