package com.sptg.gateway.controller.common.excel;

import com.sptg.common.core.beans.ExcelResultEnum;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.gateway.service.ExcelService;
import com.sptg.gateway.service.ExcelServiceFactory;
import com.sptg.permissions.api.feigns.ImportExcelErrorFeign;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author WFT
 * @date 2020/5/28
 * description:
 */
@RestController()
@RequiredArgsConstructor
public class ExcelImportController {

    private final ExcelServiceFactory excelServiceFactory;
    private final ImportExcelErrorFeign excelErrorFeign;

    @PostMapping(value = "/excel/import")
    public ResultBean<?> importExcel(@RequestParam("file") MultipartFile multipartFile, String flag){
        Assert.notNull(multipartFile,"参数异常");
        Assert.notNull(flag,"flag不能为空");
        //  获取相应Service
        ExcelService service = this.excelServiceFactory.getService(flag);
        Assert.notNull(service,"参数异常");
        //  读取表格数据
        InputStream inputStream = null;
        try{
            //  获取文件名
            String filename = multipartFile.getOriginalFilename();
            inputStream = multipartFile.getInputStream();
            //  读取数据
            Workbook workbook = service.getWorkbook(filename, inputStream);
            service.read(workbook.getSheetAt(0),this.excelErrorFeign);
        } catch (IOException e){
            e.printStackTrace();
            return new ResultBean<>(ExcelResultEnum.ERROR);
        } finally {
            if (null != inputStream){
                try {
                    inputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return ResultBean.ok();
    }

}
