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.report.ReportExamAccountsViewVo;
import com.yizhi.statistics.application.feign.StatisticsExamClient;
import com.yizhi.statistics.application.refactor.exam.StatisticsExamVO;
import com.yizhi.system.application.system.remote.OrganizationClient;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
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 javax.management.StringValueExp;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: dingxiaowei
 * @Date: 2018/8/14 09:21
 * @Description: 按考试统计-查看 (按用户统计)下载考试明细
 */
@Component
public class ExamAccountTrExamsViewExport extends AbstractDefaultTask<String, Map<String, Object>> {

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

    @Autowired
    ExamReportClient examReportClient;

    @Autowired
    ExamClient examClient;

    @Autowired
    StatisticsExamClient statisticsExamClient;

    @Autowired
    OrganizationClient organizationClient;

    @Override
    protected String execute(Map<String, Object> map) {
        String uploadUrl = null;
        String accountNameLike = (String) map.get("accountNameLike");
        String orgNameLike = (String) map.get("orgNameLike");
        Long examId = (Long) map.get("examId");
        String startTime = (String) map.get("startTime");
        String endTime = (String) map.get("endTime");
        Integer pageNo = 1;
        Integer pageSize = 1000;
        Long accountId = (Long) map.get("accountId");
        Long siteId = (Long) map.get("siteId");
        Long companyId = (Long) map.get("companyId");
        boolean isAdmin = (boolean) map.get("isAdmin");
        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);


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

            Page<ReportExamAccountsViewVo> page =
                    examReportClient.getExamAndAccountGroupView(examId, siteId, accountId, isAdmin, accountNameLike,
                            orgNameLike, startTime, endTime, pageNo, pageSize);
            List<ReportExamAccountsViewVo> 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)) {
                    pageNo = 2;
                    page = examReportClient.getExamAndAccountGroupView(examId, siteId, accountId, isAdmin, accountNameLike,
                            orgNameLike, startTime, endTime, pageNo, pageSize);
                    list.addAll(page.getRecords());
                } else {
                    for (int i = 2; i <= pageCount; i++) {
                        pageNo = i;
                        page = examReportClient.getExamAndAccountGroupView(examId, siteId, accountId, isAdmin, accountNameLike,
                                orgNameLike, startTime, endTime, pageNo, pageSize);
                        list.addAll(page.getRecords());
                    }
                    if ((pageCount * pageSize) < total) {
                        pageNo = pageCount + 1;
                        page = examReportClient.getExamAndAccountGroupView(examId, siteId, accountId, isAdmin, accountNameLike,
                                orgNameLike, startTime, endTime, pageNo, pageSize);
                        list.addAll(page.getRecords());
                    }
                }
            }


            // 创建excel表
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("下载考试明细");
            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("统计周期:" + startTime + "~" + endTime);

            //列名行
            row = sheet.createRow(2);
            row.createCell(0).setCellValue("用户名");
            row.createCell(1).setCellValue("姓名");
            row.createCell(2).setCellValue("开始考试时间");
            row.createCell(3).setCellValue("交卷时间");
            row.createCell(4).setCellValue("考试分数");
            row.createCell(5).setCellValue("考试时长");
            row.createCell(6).setCellValue("考试结果 ");
            row.createCell(7).setCellValue("用户状态");
            row.createCell(8).setCellValue("所在部门");
            row.createCell(9).setCellValue("所在组织架构");

            Map<Long, String> orgNamesMap = new HashMap<>();
            //写入数据
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    ReportExamAccountsViewVo vo = list.get(i);
                    row = sheet.createRow(i + 3);
                    row.createCell(0).setCellValue(vo.getAccountName());
                    row.createCell(1).setCellValue(vo.getAccountFullName());
                    row.createCell(2).setCellValue(sdf.format(vo.getStartTime()));
                    Date finishTime = vo.getFinishTime();
                    if (finishTime != null) {
                        row.createCell(3).setCellValue(sdf.format(vo.getFinishTime()));
                    }
                    row.createCell(4).setCellValue(vo.getScore().doubleValue());
                    row.createCell(5).setCellValue(WmyDateUtils.durationFormart(String.valueOf(vo.getDuration())));

                    if (vo.getExamState() == 1) {
                        row.createCell(6).setCellValue("通过");
                    } else if (vo.getExamState() == 0) {
                        row.createCell(6).setCellValue("不通过");
                    } else if (vo.getExamState() == 2) {
                        row.createCell((6)).setCellValue("未阅卷");
                    } else {
                        row.createCell(6).setCellValue("--");
                    }
                    if (vo.getAccountState() != null) {
                        if (vo.getAccountState() == 1) {
                            row.createCell(7).setCellValue("启用");
                        } else {
                            row.createCell(7).setCellValue("停用");
                        }
                    }
                    row.createCell(8).setCellValue(vo.getOrgName());
                    if (orgNamesMap.get(vo.getOrgId()) != null) {
                        row.createCell(9).setCellValue(orgNamesMap.get(vo.getOrgId()));
                    } else {
                        String orgNames = "";
                        List<String> orgNameList = organizationClient.getChiefOrgNames(vo.getOrgId(), companyId);
                        if (CollectionUtils.isNotEmpty(orgNameList)) {
                            for (String s : orgNameList) {
                                if (StringUtils.isBlank(orgNames)) {
                                    orgNames = orgNames + s;
                                } else {
                                    orgNames = orgNames + "/" + s;
                                }
                            }
                            row.createCell(9).setCellValue(orgNames);
                            orgNamesMap.put(vo.getOrgId(), orgNames);
                        } else {
                            row.createCell(9).setCellValue("--");
                        }
                    }
                }
            }

            String fileName = exam.getExamName() + "考试明细" + 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);
                file = new File(path);
                uploadUrl = OssUpload.upload(path, fileName);
                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;
    }
}
