package com.jjt.biz.controller;

import com.jjt.calc.domain.TwinCalcDay;
import com.jjt.calc.service.ITwinCalcDayService;
import com.jjt.common.core.controller.BaseController;
import com.jjt.common.core.domain.R;
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.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.time.LocalDate;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * Excel导出控制类
 *
 * @author ruoyi
 */
@Api(tags = "数据导出接口--产量")
@RestController
@Slf4j
public class ApiProdExportController extends BaseController {
    @Resource
    private ITwinCalcDayService twinCalcDayService;

    @ApiOperation("导出产量数据")
    @RequestMapping("/api/export/production")
    @CrossOrigin(origins = "*")
    public void productionExport(String start, String end, HttpServletResponse response) {
        LocalDate localDate = LocalDate.parse(start);
        Date sd = Date.from(localDate.atStartOfDay(ZoneOffset.of("+8")).toInstant());
        localDate = LocalDate.parse(end);
        Date ed = Date.from(localDate.atStartOfDay(ZoneOffset.of("+8")).toInstant());
        List<TwinCalcDay> list = twinCalcDayService.selectTwinCalcDayListByTime(sd, ed);
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("tpl/total.xlsx"); Workbook wb = new XSSFWorkbook(inputStream); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            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"));

            Map<Date, List<TwinCalcDay>> dayGroup = list.stream().collect(Collectors.groupingBy(TwinCalcDay::getTime, LinkedHashMap::new, Collectors.toList()));
            for (Map.Entry<Date, List<TwinCalcDay>> entry : dayGroup.entrySet()) {
                Sheet sheet = wb.cloneSheet(0);
                wb.setSheetName(wb.getSheetIndex(sheet), DateUtils.parseDateToStr("yyyy-MM-dd", entry.getKey()));
                List<TwinCalcDay> days = entry.getValue();
                days.sort(Comparator.comparing(TwinCalcDay::getDeviceId));
                AtomicInteger rowNum = new AtomicInteger(2);
                days.forEach(day -> {
                    Row row = sheet.createRow(rowNum.get());
                    Cell[] cells = new Cell[25];
                    for (int i = 0; i < cells.length; i++) {
                        cells[i] = row.createCell(i);
                    }
                    day.setCells(cells);
                    rowNum.getAndIncrement();
                });
            }

            wb.removeSheetAt(0);
            // 清空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("最近7天产量统计" + DateUtils.dateTimeNow() + ".xlsx", "UTF-8"));
            response.setContentType("application/octet-stream");
            wb.write(outputStream);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @ApiOperation("导出产量数据")
    @RequestMapping("/api/view/production")
    @CrossOrigin(origins = "*")
    public R<List<TwinCalcDay>> productionView(String start) {
        LocalDate localDate = LocalDate.parse(start);
        Date sd = Date.from(localDate.atStartOfDay(ZoneOffset.of("+8")).toInstant());
        List<TwinCalcDay> list = twinCalcDayService.selectTwinCalcDayListByTime(sd, sd);
        return R.success(list);
    }

}
