package cn.com.tenlion.systembase.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * excel工具类
 * @author renpc
 */
public class ExcelUtil {

    /**
     * 默认excel文件名和单元sheet名一样的 Excel文件导出
     * @param httpServletResponse
     * @param data
     * @param fileName
     * @param clazz
     * @throws IOException
     */
    public static void writeExcel(HttpServletResponse httpServletResponse, List data, String fileName, Class clazz) throws IOException {
        writeExcel(httpServletResponse, data, fileName, fileName, clazz);
    }

    /**
     * 导出数据为Excel文件
     * @param response  响应实体
     * @param data  导出数据
     * @param fileName 文件名
     * @param sheetName 单元格名
     * @param clazz  定义excel导出的实体
     * @throws IOException
     */
    public static void writeExcel(HttpServletResponse response, List data, String fileName, String sheetName, Class clazz) throws IOException {
        //防止中文乱码
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //防止导入excel文件名中文不乱码
        response.setHeader("Content-disposition", "attachment;fileName=" + fileName + ".xlsx" + ";fileName*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);
    }

    /**
     *  easyExcel处理上传的文件
     * @param sheetNo 单元格
     * @param rowNumber 行数
     * @param analysisEventListener  上传处理监听
     * @param clazz  上传处理excel类
     * @return
     * @throws Exception
     */
    public static List<Object> readExcel(MultipartFile file, Integer sheetNo, Integer rowNumber, AnalysisEventListener analysisEventListener, Class clazz) throws Exception {
        if(null != file) {
            String originalFilename = file.getOriginalFilename();
            if(StringUtils.isEmpty(originalFilename)){
                throw new Exception("上传的文件不能为空");
            }
            if(!originalFilename.toLowerCase().endsWith(ExcelTypeEnum.XLS.getValue()) &&
                    !originalFilename.toLowerCase().endsWith(ExcelTypeEnum.XLSX.getValue())){
                throw new Exception("上传的文件格式不匹配");
            }
            InputStream inputStream = file.getInputStream();
            return EasyExcel.read(inputStream, clazz, analysisEventListener).sheet(sheetNo).headRowNumber(rowNumber).doReadSync();
        }
        throw new Exception("上传的文件不能为空");
    }

}
