package com.jjt.biz.controller;

import com.jjt.biz.vo.FormulaDetail;
import com.jjt.biz.vo.GramMass;
import com.jjt.biz.vo.GramMassDetail;
import com.jjt.biz.vo.WarpRunIn;
import com.jjt.common.constant.CacheConstants;
import com.jjt.common.core.controller.BaseController;
import com.jjt.common.core.redis.RedisCache;
import com.jjt.common.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * Excel导出控制类
 *
 * @author ruoyi
 */
@Api(tags = "数据导出接口--实时")
@RestController
@Slf4j
public class ApiExportController extends BaseController {
    @Resource
    private RedisCache redisCache;

    @ApiOperation("送经量")
    @RequestMapping("/api/export/warp-run-in")
    @CrossOrigin(origins = "*")
    public void warpRunInExport(HttpServletResponse response) {
        List<WarpRunIn> list = redisCache.getCacheObject(CacheConstants.INDEX_WARP_RUN_IN);
        try (Workbook wb = new XSSFWorkbook(); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            Sheet sheet = wb.createSheet("送经量明细");
            sheet.setDefaultColumnWidth(15);
            CellStyle style = wb.createCellStyle();
            style.setDataFormat(wb.createDataFormat().getFormat("0.00"));
            Row titleRow = sheet.createRow(0);
            Cell titleCell = titleRow.createCell(0);
            titleCell.setCellValue("设备名");
            titleCell = titleRow.createCell(1);
            titleCell.setCellValue("L1梳栉送经量");
            titleCell = titleRow.createCell(2);
            titleCell.setCellValue("L2梳栉送经量");
            titleCell = titleRow.createCell(3);
            titleCell.setCellValue("L3梳栉送经量");
            titleCell = titleRow.createCell(4);
            titleCell.setCellValue("L4梳栉送经量");
            titleCell = titleRow.createCell(5);
            titleCell.setCellValue("L5梳栉送经量");
            titleCell = titleRow.createCell(6);
            titleCell.setCellValue("牵拉密度");
            titleCell = titleRow.createCell(7);
            titleCell.setCellValue("卷曲张力系数");
            AtomicInteger rowNum = new AtomicInteger(1);
            list.forEach(warp -> {
                Row row = sheet.createRow(rowNum.get());
                Cell[] cells = new Cell[8];
                for (int i = 0; i < cells.length; i++) {
                    cells[i] = row.createCell(i);
                }
                warp.setCells(cells, style);
                rowNum.getAndIncrement();
            });

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("送经量明细导出" + DateUtils.dateTimeNow() + ".xlsx", "UTF-8"));
            response.setContentType("application/octet-stream");
            wb.write(outputStream);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @ApiOperation("平方米克重导出")
    @RequestMapping("/api/export/gram-mass")
    @CrossOrigin(origins = "*")
    public void gramMassExport(HttpServletResponse response) {
        List<GramMass> list = redisCache.getCacheObject(CacheConstants.INDEX_GRAM_MASS);
        List<GramMassDetail> details = redisCache.getCacheObject(CacheConstants.INDEX_GRAM_MASS_DETAIL);
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("tpl/gram.xlsx"); Workbook wb = new XSSFWorkbook(inputStream); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            Sheet sheet = wb.getSheetAt(0);

            CreationHelper creationHelper = wb.getCreationHelper();
            CellStyle percentStyle = wb.createCellStyle();
            percentStyle.setDataFormat(creationHelper.createDataFormat().getFormat("0.00%"));
            CellStyle p2 = wb.createCellStyle();
            p2.setDataFormat(wb.createDataFormat().getFormat("0.00"));
            AtomicInteger rowNum = new AtomicInteger(1);
            list.forEach(gram -> {
                Row row = sheet.createRow(rowNum.get());
                Cell[] cells = new Cell[3];
                for (int i = 0; i < cells.length; i++) {
                    cells[i] = row.createCell(i);
                }
                cells[0].setCellValue(gram.getGramMass());
                cells[0].setCellStyle(p2);
                cells[1].setCellValue(gram.getNum());
                cells[2].setCellValue(gram.getPercent());
                cells[2].setCellStyle(percentStyle);
                rowNum.getAndIncrement();
                Sheet ns = wb.cloneSheet(1);
                wb.setSheetName(wb.getSheetIndex(ns), gram.getGramMass() + "克明细");
                AtomicInteger detailRowNum = new AtomicInteger(2);
                details.stream().filter(d -> d.getGramMass().equals(gram.getGramMass())).forEach(d -> {
                    Row dRow = ns.createRow(detailRowNum.get());
                    Cell[] dCells = new Cell[24];
                    for (int i = 0; i < dCells.length; i++) {
                        dCells[i] = dRow.createCell(i);
                    }
                    dCells[2].setCellStyle(p2);
                    d.setCells(dCells);
                    detailRowNum.getAndIncrement();
                });
            });
            wb.removeSheetAt(1);
            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("平方米克重明细导出" + DateUtils.dateTimeNow() + ".xlsx", "UTF-8"));
            response.setContentType("application/octet-stream");
            wb.write(outputStream);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @ApiOperation("配方详情导出")
    @RequestMapping("/api/formula/export/{height}")
    @CrossOrigin(origins = "*")
    public void formulaExport(@PathVariable Float height, HttpServletResponse response) {
        List<FormulaDetail> list = redisCache.getCacheObject(CacheConstants.INDEX_FORMULA_DETAIL);
        list = list.stream().filter(detail -> detail.getFormula_data_15().equals(height)).collect(Collectors.toList());
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("tpl/formula.xlsx"); Workbook wb = new XSSFWorkbook(inputStream); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            AtomicInteger rowNum = new AtomicInteger(2);

            list.forEach(detail -> {
                Row row = sheet.createRow(rowNum.get());
                Cell[] cells = new Cell[26];
                for (int i = 0; i < cells.length; i++) {
                    cells[i] = row.createCell(i);
                }
                detail.setCells(cells);
                rowNum.getAndIncrement();
            });

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("毛高" + height + "设备明细导出" + DateUtils.dateTimeNow() + ".xlsx", "UTF-8"));
            response.setContentType("application/octet-stream");
            wb.write(outputStream);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
