package com.qmth.themis.business.templete.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.reflect.TypeToken;
import com.qmth.themis.business.bean.admin.OpenRecordAnswerTempBean;
import com.qmth.themis.business.bean.admin.OpenRecordNeedMarkBean;
import com.qmth.themis.business.bean.cloudmark.*;
import com.qmth.themis.business.cache.bean.ExamCacheBean;
import com.qmth.themis.business.cache.bean.ExamPaperCacheBean;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dto.ExamStudentImportDto;
import com.qmth.themis.business.dto.RoomCodeImportDto;
import com.qmth.themis.business.entity.*;
import com.qmth.themis.business.enums.CloudMarkFileUploadTypeEnum;
import com.qmth.themis.business.enums.ExamModeEnum;
import com.qmth.themis.business.enums.RoleEnum;
import com.qmth.themis.business.enums.TaskStatusEnum;
import com.qmth.themis.business.forkjoin.ExamStudentImportForkJoin;
import com.qmth.themis.business.forkjoin.ForkJoinThreadPool;
import com.qmth.themis.business.service.*;
import com.qmth.themis.business.templete.service.TempleteLogicService;
import com.qmth.themis.business.util.CloudMarkUtil;
import com.qmth.themis.business.util.JacksonUtil;
import com.qmth.themis.business.util.OssUtil;
import com.qmth.themis.common.contanst.Constants;
import com.qmth.themis.common.enums.ExceptionResultEnum;
import com.qmth.themis.common.exception.BusinessException;
import com.qmth.themis.common.util.Base64Util;
import com.qmth.themis.common.util.GsonUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Description: 导入导出模版处理逻辑 impl
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/7/31
 */
@Service
public class TempleteLogicServiceImpl implements TempleteLogicService {
    private final static Logger log = LoggerFactory.getLogger(TempleteLogicServiceImpl.class);

    @Resource
    TEExamStudentService teExamStudentService;

    @Resource
    TBExamInvigilateUserService tbExamInvigilateUserService;

    @Resource
    TBUserService tbUserService;

    @Resource
    TEExamCourseService teExamCourseService;

    @Resource
    TBUserRoleService tbUserRoleService;

    @Resource
    TBExamInvigilateUserTempService tbExamInvigilateUserTempService;

    @Resource
    CloudMarkUtil cloudMarkUtil;

    @Resource
    TEExamService teExamService;

    @Resource
    TEExamPaperService teExamPaperService;

    @Resource
    ThemisCacheService themisCacheService;

    @Resource
    TOeExamRecordService tOeExamRecordService;

    @Resource
    TBTaskHistoryService tbTaskHistoryService;

    @Resource
    OssUtil ossUtil;

    @Resource
    TOeExamAnswerService examAnswerService;

    @Resource
    ForkJoinThreadPool forkJoinThreadPool;

    /**
     * 考生导入逻辑
     *
     * @param finalList
     * @param map
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> execImportExamStudentLogic(List<LinkedMultiValueMap<Integer, Object>> finalList, Map<String, Object> map) throws UnsupportedEncodingException {
        Long orgId = Long.parseLong(String.valueOf(map.get(SystemConstant.ORG_ID)));
        Long examId = Long.parseLong(String.valueOf(map.get(SystemConstant.EXAM_ID)));
        Long createId = Long.parseLong(String.valueOf(map.get(SystemConstant.CREATE_ID)));
        List<String> txtList = (List<String>) map.get("txtList");
        TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
        List<TBExamInvigilateUser> tbExamInvigilateUserList = new ArrayList<>();
        Set<String> roomCodeAndNameSet = new HashSet<>();
        Map<String, TEExamActivity> teExamActivityMap = (Map<String, TEExamActivity>) map.get("teExamActivityMap");
        Map<String, String> courseCodeMap = (Map<String, String>) map.get("courseCodeMap");
        QueryWrapper<TEExamCourse> teExamCourseQueryWrapper = new QueryWrapper<>();
        Set<String> courseCodeSet = courseCodeMap.keySet().stream().collect(Collectors.toSet());
        teExamCourseQueryWrapper.lambda().in(TEExamCourse::getCourseCode, courseCodeSet).eq(TEExamCourse::getExamId, examId);
        List<TEExamCourse> teExamCourseList = teExamCourseService.list(teExamCourseQueryWrapper);
        if (Objects.nonNull(teExamCourseList) && teExamCourseList.size() > 0) {
            teExamCourseList.forEach(s -> {
                courseCodeMap.remove(s.getCourseCode());
            });
        }
        List<TEExamCourse> teExamCourses = new ArrayList<>();
        courseCodeMap.forEach((k, v) -> {
            TEExamCourse teExamCourse = new TEExamCourse(examId, k, v, createId);
            teExamCourses.add(teExamCourse);
        });
        if (teExamCourses.size() > 0) {
            teExamCourseService.saveBatch(teExamCourses);
        }
        ExamModeEnum modeEnum = ExamModeEnum.valueOf(String.valueOf(map.get("mode")));

        int line = 0;
        //保存用户
        for (int i = 0; i < finalList.size(); i++) {
            LinkedMultiValueMap<Integer, Object> finalMap = finalList.get(i);
            List<Object> examStudentImportDtoList = finalMap.get(i);
            List<ExamStudentImportDto> gsonList = GsonUtil.fromJson(GsonUtil.toJson(examStudentImportDtoList), new TypeToken<List<ExamStudentImportDto>>() {
            }.getType());
            ExamStudentImportForkJoin myTask = new ExamStudentImportForkJoin(0, examStudentImportDtoList.size() - 1, gsonList, modeEnum, teExamActivityMap, examId, orgId, createId);
            ForkJoinTask<Set<String>> forkJoinTask = forkJoinThreadPool.taskForkJoinPool().submit(myTask);
            roomCodeAndNameSet = forkJoinTask.join();
            txtList = this.importProgress(gsonList.size(), 0, gsonList.size(), txtList, tbTaskHistory);
        }
        map.put("line", line);
        //考场创建
        if (Objects.nonNull(roomCodeAndNameSet) && roomCodeAndNameSet.size() > 0) {
            Map<String, TBExamInvigilateUser> tbExamInvigilateUserMap = (Map<String, TBExamInvigilateUser>) map.get("tbExamInvigilateUserMap");
            AtomicInteger count = new AtomicInteger(0);
            Map<String, String> roomCodeAndNameMap = new HashMap<>(roomCodeAndNameSet.size());
            roomCodeAndNameSet.forEach(s -> {
                if (Objects.isNull(tbExamInvigilateUserMap) || (Objects.nonNull(tbExamInvigilateUserMap) && Objects.isNull(tbExamInvigilateUserMap.get(s)))) {
                    String[] strs = s.split(":");
                    if (!roomCodeAndNameMap.containsKey(strs[0] + ":" + strs[1])) {
                        TBExamInvigilateUser tbExamInvigilateUser = new TBExamInvigilateUser(Long.parseLong(strs[0]), orgId, strs[1], strs[2]);
                        tbExamInvigilateUserList.add(tbExamInvigilateUser);

                        QueryWrapper<TBExamInvigilateUserTemp> tbExamInvigilateUserTempQueryWrapper = new QueryWrapper<>();
                        tbExamInvigilateUserTempQueryWrapper.lambda().eq(TBExamInvigilateUserTemp::getExamId, Long.parseLong(strs[0]))
                                .eq(TBExamInvigilateUserTemp::getOrgId, orgId)
                                .eq(TBExamInvigilateUserTemp::getRoomCode, strs[1])
                                .eq(TBExamInvigilateUserTemp::getRoomName, strs[2]);

                        map.put("dataRemark", "编码:" + strs[1] + ",名称:" + strs[2]);
                        TBExamInvigilateUserTemp tbExamInvigilateUserTemp = tbExamInvigilateUserTempService.getOne(tbExamInvigilateUserTempQueryWrapper);
                        tbExamInvigilateUserTemp = Objects.isNull(tbExamInvigilateUserTemp) ? new TBExamInvigilateUserTemp(Long.parseLong(strs[0]), orgId, strs[1], strs[2]) : tbExamInvigilateUserTemp;
                        tbExamInvigilateUserTempService.saveOrUpdate(tbExamInvigilateUserTemp);
                        count.getAndIncrement();
                        roomCodeAndNameMap.put(strs[0] + ":" + strs[1], strs[2]);
                    } else {
                        throw new BusinessException("考场代码'" + strs[1] + "'下考场名称不一致" + "[" + roomCodeAndNameMap.get(strs[0] + ":" + strs[1]) + "," + strs[2] + "]");
                    }
                }
            });
            if (!CollectionUtils.isEmpty(tbExamInvigilateUserList)) {
                tbExamInvigilateUserService.saveBatch(tbExamInvigilateUserList);
            }
            if (count.get() > 0) {
                txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->创建了" + count + "条考场数据");
            }
        }
        return map;
    }

    /**
     * 考场导入逻辑
     *
     * @param finalList
     * @param map
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> execImportRoomCodeLogic(List<LinkedMultiValueMap<Integer, Object>> finalList, Map<String, Object> map) throws UnsupportedEncodingException {
        Long orgId = null;
        if (Objects.nonNull(map.get(SystemConstant.ORG_ID))) {
            orgId = Long.parseLong(String.valueOf(map.get(SystemConstant.ORG_ID)));
        }
        Long examId = Long.parseLong(String.valueOf(map.get(SystemConstant.EXAM_ID)));
        Long createId = Long.parseLong(String.valueOf(map.get(SystemConstant.CREATE_ID)));
        List<String> txtList = (List<String>) map.get("txtList");
        Set<TBUser> tbUserList = new HashSet<>();
        Set<TBUserRole> tbUserRoleList = new HashSet<>();
        Set<TBExamInvigilateUser> tbExamInvigilateUserList = new HashSet<>();
        TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
        Set<String> roomCodeSet = new HashSet<>();
        Set<String> roomNameSet = new HashSet<>();
        //保存用户
        int line = 0;
        for (int i = 0; i < finalList.size(); i++) {
            LinkedMultiValueMap<Integer, Object> finalMap = finalList.get(i);
            List<Object> examStudentDtoImportList = finalMap.get(i);
            int min = 0;
            int max = SystemConstant.MAX_IMPORT_SIZE, size = examStudentDtoImportList.size();
            if (max >= size) {
                max = size;
            }
            while (max <= size) {
                List subList = examStudentDtoImportList.subList(min, max);
                for (int y = 0; y < subList.size(); y++) {
                    line++;
                    RoomCodeImportDto roomCodeImportDto = (RoomCodeImportDto) subList.get(y);
                    roomCodeSet.add(roomCodeImportDto.getRoomCode());
                    roomNameSet.add(roomCodeImportDto.getRoomName());
                    map.put("dataRemark", "编码:" + roomCodeImportDto.getRoomCode() + ",名称:" + roomCodeImportDto.getRoomName());
                    dataVerify(examId, roomCodeImportDto.getTeacher1(), roomCodeImportDto.getTeacher1Pwd(), roomCodeImportDto.getRoomCode(), roomCodeImportDto.getRoomName(), orgId, createId, tbUserList, tbUserRoleList, tbExamInvigilateUserList);
                    map.put("dataRemark", "编码:" + roomCodeImportDto.getRoomCode() + ",名称:" + roomCodeImportDto.getRoomName());
                    dataVerify(examId, roomCodeImportDto.getTeacher2(), roomCodeImportDto.getTeacher2Pwd(), roomCodeImportDto.getRoomCode(), roomCodeImportDto.getRoomName(), orgId, createId, tbUserList, tbUserRoleList, tbExamInvigilateUserList);
                    map.put("dataRemark", "编码:" + roomCodeImportDto.getRoomCode() + ",名称:" + roomCodeImportDto.getRoomName());
                    dataVerify(examId, roomCodeImportDto.getTeacher3(), roomCodeImportDto.getTeacher3Pwd(), roomCodeImportDto.getRoomCode(), roomCodeImportDto.getRoomName(), orgId, createId, tbUserList, tbUserRoleList, tbExamInvigilateUserList);
                }
                txtList = this.importProgress(max, min, size, txtList, tbTaskHistory);
                if (max == size) {
                    break;
                }
                min = max;
                max += SystemConstant.MAX_IMPORT_SIZE;
                if (max >= size) {
                    max = size;
                }
            }
        }
        if (!CollectionUtils.isEmpty(roomCodeSet)) {
            List<String> roomCodeList = new ArrayList<>();
            roomCodeList.addAll(roomCodeSet);
            List<String> roomNameList = new ArrayList<>();
            roomNameList.addAll(roomNameSet);

            for (int i = 0; i < roomCodeList.size(); i++) {
                if (!checkRoomCodeExist(examId, roomCodeList.get(i), orgId, roomNameList.get(i))) {
                    throw new BusinessException("考场代码 " + roomCodeList.get(i) + " 不存在");
                }
            }
        }
        QueryWrapper<TBExamInvigilateUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TBExamInvigilateUser::getOrgId, orgId)
                .in(TBExamInvigilateUser::getRoomCode, roomCodeSet)
                .eq(TBExamInvigilateUser::getExamId, examId)
                .in(TBExamInvigilateUser::getRoomName, roomNameSet);
        tbExamInvigilateUserService.remove(wrapper);

        if (!CollectionUtils.isEmpty(tbUserList)) {
            tbUserService.saveOrUpdateBatch(tbUserList);
        }
        if (!CollectionUtils.isEmpty(tbUserRoleList)) {
            tbUserRoleService.saveOrUpdateBatch(tbUserRoleList);
        }
        if (!CollectionUtils.isEmpty(tbExamInvigilateUserList)) {
            tbExamInvigilateUserService.saveOrUpdateBatch(tbExamInvigilateUserList);
        }
        map.put("line", line);
        return map;
    }

    /**
     * 考场导出逻辑
     *
     * @param map
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> execExportRoomCodeLogic(Map<String, Object> map) {
        return commonExport(map);
    }

    @Override
    @Transactional
    public Map<String, Object> execExportMarkResultSimpleLogic(Map<String, Object> map) {
        return commonExport(map);
    }

    @Override
    @Transactional
    public Map<String, Object> execExportMarkResultStandardLogic(Map<String, Object> map) {
        return commonExport(map);
    }

    /**
     * 考生导出
     *
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> execExportExamStudentLogic(Map<String, Object> map) {
        return commonExport(map);
    }

    /**
     * 推送云阅卷数据逻辑
     *
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> execPushCloudMarkDataLogic(Map<String, Object> map) throws IOException {
        checkData(map);
        Long examId = (Long) map.get(SystemConstant.EXAM_ID);
        Long orgId = Long.parseLong(String.valueOf(map.get(SystemConstant.ORG_ID)));
        String examCode = (String) map.get(SystemConstant.EXAM_CODE);

        //先推送考试
        ExamCacheBean examCacheBean = teExamService.getExamCacheBean(examId);
        TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
        JSONObject jsonObject = Objects.nonNull(tbTaskHistory.getRemark()) ? JSONObject.parseObject(tbTaskHistory.getRemark()) : null;
        Integer totalTaskSize = 1, currentTaskSize = 1, jsTotalTaskSize = 0, jsCurrentTaskSize = 0;
        Long cloudMarkExamId = null;

        TEExam teExam = teExamService.cacheConvert(examCacheBean);
        if (Objects.isNull(tbTaskHistory.getEntityId())) {
            cloudMarkExamId = cloudMarkUtil.callExamSaveApi(new SaveExamParams(orgId, null, examCode, examCacheBean.getName(), DateUtil.format(new Date(examCacheBean.getStartTime()), Constants.DEFAULT_DATE_PATTERN)));
            teExam.setUpdateTime(System.currentTimeMillis());
            teExam.setThirdExamId(String.valueOf(cloudMarkExamId));
            teExamService.updateById(teExam);
            teExamService.updateExamCacheBean(examId);
        } else {
            cloudMarkExamId = tbTaskHistory.getEntityId();
        }
        if (Objects.nonNull(cloudMarkExamId)) {
            if (Objects.isNull(jsonObject)) {
                jsonObject = new JSONObject();
                jsonObject.put("examSize", 1);
                jsonObject.put("totalTaskSize", totalTaskSize);
                jsonObject.put("currentTaskSize", currentTaskSize);
                tbTaskHistory.setEntityId(cloudMarkExamId);
                tbTaskHistory.setRemark(jsonObject.toJSONString());
            } else {
                jsTotalTaskSize = jsonObject.getInteger("totalTaskSize");
                jsCurrentTaskSize = jsonObject.getInteger("currentTaskSize");
                tbTaskHistory.setStatus(TaskStatusEnum.RUNNING);
            }
            tbTaskHistoryService.updateById(tbTaskHistory);

            //推送试卷科目
            Set<Long> examPaperIdSet = pushExamPaperLogic(map, jsonObject, totalTaskSize, jsCurrentTaskSize, currentTaskSize, cloudMarkExamId);
            if (CollectionUtils.isEmpty(examPaperIdSet)) {
                throw new BusinessException("没有考试试卷信息");
            }

            //获取所有待阅卷的考生
            List<TEExamStudent> teExamStudentList = getExamStudentNeedMarkAll(map, jsonObject, teExam, examPaperIdSet, jsTotalTaskSize, jsCurrentTaskSize);

            //获取只有一次考试记录的考生
            List<TOeExamRecord> tOeExamRecordList = getExamRecordOnce(map, jsonObject, examPaperIdSet);

            //获取多次考试记录的考试
            Boolean examStudentBreachPush = (Boolean) map.get(SystemConstant.EXAM_STUDENT_BREACH_PUSH);
            List<TOeExamRecord> tOeExamRecordManyList = tOeExamRecordService.findExamRecordNeedMarkAll(examId, examPaperIdSet, true, examStudentBreachPush);
            if (!CollectionUtils.isEmpty(tOeExamRecordManyList)) {
                Set<Long> manyExamStudentIdSet = tOeExamRecordManyList.stream().map(s -> s.getExamStudentId()).collect(Collectors.toSet());
                jsonObject.put("examRecordManyListSize", manyExamStudentIdSet.size());
                tbTaskHistory.setRemark(jsonObject.toJSONString());
                tbTaskHistoryService.updateById(tbTaskHistory);
                List<TOeExamRecord> resultExamRecordList = filterManyExamRecord(tOeExamRecordManyList, teExam);
                tOeExamRecordList.addAll(resultExamRecordList);
            }

            //推送考试记录的考生开始
            pushExamStudentLogic(map,
                    jsonObject,
                    teExamStudentList,
                    tOeExamRecordList,
                    jsCurrentTaskSize,
                    cloudMarkExamId);
        }
        return pushDataSuccess(map, jsonObject);
    }

    /**
     * 推送数据成功
     *
     * @param map
     * @param jsonObject
     * @return
     */
    private Map<String, Object> pushDataSuccess(Map<String, Object> map,
                                                JSONObject jsonObject) {
        TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
        List<String> txtList = (List<String>) map.get("txtList");
        StringJoiner stringJoiner = new StringJoiner("");
        stringJoiner.add("推送数据成功：共推送了").add(String.valueOf(jsonObject.getInteger("examSize"))).add("个考试，")
                .add(String.valueOf(jsonObject.getInteger("examPaperSize"))).add("个试卷科目，")
                .add(String.valueOf(jsonObject.getInteger("examExamStudentSize"))).add("个考生");
        txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->" + stringJoiner.toString());

        tbTaskHistory.setSummary(txtList.toString());
        tbTaskHistory.setStatus(TaskStatusEnum.FINISH);
        tbTaskHistory.setFinishTime(System.currentTimeMillis());
        tbTaskHistoryService.updateById(tbTaskHistory);
        return map;
    }

    /**
     * 获取只有一次考试记录的考生
     *
     * @param map
     * @param jsonObject
     * @param examPaperIdSet
     * @return
     */
    private List<TOeExamRecord> getExamRecordOnce(Map<String, Object> map,
                                                  JSONObject jsonObject,
                                                  Set<Long> examPaperIdSet) {
        Long examId = (Long) map.get(SystemConstant.EXAM_ID);
        TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
        Boolean examStudentBreachPush = (Boolean) map.get(SystemConstant.EXAM_STUDENT_BREACH_PUSH);
        List<TOeExamRecord> tOeExamRecordList = tOeExamRecordService.findExamRecordNeedMarkAll(examId, examPaperIdSet, false, examStudentBreachPush);
        if (!CollectionUtils.isEmpty(tOeExamRecordList)) {
            jsonObject.put("examRecordListSize", tOeExamRecordList.size());

            Integer totalTaskSize = jsonObject.getInteger("totalTaskSize");
            Integer currentTaskSize = jsonObject.getInteger("currentTaskSize");

            BigDecimal progress = BigDecimal.valueOf(0);
            BigDecimal b = BigDecimal.valueOf(100);
            progress = BigDecimal.valueOf(currentTaskSize).divide(BigDecimal.valueOf(totalTaskSize), 2, BigDecimal.ROUND_HALF_UP).multiply(b);
            if (Objects.isNull(tbTaskHistory.getProgress()) || (Objects.nonNull(tbTaskHistory.getProgress()) && tbTaskHistory.getProgress().doubleValue() < progress.doubleValue())) {
                tbTaskHistory.setProgress(progress.doubleValue());
                tbTaskHistoryService.updateById(tbTaskHistory);
            }
            tbTaskHistory.setRemark(jsonObject.toJSONString());
        } else {
            tOeExamRecordList = new ArrayList<>();
        }
        return tOeExamRecordList;
    }

    /**
     * 获取所有待阅卷的考生
     *
     * @param map
     * @param jsonObject
     * @param teExam
     * @param examPaperIdSet
     * @param jsTotalTaskSize
     * @param jsCurrentTaskSize
     * @return
     */
    private List<TEExamStudent> getExamStudentNeedMarkAll(Map<String, Object> map,
                                                          JSONObject jsonObject,
                                                          TEExam teExam,
                                                          Set<Long> examPaperIdSet,
                                                          Integer jsTotalTaskSize,
                                                          Integer jsCurrentTaskSize) {
        Long examId = (Long) map.get(SystemConstant.EXAM_ID);
        TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
        Boolean examStudentBreachPush = (Boolean) map.get(SystemConstant.EXAM_STUDENT_BREACH_PUSH);
        List<TEExamStudent> teExamStudentList = teExamStudentService.findExamStudentNeedMarkAll(examId, examPaperIdSet, examStudentBreachPush);
        if (CollectionUtils.isEmpty(teExamStudentList)) {
            throw new BusinessException("没有待阅卷的考生");
        }
        Integer totalTaskSize = jsonObject.getInteger("totalTaskSize");
        Integer currentTaskSize = jsonObject.getInteger("currentTaskSize");
        totalTaskSize = totalTaskSize.intValue() + teExamStudentList.size();
        if (jsCurrentTaskSize.intValue() > currentTaskSize.intValue() && jsTotalTaskSize.intValue() > 0 && jsTotalTaskSize.intValue() != totalTaskSize.intValue()) {
            teExam.setUpdateTime(System.currentTimeMillis());
            teExam.setThirdExamId(null);
            teExamService.updateById(teExam);
            teExamService.updateExamCacheBean(examId);
            throw new BusinessException("数据已发生改变，需重新推送");
        }
        jsonObject.put("examExamStudentSize", teExamStudentList.size());
        jsonObject.put("totalTaskSize", totalTaskSize);
        tbTaskHistory.setRemark(jsonObject.toJSONString());
        return teExamStudentList;
    }

    /**
     * 推送考生和考试记录逻辑
     *
     * @param map
     * @param jsonObject
     * @param teExamStudentList
     * @param tOeExamRecordList
     * @param jsCurrentTaskSize
     * @param cloudMarkExamId
     */
    private void pushExamStudentLogic(Map<String, Object> map,
                                      JSONObject jsonObject,
                                      List<TEExamStudent> teExamStudentList,
                                      List<TOeExamRecord> tOeExamRecordList,
                                      Integer jsCurrentTaskSize,
                                      Long cloudMarkExamId) throws IOException {
        Long orgId = Long.parseLong(String.valueOf(map.get(SystemConstant.ORG_ID)));
        TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
        Boolean objectiveScorePush = (Boolean) map.get(SystemConstant.OBJECTIVE_SCORE_PUSH);

        BigDecimal progress = BigDecimal.valueOf(0);
        BigDecimal b = BigDecimal.valueOf(100);
        TBOrg tbOrg = themisCacheService.addOrgCache(orgId);

        Integer totalTaskSize = jsonObject.getInteger("totalTaskSize");
        Integer currentTaskSize = jsonObject.getInteger("currentTaskSize");

//        Map<Long, TOeExamRecord> tOeExamRecordMap = tOeExamRecordList.stream().collect(
//                Collectors.toMap(TOeExamRecord::getExamStudentId, Function.identity(), (dto1, dto2) -> dto1));
        LinkedMultiValueMap<Long, TOeExamRecord> tOeExamRecordMap = new LinkedMultiValueMap<>();
        for (TOeExamRecord t : tOeExamRecordList) {
            tOeExamRecordMap.add(t.getExamStudentId(), t);
        }

        Map<Long, Map<String, Integer>> paperStructMap = new HashMap<>();
        List<File> recordJsonList = new ArrayList<>(teExamStudentList.size());
        map.put("recordJsonList", recordJsonList);
        //推送考试记录的考生
        int min = 0;
        int max = SystemConstant.MAX_IMPORT_SIZE, size = teExamStudentList.size();
        if (max >= size) {
            max = size;
        }
        while (max <= size) {
            List<TEExamStudent> subList = teExamStudentList.subList(min, max);
            for (int y = 0; y < subList.size(); y++) {
                TEExamStudent t = subList.get(y);
                if (jsCurrentTaskSize.intValue() > 0 && currentTaskSize.intValue() < jsCurrentTaskSize.intValue()) {
                    jsonObject.put("currentTaskSize", currentTaskSize);
                    currentTaskSize++;
                    tbTaskHistory.setRemark(jsonObject.toJSONString());
                    continue;
                } else {
                    List<TOeExamRecord> tOeExamRecordExamStudentList = tOeExamRecordMap.get(t.getId());
                    if (CollectionUtils.isEmpty(tOeExamRecordExamStudentList)) {
                        continue;
                    }
                    for (TOeExamRecord tOeExamRecord : tOeExamRecordExamStudentList) {
                        String courseCode = t.getCourseCode() + SystemConstant.JOINT_MARK + tOeExamRecord.getPaperId();
                        cloudMarkUtil.callStudentSaveApi(new SaveStudentParams(orgId, cloudMarkExamId, String.valueOf(tOeExamRecord.getId()),
                                t.getIdentity(),
                                t.getName(),
                                tbOrg.getName(),
                                Objects.isNull(t.getClassNo()) ? SystemConstant.VALUE_OF_BLANK_REQUIRED_FIELD : t.getClassNo(),
                                SystemConstant.VALUE_OF_BLANK_REQUIRED_FIELD,
                                courseCode,
                                t.getCourseName()));

                        OpenRecordNeedMarkBean openRecordNeedMarkBean = GsonUtil.fromJson(GsonUtil.toJson(tOeExamRecord), OpenRecordNeedMarkBean.class);
                        List<OpenRecordAnswerTempBean> answersTemp = examAnswerService.findByExamRecordId(tOeExamRecord.getId());
                        openRecordNeedMarkBean = SystemConstant.filterAnswer(openRecordNeedMarkBean, answersTemp, paperStructMap);
                        if (!CollectionUtils.isEmpty(openRecordNeedMarkBean.getAnswers())) {
                            File fileAnswerJson = new File(SystemConstant.TEMP_FILES_DIR + File.separator + CloudMarkFileUploadTypeEnum.ANSWER.getCode() + File.separator + SystemConstant.getNanoId() + SystemConstant.JSON_PREFIX);
                            if (!fileAnswerJson.exists()) {
                                fileAnswerJson.getParentFile().mkdirs();
                                fileAnswerJson.createNewFile();
                            }
                            IOUtils.write(JacksonUtil.parseJson(openRecordNeedMarkBean.getAnswers()).getBytes(SystemConstant.CHARSET_NAME), new FileOutputStream(fileAnswerJson));
                            recordJsonList.add(fileAnswerJson);
                            cloudMarkUtil.callFileUploadApi(new FileUploadParams(orgId, cloudMarkExamId, String.valueOf(tOeExamRecord.getId()), fileAnswerJson, CloudMarkFileUploadTypeEnum.JSON));
                        }

                        if (Objects.nonNull(objectiveScorePush) && objectiveScorePush) {
                            cloudMarkUtil.callStudentObjectiveScoreApi(new StudentObjectiveScoreParams(orgId, cloudMarkExamId, String.valueOf(tOeExamRecord.getId()), tOeExamRecord.getObjectiveScore()));
                        }
                        jsonObject.put("currentTaskSize", currentTaskSize);
                        currentTaskSize++;
                        tbTaskHistory.setRemark(jsonObject.toJSONString());
                    }
                }
            }
            progress = BigDecimal.valueOf(currentTaskSize).divide(BigDecimal.valueOf(totalTaskSize), 2, BigDecimal.ROUND_HALF_UP).multiply(b);
            if (Objects.isNull(tbTaskHistory.getProgress()) || (Objects.nonNull(tbTaskHistory.getProgress()) && tbTaskHistory.getProgress().doubleValue() < progress.doubleValue())) {
                tbTaskHistory.setProgress(progress.doubleValue());
                tbTaskHistoryService.updateById(tbTaskHistory);
            }
            if (max == size) {
                break;
            }
            min = max;
            max += SystemConstant.MAX_IMPORT_SIZE;
            if (max >= size) {
                max = size;
            }
        }
        jsonObject.put("currentTaskSize", currentTaskSize);
        tbTaskHistory.setRemark(jsonObject.toJSONString());
    }

    /**
     * 过滤多条考试记录的考生
     *
     * @param tOeExamRecordManyList
     * @param teExam
     * @return
     */
    private List<TOeExamRecord> filterManyExamRecord(List<TOeExamRecord> tOeExamRecordManyList, TEExam teExam) {
        List<TOeExamRecord> result = null;
        LinkedMultiValueMap<Long, TOeExamRecord> tOeExamRecordLinkedMultiValueMap = new LinkedMultiValueMap<>();
        for (TOeExamRecord bean : tOeExamRecordManyList) {
            tOeExamRecordLinkedMultiValueMap.add(bean.getExamStudentId(), bean);
        }
        if (!CollectionUtils.isEmpty(tOeExamRecordLinkedMultiValueMap)) {
            result = new ArrayList<>();
            List<TOeExamRecord> finalResult = result;
            tOeExamRecordLinkedMultiValueMap.forEach((k, v) -> {
                double highestObjectiveScore = 0.0;
                long maxFinishTime = 0L;
                boolean subjective = false;
                List<TOeExamRecord> tempResult = new ArrayList<>(v.size());
                for (TOeExamRecord bean : v) {
                    //获取对应的试卷信息
                    ExamPaperCacheBean paper = teExamPaperService.getExamPaperCacheBean(bean.getPaperId());
                    if (Objects.isNull(paper)) {
                        log.error("找不到对应的试卷信息, paperId=" + bean.getPaperId());
                        continue;
                    }
                    //根据试卷结构过滤没有主观题的情况
                    if (paper.getTotalSubjectiveScore().doubleValue() == 0D) {
                        subjective = true;
                        maxFinishTime = Math.max(maxFinishTime, bean.getFinishTime());
                        continue;
                    }
                    highestObjectiveScore = Math.max(highestObjectiveScore, bean.getObjectiveScore());
                    maxFinishTime = Math.max(maxFinishTime, bean.getFinishTime());
                    tempResult.add(bean);
                }
                if (tempResult.isEmpty()) {
                    return;
                }
                switch (teExam.getRecordSelectStrategy()) {
                    case HIGHEST_OBJECTIVE_SCORE:
                        if (subjective) {
                            final long time = maxFinishTime;
                            finalResult.addAll(v.stream().filter(bean -> bean.getFinishTime() == time).collect(Collectors.toList()));
                        } else {
                            //客观分最高，客观分相同则全部提交阅卷
                            final double score = highestObjectiveScore;
                            List<TOeExamRecord> temoRecordResult = tempResult.stream().filter(bean -> bean.getObjectiveScore() == score).collect(Collectors.toList());
                            if (temoRecordResult.size() > 1) {
                                TOeExamRecord tOeExamRecord = temoRecordResult.stream().max((p1, p2) -> Long.compare(p1.getFinishTime(), p2.getFinishTime())).get();
                                finalResult.add(tOeExamRecord);
                            } else {
                                finalResult.add(temoRecordResult.get(0));
                            }
                        }
                        break;
                    case LATEST:
                        //最后一次提交
                        final long time = maxFinishTime;
                        finalResult.addAll(tempResult.stream().filter(bean -> bean.getFinishTime() == time).collect(Collectors.toList()));
                        break;
                    default:
                        //总分最高，全部提交阅卷
                        finalResult.addAll(tempResult);
                        break;
                }
            });
        }
        return result;
    }

    /**
     * 推送试卷逻辑
     *
     * @param map
     * @param jsonObject
     * @param totalTaskSize
     * @param jsCurrentTaskSize
     * @param currentTaskSize
     * @param cloudMarkExamId
     * @return
     * @throws IOException
     */
    private Set<Long> pushExamPaperLogic(Map<String, Object> map,
                                         JSONObject jsonObject,
                                         Integer totalTaskSize,
                                         Integer jsCurrentTaskSize,
                                         Integer currentTaskSize,
                                         Long cloudMarkExamId) throws IOException {
        Long examId = (Long) map.get(SystemConstant.EXAM_ID);
        Long orgId = Long.parseLong(String.valueOf(map.get(SystemConstant.ORG_ID)));
        TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
        List<File> paperJsonList = null;

        QueryWrapper<TEExamPaper> teExamPaperQueryWrapper = new QueryWrapper<>();
        teExamPaperQueryWrapper.lambda().eq(TEExamPaper::getExamId, examId)
                .gt(TEExamPaper::getTotalSubjectiveScore, 0).orderByAsc(TEExamPaper::getId);
        List<TEExamPaper> teExamPaperList = teExamPaperService.list(teExamPaperQueryWrapper);
        if (CollectionUtils.isEmpty(teExamPaperList)) {
            throw new BusinessException("没有考试试卷");
        }
        totalTaskSize = totalTaskSize.intValue() + teExamPaperList.size();
        jsonObject.put("totalTaskSize", totalTaskSize);
        jsonObject.put("examPaperSize", teExamPaperList.size());
        tbTaskHistory.setRemark(jsonObject.toJSONString());
        Set<Long> examPaperIdSet = null;

        if (!CollectionUtils.isEmpty(teExamPaperList)) {
            paperJsonList = new ArrayList<>(teExamPaperList.size());
            map.put("paperJsonList", paperJsonList);
            examPaperIdSet = new HashSet<>(teExamPaperList.size());

            BigDecimal progress = BigDecimal.valueOf(0);
            BigDecimal b = BigDecimal.valueOf(100);

            int min = 0;
            int max = SystemConstant.MAX_IMPORT_SIZE, size = teExamPaperList.size();
            if (max >= size) {
                max = size;
            }
            while (max <= size) {
                List<TEExamPaper> subList = teExamPaperList.subList(min, max);
                for (int y = 0; y < subList.size(); y++) {
                    TEExamPaper t = subList.get(y);
                    examPaperIdSet.add(t.getId());
                    if (jsCurrentTaskSize.intValue() > 0 && currentTaskSize.intValue() < jsCurrentTaskSize.intValue()) {
                        jsonObject.put("currentTaskSize", currentTaskSize);
                        currentTaskSize++;
                        tbTaskHistory.setRemark(jsonObject.toJSONString());
                        continue;
                    } else {
                        String courseCode = t.getCourseCode() + SystemConstant.JOINT_MARK + t.getId();
                        cloudMarkUtil.callSubjectSaveApi(new SaveSubjectParams(orgId, cloudMarkExamId, courseCode, t.getName()));
                        //解析试卷JSON文件
                        JSONObject paperResult = JSONObject.parseObject(new String(ossUtil.download(false, t.getPaperViewPath()), StandardCharsets.UTF_8));
                        paperResult.put(SystemConstant.ID, t.getId());
                        paperResult.put("code", t.getCode());
                        paperResult.put(SystemConstant.NAME, t.getName());
                        if (Objects.nonNull(t.getAnswerPath())) {
                            JSONArray detailCollection = new JSONArray();
                            JSONArray paperDetails = paperResult.getJSONArray(SystemConstant.DETAILS);
                            //解析答案JSON文件
                            JSONObject answerJson = JSONObject.parseObject(new String(ossUtil.download(false, t.getAnswerPath()), StandardCharsets.UTF_8));
                            JSONArray answerDetails = answerJson.getJSONArray(SystemConstant.DETAILS);
                            for (int j = 0; j < paperDetails.size(); j++) {
                                //遍历所有大题
                                JSONObject paperDetail = paperDetails.getJSONObject(j);
                                JSONObject answerDetail = SystemConstant.findJsonObject(answerDetails, paperDetail.getIntValue(SystemConstant.NUMBER));
                                //按条件过滤需要的小题同时合并答案
                                JSONArray questionCollection = SystemConstant.filterQuestions(paperDetail.getJSONArray(SystemConstant.QUESTIONS),
                                        Objects.nonNull(answerDetail) ? answerDetail.getJSONArray(SystemConstant.QUESTIONS) : null, false,
                                        true);
                                //有小题的情况下，本大题才需要被包含
                                if (questionCollection.size() > 0) {
                                    paperDetail.put(SystemConstant.QUESTIONS, questionCollection);
                                    detailCollection.add(paperDetail);
                                }
                            }
                            paperResult.put(SystemConstant.DETAILS, detailCollection);
                        }

                        File filePaperJson = new File(SystemConstant.TEMP_FILES_DIR + File.separator + CloudMarkFileUploadTypeEnum.PAPER.getCode() + File.separator + SystemConstant.getNanoId() + SystemConstant.JSON_PREFIX);
                        if (!filePaperJson.exists()) {
                            filePaperJson.getParentFile().mkdirs();
                            filePaperJson.createNewFile();
                        }
                        IOUtils.write(paperResult.toJSONString().getBytes(SystemConstant.CHARSET_NAME), new FileOutputStream(filePaperJson));
                        paperJsonList.add(filePaperJson);
                        FileUploadParams fileUploadParamsPaperJson = new FileUploadParams(orgId, cloudMarkExamId, courseCode, CloudMarkFileUploadTypeEnum.JSON, filePaperJson, CloudMarkFileUploadTypeEnum.PAPER);
                        cloudMarkUtil.callFileUploadApi(fileUploadParamsPaperJson);

                        jsonObject.put("currentTaskSize", currentTaskSize);
                        currentTaskSize++;
                        tbTaskHistory.setRemark(jsonObject.toJSONString());
                    }
                }
                progress = BigDecimal.valueOf(currentTaskSize).divide(BigDecimal.valueOf(totalTaskSize), 2, BigDecimal.ROUND_HALF_UP).multiply(b);
                if (Objects.isNull(tbTaskHistory.getProgress()) || (Objects.nonNull(tbTaskHistory.getProgress()) && tbTaskHistory.getProgress().doubleValue() < progress.doubleValue())) {
                    tbTaskHistory.setProgress(progress.doubleValue());
                    tbTaskHistoryService.updateById(tbTaskHistory);
                }
                if (max == size) {
                    break;
                }
                min = max;
                max += SystemConstant.MAX_IMPORT_SIZE;
                if (max >= size) {
                    max = size;
                }
            }
            jsonObject.put("currentTaskSize", currentTaskSize);
            tbTaskHistory.setRemark(jsonObject.toJSONString());
            tbTaskHistoryService.updateById(tbTaskHistory);
        }
        return examPaperIdSet;
    }

    /**
     * 数据检查
     *
     * @param map
     */
    private void checkData(Map<String, Object> map) {
        Long examId = (Long) map.get(SystemConstant.EXAM_ID);
        if (Objects.isNull(examId)) {
            throw new RuntimeException("考试id为空");
        }
        Long orgId = Long.parseLong(String.valueOf(map.get(SystemConstant.ORG_ID)));
        if (Objects.isNull(orgId)) {
            throw new BusinessException("机构id为空");
        }
        String examCode = (String) map.get(SystemConstant.EXAM_CODE);
        if (Objects.isNull(examCode)) {
            throw new RuntimeException("考试编码为空");
        }
        TBOrg tbOrg = themisCacheService.addOrgCache(orgId);
        Optional.ofNullable(tbOrg).orElseThrow(() -> new BusinessException(ExceptionResultEnum.ORG_NO));

        //先推送考试
        ExamCacheBean examCacheBean = teExamService.getExamCacheBean(examId);
        Optional.ofNullable(examCacheBean).orElseThrow(() -> new BusinessException(ExceptionResultEnum.EXAM_NO));

        if (Objects.isNull(examCacheBean.getEnable()) || examCacheBean.getEnable().intValue() == 0) {
            throw new BusinessException(ExceptionResultEnum.EXAM_ENABLE);
        }
    }

    /**
     * 查询监考帐号是否存在
     *
     * @param examId
     * @param userName
     * @param password
     * @param roomCode
     * @param roomName
     * @param orgId
     * @param createId
     */
    public void dataVerify(Long examId, String userName, String password, String roomCode, String roomName, Long orgId, Long createId, Set<TBUser> tbUserList, Set<TBUserRole> tbUserRoleList, Set<TBExamInvigilateUser> tbExamInvigilateUserList) throws UnsupportedEncodingException {
        if (Objects.nonNull(userName)) {
            //先查询监考帐号是否存在
            QueryWrapper<TBUser> tbUserQueryWrapper = new QueryWrapper<>();
            tbUserQueryWrapper.lambda().eq(TBUser::getLoginName, userName).eq(TBUser::getOrgId, orgId);
            TBUser tbUser = tbUserService.getOne(tbUserQueryWrapper);
            if (Objects.isNull(tbUser)) {
                //新增用户
                tbUser = new TBUser(orgId, userName, userName, createId, password);
                TBUserRole tbUserRole = new TBUserRole(tbUser.getId(), RoleEnum.INVIGILATE.name());
                tbUserRoleList.add(tbUserRole);
            } else {
                if (Objects.nonNull(password) && !Objects.equals(password, "")) {
                    tbUser.setPassword(Base64Util.encode(password.getBytes(SystemConstant.CHARSET_NAME)));
                } else {
                    tbUser.setPassword(SystemConstant.DEFAULT_PASSWORD);
                }
            }
            tbUserList.add(tbUser);

            QueryWrapper<TBExamInvigilateUser> tbExamInvigilateUserQueryWrapper = new QueryWrapper<>();
            tbExamInvigilateUserQueryWrapper.lambda().eq(TBExamInvigilateUser::getOrgId, orgId)
                    .eq(TBExamInvigilateUser::getUserId, tbUser.getId())
                    .eq(TBExamInvigilateUser::getRoomCode, roomCode)
                    .eq(TBExamInvigilateUser::getExamId, examId)
                    .eq(TBExamInvigilateUser::getRoomName, roomName);
            TBExamInvigilateUser tbExamInvigilateUser = tbExamInvigilateUserService.getOne(tbExamInvigilateUserQueryWrapper);
            if (Objects.isNull(tbExamInvigilateUser)) {//新增考场
                tbExamInvigilateUser = new TBExamInvigilateUser(examId, orgId, tbUser.getId(), roomCode, roomName);
            }
            tbExamInvigilateUserList.add(tbExamInvigilateUser);
        } else {
            TBExamInvigilateUser tbExamInvigilateUser = new TBExamInvigilateUser(examId, orgId, null, roomCode, roomName);
            if (!tbExamInvigilateUserList.contains(tbExamInvigilateUser)) {
                tbExamInvigilateUserList.add(tbExamInvigilateUser);
            }
        }
    }

    private boolean checkRoomCodeExist(Long examId, String roomCode, Long orgId, String roomName) {
        QueryWrapper<TBExamInvigilateUserTemp> tbExamInvigilateUserTempQueryWrapper = new QueryWrapper<>();
        tbExamInvigilateUserTempQueryWrapper.lambda().eq(TBExamInvigilateUserTemp::getExamId, examId)
                .eq(TBExamInvigilateUserTemp::getOrgId, orgId)
                .eq(TBExamInvigilateUserTemp::getRoomCode, roomCode)
                .eq(TBExamInvigilateUserTemp::getRoomName, roomName);
        TBExamInvigilateUserTemp tbExamInvigilateUserTemp = tbExamInvigilateUserTempService.getOne(tbExamInvigilateUserTempQueryWrapper);
        tbExamInvigilateUserTemp = Objects.isNull(tbExamInvigilateUserTemp) ? new TBExamInvigilateUserTemp(examId, orgId, roomCode, roomName) : tbExamInvigilateUserTemp;
        return tbExamInvigilateUserTempService.saveOrUpdate(tbExamInvigilateUserTemp);
    }

    /**
     * 导入换算进度
     *
     * @param max
     * @param min
     * @param size
     * @param txtList
     * @param tbTaskHistory
     * @return
     */
    public List<String> importProgress(int max, int min, int size, List<String> txtList, TBTaskHistory tbTaskHistory) {
        BigDecimal bigDecimal = BigDecimal.valueOf(100);
        BigDecimal progress = BigDecimal.valueOf(Double.valueOf(BigDecimal.valueOf(max).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP).multiply(bigDecimal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())).setScale(0, BigDecimal.ROUND_HALF_UP);
        if (progress.intValue() == 100) {
            tbTaskHistory.setStatus(TaskStatusEnum.FINISH);
            tbTaskHistory.setSummary("共处理了" + size + "条数据");
            tbTaskHistory.setFinishTime(System.currentTimeMillis());
            txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据处理完毕，" + tbTaskHistory.getSummary());
        } else {
            tbTaskHistory.setStatus(TaskStatusEnum.RUNNING);
            tbTaskHistory.setSummary("正在处理第" + min + "条至" + max + "条数据");
            txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据处理中，" + tbTaskHistory.getSummary());
        }
        tbTaskHistory.setProgress(progress.doubleValue());
        return txtList;
    }

    /**
     * 导出换算进度
     *
     * @param max
     * @param min
     * @param size
     * @param txtList
     * @param tbTaskHistory
     * @return
     */
    public List<String> exportProgress(int max, int min, int size, List<String> txtList, TBTaskHistory tbTaskHistory) {
        BigDecimal bigDecimal = BigDecimal.valueOf(100);
        BigDecimal progress = null;
        if (size > 0) {
            progress = BigDecimal.valueOf(Double.valueOf(BigDecimal.valueOf(max).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP).multiply(bigDecimal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())).setScale(0, BigDecimal.ROUND_HALF_UP);
        } else {
            progress = BigDecimal.valueOf(-1);
        }
        if (progress.intValue() == 100) {
            tbTaskHistory.setStatus(TaskStatusEnum.FINISH);
            tbTaskHistory.setSummary("共导出了" + size + "条数据");
            tbTaskHistory.setFinishTime(System.currentTimeMillis());
            txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据导出完毕，" + tbTaskHistory.getSummary());
        } else if (progress.intValue() == -1) {
            tbTaskHistory.setStatus(TaskStatusEnum.FINISH);
            tbTaskHistory.setSummary("没有导出数据");
            tbTaskHistory.setFinishTime(System.currentTimeMillis());
            txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据导出完毕，" + tbTaskHistory.getSummary());
        } else {
            tbTaskHistory.setStatus(TaskStatusEnum.RUNNING);
            tbTaskHistory.setSummary("正在导出第" + min + "条至" + max + "条数据");
            txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->数据导出中，" + tbTaskHistory.getSummary());
        }
        tbTaskHistory.setProgress(progress.doubleValue());
        return txtList;
    }

    /**
     * 导入公用
     *
     * @param map
     * @return
     */
    private Map<String, Object> commonExport(Map<String, Object> map) {
        List<String> txtList = (List<String>) map.get("txtList");
        TBTaskHistory tbTaskHistory = (TBTaskHistory) map.get("tbTaskHistory");
        Integer max = Integer.parseInt(String.valueOf(map.get("max")));
        Integer min = Integer.parseInt(String.valueOf(map.get("min")));
        Integer size = Integer.parseInt(String.valueOf(map.get("size")));
        this.exportProgress(max, min, size, txtList, tbTaskHistory);
        return map;
    }
}