package com.css.simulation.resource.common.adapter.controller;

import api.common.pojo.common.ResponseBodyVO;
import api.common.util.ExcelUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

@Slf4j
@RestController
@RequestMapping("/excel")
public class ExcelController {

    /**
     * 不解析第一列
     * @param excel
     * @return
     */
    @PostMapping(value = "/parse", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @SneakyThrows
    public ResponseBodyVO<List<List<String>>> parse(@RequestPart("excel") MultipartFile excel) {
        String originalFilename = excel.getOriginalFilename();
        log.info("excel 名称为：" + originalFilename);
        String suffix = originalFilename.split("\\.")[1];
        InputStream inputStream = excel.getInputStream();
        Workbook workbook = ExcelUtil.getExcel(inputStream, suffix);
        Sheet sheet = ExcelUtil.getSheetByIndex(workbook, 0);
        List<List<String>> table = ExcelUtil.getTable(sheet, 0, Integer.MAX_VALUE, 1, Integer.MAX_VALUE);
        workbook.close();
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS, table);
    }


    /**
     * 解析全部字段
     * @param excel
     * @return
     */
    @PostMapping(value = "/parseAll", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @SneakyThrows
    public ResponseBodyVO<List<List<String>>> parseAll(@RequestPart("excel") MultipartFile excel) {
            String originalFilename = excel.getOriginalFilename();
            log.info("excel 名称为：" + originalFilename);
            String suffix = originalFilename.split("\\.")[1];
            InputStream inputStream = excel.getInputStream();
            Workbook workbook = ExcelUtil.getExcel(inputStream, suffix);
            Sheet sheet = ExcelUtil.getSheetByIndex(workbook, 0);
            List<List<String>> table = ExcelUtil.getTable(sheet, 0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE);
            workbook.close();
            return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS, table);
    }



}
