package com.yizhi.application.report.exam;

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.core.application.context.TaskContext;
import com.yizhi.core.application.file.constant.FileConstant;
import com.yizhi.core.application.file.task.AbstractDefaultTask;
import com.yizhi.core.application.file.util.OssUpload;
import com.yizhi.exam.application.feign.ExamReportClient;
import com.yizhi.exam.application.vo.report.ReportExamParam;
import com.yizhi.exam.application.vo.report.ReportExamVO;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Auther: dingxiaowei
 * @Date: 2018/8/10 09:36
 * @Description:按考试统计报表导出excel
 */
@Component
public class ExamGroupExport extends AbstractDefaultTask<String, Map<String, Object>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExamGroupExport.class);

    @Autowired
    ExamReportClient examReportClient;

    @Override
    protected String execute(Map<String, Object> map) {
        String uploadUrl = null;

        ReportExamParam reportExamParam = (ReportExamParam) map.get("reportExamParam");
        Long accountId = (Long) map.get("accountId");
        Long siteId = reportExamParam.getSiteId();
        Long companyId = reportExamParam.getCompanyId();

        Date submitTime = new Date();
        Long taskId = (Long) map.get("taskId");
        String serialNo = (String) map.get("serialNo");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String taskName = (String) map.get("taskName");
        TaskContext taskContext = new TaskContext(taskId, serialNo, taskName,
                accountId, submitTime, siteId, companyId);
        working(taskContext);

        Integer pageNo = 1;
        Integer pageSize = 30;
        reportExamParam.setPageNo(pageNo);
        reportExamParam.setPageSize(pageSize);
        Page<ReportExamVO> page = examReportClient.getExamGroup(reportExamParam);
        List<ReportExamVO> list = new ArrayList<>();
        //分页查询大幅度减少中台请求时间
        if (page != null) {
            list.addAll(page.getRecords());
        }
        Integer total = page.getTotal();
        if (total > pageSize) {
            Integer pageCount = total / pageSize;
            if (pageCount.equals(1)) {
                reportExamParam.setPageNo(2);
                page = examReportClient.getExamGroup(reportExamParam);
                list.addAll(page.getRecords());
            } else {
                for (int i = 2; i <= pageCount; i++) {
                    reportExamParam.setPageNo(i);
                    page = examReportClient.getExamGroup(reportExamParam);
                    list.addAll(page.getRecords());
                }
                if ((pageSize * pageCount) < total) {
                    reportExamParam.setPageNo(pageCount + 1);
                    page = examReportClient.getExamGroup(reportExamParam);
                    list.addAll(page.getRecords());
                }
            }
        }


        try {
            HSSFWorkbook wb = new HSSFWorkbook();//创建excel文件
            HSSFSheet sheet = wb.createSheet("按考试统计报表");//创建报表页
            HSSFRow row = sheet.createRow(0);//创建表头

//            HSSFCellStyle style = wb.createCellStyle();
//            style.setAlignment(HorizontalAlignment.CENTER);

            CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 6);
            sheet.addMergedRegion(cra);//表头合并单元格
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("按考试统计报表");//填写表头名
//            cell.setCellStyle(style);//表头居中

            row = sheet.createRow(1);
            CellRangeAddress cra2 = new CellRangeAddress(1, 1, 0, 6);
            sheet.addMergedRegion(cra2);
            cell = row.createCell(0);
            cell.setCellValue("统计周期:" + reportExamParam.getStartTime()
                    + "~" + reportExamParam.getEndTime());

            HSSFRow row2 = sheet.createRow(2);//创建 列名行
            row2.createCell(0).setCellValue("考试名称");
            row2.createCell(1).setCellValue("考试时间");
            row2.createCell(2).setCellValue("可参加人数");
            row2.createCell(3).setCellValue("实际参加人数");
            row2.createCell(4).setCellValue("通过人数");
            row2.createCell(5).setCellValue("通过率");
            row2.createCell(6).setCellValue("平均分");
            row2.createCell(7).setCellValue("完成率");

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    ReportExamVO reportExamVO = list.get(i);
                    row = sheet.createRow(i + 3);
                    row.createCell(0).setCellValue(reportExamVO.getName());
                    String examTime = sdf.format(reportExamVO.getStartTime()) + " " + sdf.format(reportExamVO.getEndTime());
                    row.createCell(1).setCellValue(examTime);
                    row.createCell(2).setCellValue(reportExamVO.getTotalAsk());
                    row.createCell(3).setCellValue(reportExamVO.getTotalIn());
                    row.createCell(4).setCellValue(reportExamVO.getTotalPass());
                    row.createCell(5).setCellValue(reportExamVO.getPassRate() + "%");
                    row.createCell(6).setCellValue(reportExamVO.getAvgScore().doubleValue());
                    if (reportExamVO.getComplete() != null) {
                        row.createCell(7).setCellValue(reportExamVO.getComplete() + "%");
                    } else {
                        row.createCell(7).setCellValue("0.00%");
                    }
                }
            }

            String fileName = "按考试统计报表" + sdf2.format(submitTime) + ".xls";
//            String requestPath = "/Users/dingxiaowei/aaa";
            String requestPath = FileConstant.SAVE_PATH;
            File fileDir = new File(requestPath);
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }

            String path = requestPath + "/" + fileName;
            FileOutputStream os = null;
            File file = null;
            try {
                os = new FileOutputStream(path);
                wb.write(os);
                uploadUrl = OssUpload.upload(path, fileName);//阿里云返回url
                file = new File(path);
                success(taskContext, "成功", uploadUrl);
            } catch (Exception e2) {
                e2.printStackTrace();
                fail(taskContext, "按考试统计写入过程中发生错误");
                LOGGER.error("按考试统计写入过程中发生错误");
            } finally {
                if (os != null) {
                    os.close();
                }
                if (wb != null) {
                    wb.close();
                }
                if (file != null) {
                    file.delete();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            fail(taskContext, "按考试统计报表下载发生错误");
            LOGGER.error("按考试统计报表下载发生错误，请查看日志");
        }

        return uploadUrl;
    }
}
