package com.gree.mall.manager.logic.comlist;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.enums.admin.AdminWebsitTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.AdminWebsit;
import com.gree.mall.manager.plus.entity.ComDetail;
import com.gree.mall.manager.plus.entity.ComDetailLog;
import com.gree.mall.manager.plus.entity.ComList;
import com.gree.mall.manager.plus.service.AdminWebsitService;
import com.gree.mall.manager.plus.service.ComDetailLogService;
import com.gree.mall.manager.plus.service.ComDetailService;
import com.gree.mall.manager.plus.service.ComListService;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.utils.DateUtils;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import com.gree.mall.manager.utils.oss.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ComListLogic {

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    OSSUtil ossUtil;

    @Autowired
    ComDetailService comDetailService;
    @Autowired
    ComListService comListService;
    @Autowired
    ComDetailLogService comDetailLogService;
    @Autowired
    CommonMapper commonMapper;
    @Autowired
    AdminWebsitService adminWebsitService;


    public IPage<ComList> list(String title, String remark, Boolean isNotice, Integer pageNo, Integer pageSize, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        List<ComDetail> comDetails = comDetailService.lambdaQuery()
                .select(ComDetail::getComListId)
                .in(CollectionUtil.isNotEmpty(adminUser.getAdminWebsitIds()), ComDetail::getWebsitId, adminUser.getAdminWebsitIds())
                .list();
        List<String> comListIds = comDetails.stream().map(ComDetail::getComListId).collect(Collectors.toList());
        if (comListIds.size() == 0) {
            return new Page<>(pageNo, pageSize);
        }

        IPage<ComList> page = comListService.lambdaQuery()
                //.eq(StringUtils.isNotEmpty(admin.getBelongCompany()),ComList::getBelongCompany,admin.getBelongCompany())
                .in(ComList::getId, comListIds)
                .eq(isNotice != null, ComList::getIsNotice, isNotice)
                .like(StringUtils.isNotEmpty(title), ComList::getTitle, title)
                .like(StringUtils.isNotEmpty(remark), ComList::getRemark, remark)
                .eq( ComList::getType, "CENTER")
                .orderByDesc(ComList::getCreateTime)
                .page(new Page<>(pageNo, pageSize));
        //不返回密码
        page.getRecords().forEach(v -> v.setDownloadPwd(""));
        return page;
    }


    public void delete(String id, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if (adminUser.getType() == 0) {
            throw new RemoteServiceException("暂无权限");
        }
        comListService.removeById(id);
        comDetailService.lambdaUpdate().eq(ComDetail::getComListId, id).remove();
    }


    public void yonge(String title, String remark, String file, Boolean isNotice, String downloadPwd, HttpServletRequest request) throws RemoteServiceException, IOException {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        Map<String, String> map = new HashMap<>();
        ComList comList = new ComList();
        comList.setCompanyWechatId(adminUser.getCompanyWechatId());
        comList.setCompanyName(adminUser.getCompanyName());
        comList.setTitle(title);
        comList.setRemark(remark);
        comList.setFileName(title);
        comList.setIsNotice(isNotice);
        comList.setDownloadPwd(downloadPwd);
        comList.setIsPwd(StringUtils.isNotBlank(downloadPwd));
        comList.setOperatorUserName(adminUser.getUserName());
        comList.setOperatorNickName(adminUser.getNickName());
        comList.setCreateTime(new Date());
        comList.insert();

        //新增拆分的附件明细表
        ComDetail bean = new ComDetail();
        bean.setCompanyWechatId(adminUser.getCompanyWechatId());
        bean.setCompanyName(adminUser.getCompanyName());
        bean.setTitle(title);
        bean.setComListId(comList.getId());
        bean.setFileName(title);
        bean.setWebsitId(adminUser.getUserName());
        bean.setFileUrl(file);
        bean.setIsDownload(false);
        bean.setIsNotice(comList.getIsNotice());
        bean.setCreateTime(new Date());
        bean.insert();

        map.put(comList.getCompanyName(), comList.getId());

        //上传主文件到oss,并记录
        //CommonFile commonFile = commonLogic.uploadFile(file);

        InputStream inputStream = commonLogic.getFileInputStreamByUrl(file);
        List<Object> objects = ExcelUtils.importExcel(inputStream);
        //拆分excel并上传oss
        List<Map<String, Object>> fileUrls = this.createExcel(objects);
        if (fileUrls == null) {
            throw new RemoteServiceException("拆分失败");
        }
        List<ComDetail> comDetails = new ArrayList<>();
        for (Map<String, Object> fileUrl : fileUrls) {
            String websitNumber = (String) fileUrl.get("websitNumber");
            String filePath = (String) fileUrl.get("filePath");
            //新增拆分的附件明细表
            //for(Belongcompany belongcompany : list) {
            ComDetail comDetail = new ComDetail();
            comDetail.setCompanyWechatId(adminUser.getCompanyWechatId());
            comDetail.setCompanyName(adminUser.getCompanyName());
            comDetail.setTitle(title);
            comDetail.setComListId(map.get(comDetail.getCompanyName()));
            comDetail.setFileName(title);
            comDetail.setWebsitId(websitNumber);
            comDetail.setFileUrl(filePath);
            comDetail.setIsDownload(false);
            comDetail.setCreateTime(new Date());
            comDetail.setIsNotice(comList.getIsNotice());
            //comDetail.insert();
            comDetails.add(comDetail);
            //}
        }
        comDetailService.saveBatch(comDetails);
    }

    public void download(String id, String downloadPwd, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        ComList comList = comListService.getById(id);
        if (comList.getIsPwd() && !StringUtils.equals(comList.getDownloadPwd(), downloadPwd)) {
            throw new RemoteServiceException("下载密码校验失败，请联系相关人员");
        }
        log.info("【中心文件下发下载】:{}", JSONObject.toJSONString(adminUser));
        List<ComDetail> comDetails = comDetailService.lambdaQuery()
                .eq(ComDetail::getComListId, id)
                .in(ComDetail::getWebsitId, adminUser.getAdminWebsitIds())
                .list();

        if (CollectionUtils.isEmpty(comDetails)) {
            throw new RemoteServiceException("暂无您可下载的内容");
        }
        this.download(comDetails, adminUser, response);
    }

    private void download(List<ComDetail> comDetails, AdminUserCom admin, HttpServletResponse response) throws IOException {
        String title = comDetails.get(0).getTitle();

        final List<AdminWebsit> websitList = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getCompanyWechatId, admin.getCompanyWechatId())
                .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey())
                .in(AdminWebsit::getWebsitId, admin.getAdminWebsitIds())
                .list();

        final Map<String, String> websitMap = websitList.stream().collect(Collectors.toMap(AdminWebsit::getWebsitId, AdminWebsit::getName));

        for (ComDetail comDetail : comDetails) {
            ComDetailLog comDetailLog = new ComDetailLog();
            comDetailLog.setCompanyWechatId(admin.getCompanyWechatId());
            comDetailLog.setCompanyName(admin.getCompanyName());
            comDetailLog.setCreateTime(new Date());
            comDetailLog.setComListId(comDetail.getComListId());
            comDetailLog.setTitle(comDetail.getTitle());
            comDetailLog.setUserName(admin.getUserName());
            comDetailLog.setWebsitId(comDetail.getWebsitId());
            comDetailLog.setIsNotice(comDetail.getIsNotice());
            comDetailLog.setWebsitName(websitMap.get(comDetail.getWebsitId()));
            comDetailLog.insert();
        }
        List<Map<String, Object>> files = new ArrayList<>();
        //String fileUrl = comDetail.getFileUrl();
        for (ComDetail comDetail : comDetails) {
            if (StringUtils.isEmpty(comDetail.getWebsitId())) {
                continue;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("fileUrl", comDetail.getFileUrl());
            map.put("fileName", comDetail.getWebsitId() + "-(" + comDetail.getTitle() + ").xlsx");
            files.add(map);
        }
        if (files.size() > 1) {
            CommonUtils.writeZip(response, files);
        } else {
            CommonUtils.downloadFile(files.get(0).get("fileUrl").toString(), websitMap.get(admin.getAdminWebsitIds().get(0)) + "-" + title + ".xlsx", response);
        }
        //CommonUtils.downloadFile(imgFile,admin.getWebsitNumber()+"-"+comDetail.getTitle()+".csv",response);
        //return imgFile;
    }


    public IPage<ComDetailLog> logList(String id, Integer pageNo, Integer pageSize, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        IPage<ComDetailLog> page = comDetailLogService.lambdaQuery()
                .in(CollectionUtil.isNotEmpty(adminUser.getAdminWebsitIds()), ComDetailLog::getWebsitId, adminUser.getAdminWebsitIds())
                .eq(Objects.nonNull(adminUser.getAdminCompanyWechat()), ComDetailLog::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(ComDetailLog::getComListId, id)
                .orderByDesc(ComDetailLog::getCreateTime)
                .page(new Page<>(pageNo, pageSize));
        return page;
    }

    /**
     * 未下载的中心文件
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<ComList> notDownComList(Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (adminUser.getType() != 0) {
            return new Page<>();
        }
        IPage<ComList> comListIPage = commonMapper.queryComList(new Page(pageNum, pageSize), adminUser.getAdminWebsitIds(), adminUser.getUserName());
        return comListIPage;
    }

    /**
     * 公告提示的批量下载文件
     */
    public void download(Integer pageSize, HttpServletResponse response) throws IOException {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //最多下载10个
        IPage<ComList> comListIPage = commonMapper.queryComList(new Page(1, 10), adminUser.getAdminWebsitIds(), adminUser.getUserName());
        if (CollectionUtils.isEmpty(comListIPage.getRecords())) {
            return;
        }
        List<String> comListIds = comListIPage.getRecords().stream().map(ComList::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(comListIds))
            return;
        List<ComDetail> comDetails = comDetailService.lambdaQuery()
                .in(ComDetail::getComListId, comListIds)
                .in(ComDetail::getWebsitId, adminUser.getAdminWebsitIds()).list();
        if (CollectionUtils.isEmpty(comDetails)) {
            return;
        }
        List<String> comDetailIds = comDetails.stream().map(ComDetail::getId).collect(Collectors.toList());
        comDetailService.lambdaUpdate().set(ComDetail::getIsDownload, true).in(ComDetail::getId, comDetailIds).update();
        this.download(comDetails, adminUser, response);
    }


    /**
     * 创建Excel
     */
    public List<Map<String, Object>> createExcel(List<Object> datas) {
        try {
            // List<Object> datas = ExcelUtils.importExcel(file);
            List<Object> tableHeaders = (List<Object>) datas.get(0);

            Map<String, List<List<Object>>> map = new HashMap<>();
            log.info("【中心下发文件1】" + DateUtils.formatDate(new Date()));
            for (int i = 1; i < datas.size(); i++) {
                List<Object> row = (List<Object>) datas.get(i);
                CommonUtils.initList2(row, row.size() + 1);
                //网点编号
                String websitNumber = (String) row.get(1);

                List<List<Object>> objects = map.get(websitNumber);
                if (objects == null) {
                    objects = new ArrayList<>();
                }
                //row.remove(0);
                objects.add(row);

                if (!map.containsKey(websitNumber)) {
                    map.put(websitNumber, objects);
                }
            }
            log.info("【中心下发文件2】" + DateUtils.formatDate(new Date()));
            List<Map<String, Object>> fileUrls = new ArrayList<>();
            for (String websitNumber : map.keySet()) {
                //String filePath = "B:/"+email+"-"+file.getName()+".xlsx";
                long currentTime = System.currentTimeMillis();
                String filePath = OSSUtil.OSS_TYPE_PIC + websitNumber + currentTime + ".csv";
                //executorService.submit( ()->{
//                    try {
//                ExcelData excelData = new ExcelData();
//                excelData.setTitles(tableHeaders);
//                excelData.setRows(map.get(websitNumber));

                this.write(filePath, tableHeaders, map.get(websitNumber));
//                    } catch (IOException e) {
//                        log.error("上传文件失败",e);
//                    }
                //});

                String ossUrl = ossUtil.getAccessUrl() + filePath;
                Map<String, Object> mp = new HashMap<>();
                mp.put("websitNumber", websitNumber);
                mp.put("filePath", ossUrl);
                fileUrls.add(mp);
            }
            log.info("【中心下发文件3】" + DateUtils.formatDate(new Date()));
            return fileUrls;
        } catch (Exception e) {
            log.error("【创建excel失败】", e);
        }
        return null;
    }


    //    public void export(ExcelData excelData,String fileName) throws IOException {
//        OutputStream outputStream = null;
//        try {
//            //标题
//            List<List<String>> titles = new ArrayList<>();
//            for(String title : excelData.getTitles()){
//                titles.add(Arrays.asList(title));
//            }
//
//            //记录总数:实际中需要根据查询条件进行统计即可
//            Integer totalCount = excelData.getRows().size();
//            //每一个Sheet存放100w条数据
//            Integer sheetDataRows = 1000000;
//            //每次写入的数据量20w,每页查询20W
//            Integer writeDataRows = 200000;
//            //计算需要的Sheet数量
//            Integer sheetNum = totalCount % sheetDataRows == 0 ? (totalCount / sheetDataRows) : (totalCount / sheetDataRows + 1);
//            //计算一般情况下每一个Sheet需要写入的次数(一般情况不包含最后一个sheet,因为最后一个sheet不确定会写入多少条数据)
//            Integer oneSheetWriteCount = sheetDataRows / writeDataRows;
//            //计算最后一个sheet需要写入的次数
//            Integer lastSheetWriteCount = totalCount % sheetDataRows == 0 ? oneSheetWriteCount : (totalCount % sheetDataRows % writeDataRows == 0 ? (totalCount / sheetDataRows / writeDataRows) : (totalCount / sheetDataRows / writeDataRows + 1));
//            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//            HttpServletResponse response = requestAttributes.getResponse();
//            outputStream = response.getOutputStream();
//
//            //样式
//            WriteCellStyle cellStyle = writeCellStyle();
//
//            //必须放到循环外，否则会刷新流
//            ExcelWriter excelWriter = EasyExcel.write(outputStream).registerWriteHandler(new CellWriteHandler(){
//                public void afterCellDispose(CellWriteHandlerContext context) {
//                    CellWriteHandler.super.afterCellDispose(context);
//                    if (BooleanUtils.isNotTrue(context.getHead())) {
//                        context.getFirstCellData().setWriteCellStyle(cellStyle);
//                    }
//                }
//            }).build();
//            //开始分批查询分次写入
//            for (int i = 0; i < sheetNum; i++) {
//                //创建Sheet
////                WriteSheet sheet = new WriteSheet();
////                sheet.setSheetName("Sheet"+i);
////                sheet.setSheetNo(i);
//                //循环写入次数: j的自增条件是当不是最后一个Sheet的时候写入次数为正常的每个Sheet写入的次数,如果是最后一个就需要使用计算的次数lastSheetWriteCount
//                for (int j = 0; j < (i != sheetNum - 1 ? oneSheetWriteCount : lastSheetWriteCount); j++) {
//                    //分页查询一次20w
//                    WriteSheet writeSheet = EasyExcel.writerSheet(i, "Sheet" + (i + 1)).head(titles)
//                            .registerWriteHandler(new SimpleColumnWidthStyleStrategy(30))
//                            .build();
//                    //写数据
//                    excelWriter.write(excelData.getRows(), writeSheet);
//                }
//            }
//            // 下载EXCEL
////            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
////            response.setCharacterEncoding("utf-8");
////            // 这里URLEncoder.encode可以防止浏览器端导出excel文件名中文乱码 当然和easyexcel没有关系
////            //String fileName = URLEncoder.encode("员工信息", "UTF-8").replaceAll("\\+", "%20");
////            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
//            Workbook workbook = excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
//            ByteArrayOutputStream ba = new ByteArrayOutputStream();
//            try {
//                workbook.write(ba);
//                ByteArrayInputStream bio = new ByteArrayInputStream(ba.toByteArray());
//                ossUtil.uploadFile(fileName,bio);
//                bio.close();
//            }finally {
//                ba.flush();
//                ba.close();
//            }
//            excelWriter.finish();
//            outputStream.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (BeansException e) {
//            e.printStackTrace();
//        }finally {
//            if (outputStream != null) {
//                outputStream.close();
//            }
//        }
//    }
//
//
//    /**
//     * excel样式
//     * @return
//     */
    public static WriteCellStyle writeCellStyle() {
        //样式
        WriteFont font = new WriteFont();
        font.setFontName("simsun");
        font.setFontHeightInPoints((short) 10);
        font.setColor(IndexedColors.BLACK.index);
        WriteCellStyle cellStyle = new WriteCellStyle();
        cellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setWriteFont(font);
        cellStyle.setWrapped(false);
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        return cellStyle;
    }


    /**
     * 生成Excel文件的方法write
     */
    public void write(String fileName, List<Object> tableHeaders, List<List<Object>> rows) throws IOException {
        // 初始一个workbook
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        // 创建单个sheet
        SXSSFSheet sheet = workbook.createSheet("sheet1");
        // 创建第一行，设置列名
        SXSSFRow row0 = sheet.createRow(0);
        row0.setHeight((short) 400);             // 设置行高         // Excel的列

        short cellNumber = (short) tableHeaders.size();  // 表的列数
        //限制最多1000列
        cellNumber = cellNumber > 1000 ? 1000 : cellNumber;
        for (int k = 0; k < cellNumber; k++) {
            short b = 5000;
            SXSSFCell cell = row0.createCell(k);          // 创建第0行第k列
            cell.setCellValue((String) tableHeaders.get(k));  // 设置第0行第k列的值
            sheet.setColumnWidth(k, b);         // 设置列的宽度
        }
        if (rows.size() > 0) {
            // 创建剩余行
            for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
                SXSSFRow row = sheet.createRow(rowIndex + 1);
                List<Object> values = rows.get(rowIndex);
                // 创建多列
                for (int cellIndex = 0; cellIndex < values.size(); cellIndex++) {
                    if (cellIndex > 1000) {
                        continue;
                    }
                    SXSSFCell cell = row.createCell(cellIndex);
                    cell.setCellValue((String) values.get(cellIndex));
                }
            }
        }
        ByteArrayOutputStream ba = new ByteArrayOutputStream();
        try {

            workbook.write(ba);
            ByteArrayInputStream bio = new ByteArrayInputStream(ba.toByteArray());
            ossUtil.uploadFile(fileName, bio);
            bio.close();
        } finally {
            workbook.close();
            ba.flush();
            ba.close();
        }
    }

    //
//
//    /**
//     * 设备条码生成Excel文件的方法write
//     */
    public void writeExcel(String fileName, List<Object> tableHeaders, List<List<Object>> rows) throws IOException {
        // 初始一个workbook
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建单个sheet
        XSSFSheet sheet = workbook.createSheet("sheet1");
        // 创建第一行，设置列名
        XSSFRow row0 = sheet.createRow(0);
        row0.setHeight((short) 400);             // 设置行高         // Excel的列
        XSSFFont font = workbook.createFont();// 设置字体
        font.setColor(HSSFFont.COLOR_NORMAL);           // 设置单元格字体的颜色
        XSSFCellStyle style = workbook.createCellStyle();// 样式
        // 设置边框颜色
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        // 设置文本格式
        XSSFDataFormat format = workbook.createDataFormat();
        style.setDataFormat(format.getFormat("@"));

        short cellNumber = (short) tableHeaders.size();  // 表的列数
        for (int k = 0; k < cellNumber; k++) {
            short b = 5000;
            XSSFCell cell = row0.createCell(k);          // 创建第0行第k列
            cell.setCellValue((String) tableHeaders.get(k));  // 设置第0行第k列的值
            sheet.setColumnWidth(k, b);         // 设置列的宽度
            style.setFont(font);                // 设置字体风格
            cell.setCellStyle(style);
        }

        XSSFCellStyle styleContext = workbook.createCellStyle();
        styleContext.setWrapText(true);
        // 设置边框颜色
        styleContext.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        styleContext.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        styleContext.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        styleContext.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        // 设置文本格式
        styleContext.setDataFormat(format.getFormat("@"));

        if (rows.size() > 0) {
            // 创建剩余行
            for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
                XSSFRow row = sheet.createRow(rowIndex + 1);
                List<Object> values = rows.get(rowIndex);
                // 创建多列
                for (int cellIndex = 0; cellIndex < values.size(); cellIndex++) {
                    XSSFCell cell = row.createCell(cellIndex);
                    cell.setCellStyle(styleContext);               // 设置风格
                    cell.setCellValue(values.get(cellIndex).toString());
                }
            }
        }
        ByteArrayOutputStream ba = new ByteArrayOutputStream();
        try {

            workbook.write(ba);
            ByteArrayInputStream bio = new ByteArrayInputStream(ba.toByteArray());
            ossUtil.uploadFile(fileName, bio);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ba.flush();
            ba.close();
        }
    }

}
