package com.yizhi.application.report.exam;

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.util.WmyDateUtils;
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.ExamClient;
import com.yizhi.exam.application.feign.ExamReportClient;
import com.yizhi.exam.application.vo.ExamCountByUserVO;
import com.yizhi.exam.application.vo.report.ReportExamAccountsViewVo;
import com.yizhi.point.application.feign.PointUserFeignClients;
import com.yizhi.statistics.application.feign.StatisticsExamClient;
import com.yizhi.statistics.application.refactor.exam.StatisticsExamVO;
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/13 14:13
 * @Description:
 */
@Component
public class ExamAccountTrExamsExport extends AbstractDefaultTask<String, Map<String, Object>> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExamAccountTrExamsExport.class);

    @Autowired
    ExamReportClient examReportClient;

    @Autowired
    PointUserFeignClients pointUserFeignClients;

    @Autowired
    ExamClient examClient;

    @Autowired
    StatisticsExamClient statisticsExamClient;

    @Override
    protected String execute(Map<String, Object> map) {
        // TODO 友邦数据修改 下载考试明细数据 2
        String uploadUrl = null;
        ExamCountByUserVO vo = (ExamCountByUserVO) map.get("vo");
        Long examId = vo.getExamId();
        String startTime = vo.getStartTime();
        Integer pageNo = 1;
        Integer pageSize = 30;
        vo.setPageNo(pageNo);
        vo.setPageSize(pageSize);

        Long accountId = (Long) map.get("accountId");
        Long siteId = (Long) map.get("siteId");
        Long companyId = (Long) map.get("companyId");

        Date comitTime = new Date();
        Long taskId = (Long) map.get("taskId");
        String serialNo = (String) map.get("serialNo");
        String taskName = (String) map.get("taskName");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
        TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, accountId, comitTime, siteId, companyId);
        working(taskContext);


        try {
            StatisticsExamVO exam = statisticsExamClient.getExam(examId);

            Page<ReportExamAccountsViewVo> page = examReportClient.getExamAndAccountGroup(vo);
            List<ReportExamAccountsViewVo> list = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //分页查询
            if (page != null) {
                list.addAll(page.getRecords());
            }
            Integer total = page.getTotal();
            if (total > pageSize) {
                Integer pageCount = total / pageSize;
                if (pageCount.equals(1)) {
                    vo.setPageNo(2);
                    page = examReportClient.getExamAndAccountGroup(vo);
                    list.addAll(page.getRecords());
                } else {
                    for (int i = 2; i <= pageCount; i++) {
                        vo.setPageNo(i);
                        page = examReportClient.getExamAndAccountGroup(vo);
                        list.addAll(page.getRecords());
                    }
                    if ((pageCount * pageSize) < total) {
                        vo.setPageNo(pageCount + 1);
                        page = examReportClient.getExamAndAccountGroup(vo);
                        list.addAll(page.getRecords());
                    }
                }
            }

            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet(exam.getExamName() + "下载考试结果数据");
            HSSFRow row = sheet.createRow(0);

            CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 8);
            sheet.addMergedRegion(cra);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue(exam.getExamName() + "下载考试结果数据");

            row = sheet.createRow(1);
            cra = new CellRangeAddress(1, 1, 0, 8);
            sheet.addMergedRegion(cra);
            cell = row.createCell(0);
            cell.setCellValue("统计周期:" + vo.getStartTime() + "~" + vo.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("考试结果");
            row2.createCell(8).setCellValue("获得积分");
            row2.createCell(9).setCellValue("用户状态");
            row2.createCell(10).setCellValue("所在部门");
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    ReportExamAccountsViewVo reportExamAccountsViewVo = list.get(i);
                    row = sheet.createRow(i + 3);
                    row.createCell(0).setCellValue(reportExamAccountsViewVo.getAccountName());
                    row.createCell(1).setCellValue(reportExamAccountsViewVo.getAccountFullName());

                    if (reportExamAccountsViewVo.getFinishTime() != null) {
                        row.createCell(2).setCellValue(sdf.format(reportExamAccountsViewVo.getFinishTime()));
                    }

                    if (reportExamAccountsViewVo.getLastFinishTime() != null) {
                        row.createCell(3).setCellValue(sdf.format(reportExamAccountsViewVo.getLastFinishTime()));
                    }

                    row.createCell(4).setCellValue(reportExamAccountsViewVo.getExamCount());
                    row.createCell(5).setCellValue(WmyDateUtils.durationFormart(String.valueOf(reportExamAccountsViewVo.getDuration())));
                    if (reportExamAccountsViewVo.getScore() != null) {
                        row.createCell(6).setCellValue(reportExamAccountsViewVo.getScore().doubleValue());
                    }
                    if (reportExamAccountsViewVo.getExamState() == 1) {
                        row.createCell(7).setCellValue("通过");
                    } else if (reportExamAccountsViewVo.getExamState() == 0) {
                        row.createCell(7).setCellValue("不通过");
                    } else {
                        row.createCell(7).setCellValue("--");
                    }
                    row.createCell(8).setCellValue(reportExamAccountsViewVo.getPoint());

                    if (reportExamAccountsViewVo.getAccountState() != null) {
                        if (reportExamAccountsViewVo.getAccountState() == 1) {
                            row.createCell(9).setCellValue("启用");
                        } else {
                            row.createCell(9).setCellValue("停用");
                        }
                    }
                    row.createCell(10).setCellValue(reportExamAccountsViewVo.getOrgName());
                }
            }


            String fileName = exam.getExamName() + "考试结果" + sdf2.format(comitTime) + ".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);
                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;
    }
}
