package com.qmth.jkserver.controller.system;

import com.qmth.jkserver.common.Constants;
import com.qmth.jkserver.constant.SystemConstant;
import com.qmth.jkserver.core.exception.JkServerException;
import com.qmth.jkserver.dto.ExamStudenDetailDto;
import com.qmth.jkserver.dto.ExamStudenDetailDtoSorter;
import com.qmth.jkserver.dto.ExamStudentCountDto;
import com.qmth.jkserver.model.ExamAbort;
import com.qmth.jkserver.model.SysConfig;
import com.qmth.jkserver.service.CommonCacheService;
import com.qmth.jkserver.service.ExamKwHZService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.CellStyle;
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.XSSFWorkbook;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 查询统计(考务汇总)
 *
 * @author tianjun
 */
@Controller
@RequestMapping("/system/kwhz")
public class ExamKwHZController {

    @Resource
    @Lazy
    ExamKwHZService examKwHZService;

    @Resource
    CommonCacheService commonCacheService;

    //考务汇总情况整体统计
    @ResponseBody
    @RequestMapping(value = "/normal_utest/countStuats", method = RequestMethod.POST)
    public Object countStudtentStuats(String examCode, @RequestParam(required = false) String batchId,
                                      @RequestParam(required = false) String placeCode, @RequestParam(required = false) String placeName,
                                      @RequestParam(required = false) String roomCode, @RequestParam(required = false) Integer pageNo,
                                      @RequestParam(required = false) Integer pageSize) {
        if (StringUtils.isEmpty(examCode)) {
            throw JkServerException.withFieldValidateError("请选择一个考试计划");
        }
        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page<ExamStudentCountDto> examStudentCountDtos = examKwHZService.statisticKwHZDetails(examCode, batchId, placeCode,
                placeName, roomCode, pageNo, pageSize);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("list", examStudentCountDtos);
        result.put("total", examKwHZService.statisticKwHZ(examCode, batchId, placeCode, placeName, roomCode));
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/details", method = RequestMethod.POST)
    public Object getStudtentDetails(String examCode, String condition, @RequestParam(required = false) String batchId,
                                     @RequestParam(required = false) String placeCode, @RequestParam(required = false) String placeName,
                                     @RequestParam(required = false) String roomCode, @RequestParam(required = false) Integer pageNo,
                                     @RequestParam(required = false) Integer pageSize) {
        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        return examKwHZService.queryKwHZDetails(examCode, batchId, placeCode, placeName, roomCode, condition, pageNo,
                pageSize);
    }

    // 导出考务汇总数据
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, String examCode)
            throws IOException {
        // 读取模板
        ClassPathResource cp = new ClassPathResource("/tpl/kw_hz_tpl.xlsx");
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(cp.getInputStream());
        SXSSFWorkbook workbook = new SXSSFWorkbook(xssfWorkbook, 20);
        // 汇总情况整体
        List<ExamStudentCountDto> allSituations = examKwHZService.exportStatisticKwHZ(examCode);
        SXSSFSheet sheet0 = (SXSSFSheet) workbook.getSheetAt(0);
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
        int indexa = 2;
        int full = 0;
        int real = 0;
        int absent = 0;
        for (int i = 0; i < allSituations.size(); i++) {
            ExamStudentCountDto dto = allSituations.get(i);
            int cellIndex = -1;
            sheet0.getRow(0);
            sheet0.getPhysicalNumberOfRows();
            SXSSFRow row = sheet0.createRow(indexa);
            SXSSFCell cell0 = row.createCell(++cellIndex);
            cell0.setCellStyle(cellStyle);
            cell0.setCellValue(dto.getBatchName());
            SXSSFCell cell1 = row.createCell(++cellIndex);
            cell1.setCellValue(dto.getStageId());
            cell1.setCellStyle(cellStyle);
            SXSSFCell cell2 = row.createCell(++cellIndex);
            cell2.setCellStyle(cellStyle);
            cell2.setCellValue(String.valueOf(dto.getFullStudentNum()));
            SXSSFCell cell3 = row.createCell(++cellIndex);
            cell3.setCellValue(String.valueOf(dto.getRealityStudentNum()));
            cell3.setCellStyle(cellStyle);
            SXSSFCell cell4 = row.createCell(++cellIndex);
            cell4.setCellValue(String.valueOf(dto.getAbsentStudentNum()));
            cell4.setCellStyle(cellStyle);
            full += dto.getFullStudentNum();
            real += dto.getRealityStudentNum();
            absent += dto.getAbsentStudentNum();
            indexa++;
        }
        SXSSFRow row = sheet0.createRow(indexa);
        SXSSFCell cell0 = row.createCell(0);
        cell0.setCellValue("共计：");
        SXSSFCell cell2 = row.createCell(2);
        cell2.setCellValue(String.valueOf(full));
        SXSSFCell cell3 = row.createCell(3);
        cell3.setCellValue(String.valueOf(real));
        SXSSFCell cell4 = row.createCell(4);
        cell4.setCellValue(String.valueOf(absent));
        Map<String, List<ExamStudenDetailDto>> details = examKwHZService.exportKwHzDetails(examCode);
        // 缺考名单
        SXSSFSheet sheet1 = (SXSSFSheet) workbook.getSheetAt(1);
        int indexb = 2;
        List<ExamStudenDetailDto> list = details.get("isAbsent");
        Collections.sort(list, new ExamStudenDetailDtoSorter());
        for (ExamStudenDetailDto examStudenDetailDto : list) {
            int cellIndex = -1;
            SXSSFRow myrow = sheet1.createRow(indexb);
            SXSSFCell mycell0 = myrow.createCell(++cellIndex);
            mycell0.setCellStyle(cellStyle);
            mycell0.setCellValue(examStudenDetailDto.getBatchName());
            SXSSFCell mycell1 = myrow.createCell(++cellIndex);
            mycell1.setCellStyle(cellStyle);
            mycell1.setCellValue(String.valueOf(examStudenDetailDto.getStageId()));
            SXSSFCell mycell2 = myrow.createCell(++cellIndex);
            mycell2.setCellStyle(cellStyle);
            mycell2.setCellValue(String.valueOf(examStudenDetailDto.getTicketNo()));
            SXSSFCell mycell3 = myrow.createCell(++cellIndex);
            mycell3.setCellStyle(cellStyle);
            mycell3.setCellValue(String.valueOf(examStudenDetailDto.getName()));
            SXSSFCell mycell4 = myrow.createCell(++cellIndex);
            mycell4.setCellStyle(cellStyle);
            mycell4.setCellValue(examStudenDetailDto.getCourseName() + "(" + examStudenDetailDto.getCourseCode() + ")");
            indexb++;
        }
        // 异常处理名单
        SXSSFSheet sheet2 = (SXSSFSheet) workbook.getSheetAt(2);
        int indexc = 2;
        list = details.get("isAbort");
        Collections.sort(list, new ExamStudenDetailDtoSorter());
        for (ExamStudenDetailDto examStudenDetailDto : list) {
            if (examStudenDetailDto.getAborts() == null || examStudenDetailDto.getAborts().size() == 0) {
                continue;
            }
            for (ExamAbort examAbort : examStudenDetailDto.getAborts()) {
                int cellIndex = -1;
                SXSSFRow myrow = sheet2.createRow(indexc);
                SXSSFCell mycell0 = myrow.createCell(++cellIndex);
                mycell0.setCellStyle(cellStyle);
                mycell0.setCellValue(examStudenDetailDto.getBatchName());
                SXSSFCell mycell1 = myrow.createCell(++cellIndex);
                mycell1.setCellStyle(cellStyle);
                mycell1.setCellValue(String.valueOf(examStudenDetailDto.getStageId()));
                SXSSFCell mycell2 = myrow.createCell(++cellIndex);
                mycell2.setCellStyle(cellStyle);
                mycell2.setCellValue(String.valueOf(examStudenDetailDto.getTicketNo()));
                SXSSFCell mycell3 = myrow.createCell(++cellIndex);
                mycell3.setCellStyle(cellStyle);
                mycell3.setCellValue(String.valueOf(examStudenDetailDto.getName()));
                SXSSFCell mycell4 = myrow.createCell(++cellIndex);
                mycell4.setCellStyle(cellStyle);
                mycell4.setCellValue(
                        examStudenDetailDto.getCourseName() + "(" + examStudenDetailDto.getCourseCode() + ")");
                SXSSFCell mycell5 = myrow.createCell(++cellIndex);
                mycell5.setCellStyle(cellStyle);
                mycell5.setCellValue(examAbort.getTime());
                SXSSFCell mycell6 = myrow.createCell(++cellIndex);
                mycell6.setCellStyle(cellStyle);
                mycell6.setCellValue(examAbort.getReason());
                SXSSFCell mycell7 = myrow.createCell(++cellIndex);
                mycell7.setCellStyle(cellStyle);
                mycell7.setCellValue(examAbort.getRemark());
                indexc++;
            }
        }
        // 重考处理名单
        SXSSFSheet sheet3 = (SXSSFSheet) workbook.getSheetAt(3);
        int indexd = 2;
        list = details.get("isRepeat");
        Collections.sort(list, new ExamStudenDetailDtoSorter());
        for (ExamStudenDetailDto examStudenDetailDto : list) {
            int cellIndex = -1;
            SXSSFRow myrow = sheet3.createRow(indexd);
            SXSSFCell mycell0 = myrow.createCell(++cellIndex);
            mycell0.setCellStyle(cellStyle);
            mycell0.setCellValue(examStudenDetailDto.getBatchName());
            SXSSFCell mycell1 = myrow.createCell(++cellIndex);
            mycell1.setCellStyle(cellStyle);
            mycell1.setCellValue(String.valueOf(examStudenDetailDto.getStageId()));
            SXSSFCell mycell2 = myrow.createCell(++cellIndex);
            mycell2.setCellStyle(cellStyle);
            mycell2.setCellValue(String.valueOf(examStudenDetailDto.getTicketNo()));
            SXSSFCell mycell3 = myrow.createCell(++cellIndex);
            mycell3.setCellStyle(cellStyle);
            mycell3.setCellValue(String.valueOf(examStudenDetailDto.getName()));
            SXSSFCell mycell4 = myrow.createCell(++cellIndex);
            mycell4.setCellStyle(cellStyle);
            mycell4.setCellValue(examStudenDetailDto.getCourseName() + "(" + examStudenDetailDto.getCourseCode() + ")");
            SXSSFCell mycell5 = myrow.createCell(++cellIndex);
            mycell5.setCellStyle(cellStyle);
            mycell5.setCellValue(examStudenDetailDto.getTime());
            SXSSFCell mycell6 = myrow.createCell(++cellIndex);
            mycell6.setCellStyle(cellStyle);
            mycell6.setCellValue(examStudenDetailDto.getNewBatchName());
            SXSSFCell mycell7 = myrow.createCell(++cellIndex);
            mycell7.setCellStyle(cellStyle);
            mycell7.setCellValue(examStudenDetailDto.getNewStageId());
            SXSSFCell mycell8 = myrow.createCell(++cellIndex);
            mycell8.setCellStyle(cellStyle);
            mycell8.setCellValue(examStudenDetailDto.getRemark());
            indexd++;
        }
        SXSSFSheet sheet4 = (SXSSFSheet) workbook.getSheetAt(4);
        int indexe = 2;
        list = details.get("isCheat");
        Collections.sort(list, new ExamStudenDetailDtoSorter());
        for (ExamStudenDetailDto examStudenDetailDto : list) {
            int cellIndex = -1;
            SXSSFRow myrow = sheet4.createRow(indexe);
            SXSSFCell mycell0 = myrow.createCell(++cellIndex);
            mycell0.setCellStyle(cellStyle);
            mycell0.setCellValue(examStudenDetailDto.getBatchName());
            SXSSFCell mycell1 = myrow.createCell(++cellIndex);
            mycell1.setCellStyle(cellStyle);
            mycell1.setCellValue(String.valueOf(examStudenDetailDto.getStageId()));
            SXSSFCell mycell2 = myrow.createCell(++cellIndex);
            mycell2.setCellStyle(cellStyle);
            mycell2.setCellValue(String.valueOf(examStudenDetailDto.getTicketNo()));
            SXSSFCell mycell3 = myrow.createCell(++cellIndex);
            mycell3.setCellStyle(cellStyle);
            mycell3.setCellValue(String.valueOf(examStudenDetailDto.getName()));
            SXSSFCell mycell4 = myrow.createCell(++cellIndex);
            mycell4.setCellStyle(cellStyle);
            mycell4.setCellValue(examStudenDetailDto.getCourseName() + "(" + examStudenDetailDto.getCourseCode() + ")");
            SXSSFCell mycell5 = myrow.createCell(++cellIndex);
            mycell5.setCellStyle(cellStyle);
            mycell5.setCellValue(examStudenDetailDto.getExamCheat().getOperateType());
            SXSSFCell mycell6 = myrow.createCell(++cellIndex);
            mycell6.setCellStyle(cellStyle);
            mycell6.setCellValue(examStudenDetailDto.getExamCheat().getOperateTime());
            SXSSFCell mycell7 = myrow.createCell(++cellIndex);
            mycell7.setCellStyle(cellStyle);
            mycell7.setCellValue(examStudenDetailDto.getExamCheat().getReason());
            SXSSFCell mycell8 = myrow.createCell(++cellIndex);
            mycell8.setCellStyle(cellStyle);
            mycell8.setCellValue(examStudenDetailDto.getExamCheat().getIntroduce());
            indexe++;
        }
//        SysConfig sysConfig = commonCacheService.addSysConfigCache(SystemConstant.SYS_CONFIG_KEY_CHARSETS);
        response.setCharacterEncoding(SystemConstant.CHARSET_NAME);
        response.setContentType("multipart/form-data");
        String fileName = "考务汇总_" + new SimpleDateFormat("yyyy_MM_ddHHmmss").format(new Date()) + ".xlsx";
        fileName = URLEncoder.encode(fileName, SystemConstant.CHARSET_NAME);
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        IOUtils.closeQuietly(os);
        workbook.close();
    }
}
