package com.testor.module.train.myManagement.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.dict.data.controller.SysDictDataController;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataResponse;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.util.DateUtil;
import com.testor.common.util.PageUtil;
import com.testor.module.train.course.dao.TTrainSmallNodeDao;
import com.testor.module.train.course.model.domain.TTrainCourse;
import com.testor.module.train.course.model.domain.TTrainSection;
import com.testor.module.train.course.model.domain.TTrainSmallNode;
import com.testor.module.train.course.model.dto.TTrainCourseParam;
import com.testor.module.train.course.service.TTrainCourseService;
import com.testor.module.train.course.service.TTrainSectionService;
import com.testor.module.train.course.service.TTrainSmallNodeService;
import com.testor.module.train.exam.model.domain.TTrainExamChoice;
import com.testor.module.train.exam.model.domain.TTrainExamJudgment;
import com.testor.module.train.exam.model.domain.TTrainQuestionBank;
import com.testor.module.train.exam.model.domain.TTrainTestQuestions;
import com.testor.module.train.exam.service.TTrainExamChoiceService;
import com.testor.module.train.exam.service.TTrainExamJudgmentService;
import com.testor.module.train.exam.service.TTrainTestQuestionsService;
import com.testor.module.train.examinationManage.model.dto.TTrainExaminationManageQueryParam;
import com.testor.module.train.myManagement.model.domain.*;
import com.testor.module.train.myManagement.model.dto.TTrainMyManagementDelParam;
import com.testor.module.train.myManagement.model.dto.TTrainMyManagementParam;
import com.testor.module.train.myManagement.model.dto.TTrainMyManagementQueryVO;
import com.testor.module.train.myManagement.model.dto.TTrainTestQuestionsExerciseParam;
import com.testor.module.train.myManagement.service.*;
import com.testor.module.train.paper.model.dto.Options;
import com.testor.module.train.paper.model.dto.ReturnTrainPaper;
import com.testor.module.train.paper.model.dto.TestQuestionsContent;
import com.testor.module.train.project.model.domain.TTrainEvaluateManage;
import com.testor.module.train.project.model.domain.TTrainProject;
import com.testor.module.train.project.model.dto.Exercise;
import com.testor.module.train.project.model.dto.MyManagement;
import com.testor.module.train.project.service.TTrainProjectService;
import com.testor.module.video.util.Beans;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * 我的培训教育及考试—安全培训教育Controller
 *
 * @author testor-framework
 * @date 2022-07-28 15:25:02
 */
@RestController
@RequestMapping("/management")
@Api(value = "TTrainMyManagement", tags = "安全培训教育——我的培训教育及考试")
@Slf4j
public class TTrainMyManagementController extends SuperController {
    @Autowired
    private TTrainMyManagementService tTrainMyManagementService;
    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private TTrainProjectService tTrainProjectService;

    @Autowired
    private TTrainCourseService tTrainCourseService;

    @Autowired
    private TTrainTestQuestionsExerciseService tTrainTestQuestionsExerciseService;

    @Autowired
    private TTrainTestQuestionsService tTrainTestQuestionsService;

    @Autowired
    private TTrainExamChoiceService tTrainExamChoiceService;

    @Autowired
    private TTrainExamJudgmentService tTrainExamJudgmentService;

    @Autowired
    private SysDictDataController sysDictDataController;

    @Autowired
    private TTrainGradeService tTrainGradeService;

    @Autowired
    private TTrainSmallNodeService tTrainSmallNodeService;

    @Autowired
    private TTrainSectionService tTrainSectionService;

    @Autowired
    private TSysOrgClientService tSysOrgClientService;

    @Autowired
    private TTrainSmallNodeDao tTrainSmallNodeDao;

    /* Generated Method*/
//    @ApiOperation(value = "新增 我的培训教育及考试—安全培训教育", notes = "Add TTrainMyManagement")
//    @PostMapping(value = "/add")
    public BaseResponse<TTrainMyManagement> addEntity(@RequestBody List<MyManagement> addRequest) {
        return tTrainMyManagementService.addEntity(addRequest);
    }

    @ApiOperation(value = "我的学习-开始学习 ", notes = "传 id ")
    @GetMapping(value = "/startLearn")
    public BaseResponse<List<TTrainCourseParam>> startLearn(TTrainMyManagement tTrainMyManagement) throws Exception {
        BaseResponse<List<TTrainCourseParam>> testQuestions = tTrainMyManagementService.startLearn(tTrainMyManagement);
        return testQuestions;
    }

    @ApiOperation(value = "线下集体培训签到", notes = "")
    @GetMapping(value = "/lineTrainSign")
    public BaseResponse<TTrainMyManagement> lineTrainSign(String id) throws Exception {
        return tTrainMyManagementService.lineTrainSign(id);
    }

    @ApiOperation(value = "扫码考试", notes = "")
    @GetMapping(value = "/scanCodeExam")
    public BaseResponse<TTrainExaminationManageQueryParam> scanCodeExam(String id) throws Exception {
        return tTrainMyManagementService.scanCodeExam(id);
    }

    @ApiOperation(value = "扫码考试-开始考试", notes = "")
    @GetMapping(value = "/startExam")
    public BaseResponse<ReturnTrainPaper> startExam(String id) throws Exception {
        return tTrainMyManagementService.startExam(id);
    }

    @ApiOperation(value = "测试", notes = "")
    @GetMapping(value = "/sysorgclient")
    public List<TSysOrgClient> sysorgclient() throws Exception {
        return tSysOrgClientService.list();
    }


    @ApiOperation(value = "我的学习-开始学习-获取课程详情 ", notes = "传 课程id  和 列表 id ")
    @GetMapping(value = "/getCourseDetail")
    public BaseResponse<TTrainCourseParam> getCourseDetail(String id, String taskId) throws Exception {
        if (StringHelper.isEmpty(id)) {
            throw new BusinessException("参数有误");
        }
        BaseResponse<TTrainCourseParam> testQuestions = tTrainMyManagementService.getCourseDetail(id, taskId);
        return testQuestions;
    }


    @ApiOperation(value = "查询培训计划下所有课程进度是否未完成 ", notes = "传培训计划 id ")
    @GetMapping(value = "/findAllProjectCourseCompleteState")
    public BaseResponse<Boolean> findAllProjectCourseCompleteState(TTrainMyManagement tTrainMyManagement  ) throws Exception {
        return tTrainMyManagementService.findAllProjectCourseCompleteState(tTrainMyManagement);
    }





    @ApiOperation(value = "我的学习-开始学习-学习进度统计保存 ", notes = "传 taskId 课程id 章节id 小节id %")
    @PostMapping(value = "/planStatistics")
    public BaseResponse<TTrainCourseLearnStatistics> planStatistics(@RequestBody List<TTrainCourseLearnStatistics> courseLearnStatistics) throws Exception {
        BaseResponse<TTrainCourseLearnStatistics> baseResponse = tTrainMyManagementService.planStatistics(courseLearnStatistics);
        return baseResponse;
    }

    @ApiOperation(value = "我的练习-题库名称-下拉框 ", notes = "Get TTrainMyManagement By Id")
    @GetMapping(value = "/getTestBlankName")
    public BaseResponse<List<TTrainQuestionBank>> getTestBlankName() throws Exception {
        BaseResponse<List<TTrainQuestionBank>> testQuestions = tTrainMyManagementService.getTestBlankName();
        return testQuestions;
    }

    @ApiOperation(value = "我的练习-开始练习 ", notes = "")
    @GetMapping(value = "/startExercise")
    public BaseResponse<BaseResponseList<TestQuestionsContent>> startExercise(Exercise exercise) throws Exception {
        BaseResponse<BaseResponseList<TestQuestionsContent>> testQuestions = tTrainTestQuestionsExerciseService.getTestQuestions(exercise);
        return testQuestions;
    }

    @ApiOperation(value = "我的练习-开始练习-保存关闭 ", notes = "必传个人中心主键id 试题id 选项id")
    @PostMapping(value = "/saveClose")
    public BaseResponse<TTrainTestQuestionsExercise> saveClose(@RequestBody List<TTrainTestQuestionsExercise> questBody) throws Exception {
        BaseResponse<TTrainTestQuestionsExercise> exerciseBaseResponse = tTrainTestQuestionsExerciseService.saveClose(questBody);
        return exerciseBaseResponse;
    }


    @ApiOperation(value = "我的练习-开始练习-重新练习 ", notes = "传所有已经做过题的id")
    @PostMapping(value = "/againExercise")
    public BaseResponse<BizGeneralResponse> againExercise(@RequestBody List<String> id) throws Exception {
        BaseResponse<BizGeneralResponse> exerciseBaseResponse = tTrainTestQuestionsExerciseService.againExercise(id);
        return exerciseBaseResponse;
    }

    @ApiOperation(value = "我的考试-开始考试 ", notes = "Get TTrainMyManagement By Id")
    @GetMapping(value = "/startExamine")
    public BaseResponse<ReturnTrainPaper> startExamine(String id) throws Exception {
        BaseResponse<ReturnTrainPaper> testQuestions = tTrainTestQuestionsExerciseService.startExamine(id);
        return testQuestions;
    }

    @ApiOperation(value = "我的考试-开始考试-提交试卷 ", notes = "必传个人中心主键id 试题id 选项id")
    @PostMapping(value = "/submitTestPaper")
    public BaseResponse<TTrainTestQuestionsExercise> submitTestPaper(@RequestBody List<TTrainTestQuestionsExercise> questBody) throws Exception {
        BaseResponse<TTrainTestQuestionsExercise> exerciseBaseResponse = tTrainTestQuestionsExerciseService.submitTestPaper(questBody);
        return exerciseBaseResponse;
    }

    @ApiOperation(value = "我的考试-开始考试-查看详情 ", notes = "Get TTrainMyManagement By Id")
    @GetMapping(value = "/getTestPaperDetail")
    public BaseResponse<ReturnTrainPaper> getTestPaperDetail(String id) throws Exception {
        BaseResponse<ReturnTrainPaper> testQuestions = tTrainTestQuestionsExerciseService.getTestPaperDetail(id);
        return testQuestions;
    }


    @ApiOperation(value = "错题记录-我的培训教育及考试 ", notes = "")
    @GetMapping(value = "/errorRecord")
    public BaseResponse<BaseResponseList<TestQuestionsContent>> errorRecord(TTrainTestQuestionsExerciseParam param) throws Exception {
        BaseResponse<BaseResponseList<TestQuestionsContent>> baseResponse = new BaseResponse<>();
        BaseResponseList<TestQuestionsContent> baseResponseList = new BaseResponseList<>();
        String userId = ContextUtils.getLoginUser().getUserId();
        IPage<TTrainTestQuestionsExercise> affiliation = tTrainTestQuestionsExerciseService.errorRecord(param, userId);
        // 获取所有试题id
        List<String> list = new ArrayList<>();
        for (TTrainTestQuestionsExercise record : affiliation.getRecords()) {
            list.add(record.getTestQuestionsId());
        }
        // 获取所有试题
        if (list.size() > 0) {
            List<TTrainTestQuestions> testQuestions = tTrainTestQuestionsService.list(new QueryWrapper<TTrainTestQuestions>()
                    .in(TTrainTestQuestions.ID, list)
            );
            // 获取试题及选项
            List<TestQuestionsContent> testList = getTestQuestions(testQuestions);
            baseResponseList.setData(testList);
            baseResponseList.setTotal(affiliation.getTotal());
            baseResponse.setData(baseResponseList);
        }
        return baseResponse;
    }

    @ApiOperation(value = "员工培训情况 教育培训计划", notes = "List TTrainProject with page")
    @GetMapping(value = "/staffTrainCase")
    public BaseResponse<BaseResponseList<TTrainMyManagementParam>> staffTrainCase(TTrainMyManagementParam param) {
        BaseResponse<BaseResponseList<TTrainMyManagementParam>> baseResponse = new BaseResponse<>();
        BaseResponseList<TTrainMyManagementParam> baseResponseList = new BaseResponseList<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        String parentIds = sysOrg.getParentIds();
        String orgId = sysOrg.getOrgId();
        IPage<TTrainMyManagementParam> affiliation = tTrainMyManagementService.staffTrainCase(param, parentIds, orgId);
        baseResponseList.setData(affiliation.getRecords());
        baseResponseList.setTotal(affiliation.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "获取详情  员工培训情况 ", notes = "返回培训计划关联的课程名称和id")
    @GetMapping(value = "/getDetail")
    public BaseResponse<List<TTrainCourse>> getDetail(String id) {
        BaseResponse<List<TTrainCourse>> listBaseResponse = new BaseResponse<>();
        TTrainMyManagement one = tTrainMyManagementService.getOne(new QueryWrapper<TTrainMyManagement>()
                .eq(TTrainMyManagement.ID, id)
                .ne(TTrainMyManagement.STATUS, BizConstants.STATUS_DELETE)
        );
        // 任务id
        String taskId = one.getTaskId();
        TTrainProject tTrainProject = tTrainProjectService.getById(taskId);
        // 任务关联的课程id
        String courseId = tTrainProject.getCourseId();
        List<TTrainCourse> detailCourse = tTrainCourseService.getDetailCourse(courseId);
        listBaseResponse.setData(detailCourse);
        return listBaseResponse;
    }

    @ApiOperation(value = "我的课程-评价  ", notes = "传id 评分")
    @GetMapping(value = "/evaluate")
    public BaseResponse<BizGeneralResponse> evaluate(TTrainEvaluateManage tTrainEvaluateManage) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        if (ObjectHelper.isNotEmpty(tTrainEvaluateManage)) {
            // 个人中心主键id
            String id = tTrainEvaluateManage.getId();
            TTrainMyManagement tTrainMyManagement = tTrainMyManagementService.getById(id);
            // 获取任务id
            String taskId = tTrainMyManagement.getTaskId();
            // 获取评分人
            String personId = tTrainMyManagement.getPersonId();
            // 获取评分
            String assessMinute = tTrainEvaluateManage.getAssessMinute();

            TTrainGrade tTrainGrade = new TTrainGrade();
            // 主键id
            String gradeId = IdHelper.getId32bit();
            tTrainGrade.setId(gradeId).setUserId(personId).setTaskId(taskId).setAssessMinute(Integer.valueOf(assessMinute))
                    .setOrgId(loginUser.getOrgId()).setAssessMinuteInfo(tTrainEvaluateManage.getAssessMinuteInfo());
            boolean result = tTrainGradeService.save(tTrainGrade);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @Autowired
    private TTrainMyManagementReadService tTrainMyManagementReadService;

    @ApiOperation(value = "更改阅读状态", notes = "learnWay 1集体 2自主")
    @GetMapping(value = "/read")
    public BaseResponse read(@RequestParam("nodeId") String nodeId, String learnWay, @RequestParam("managementId") String managementId, String courseId) {
        BaseResponse baseResponse = new BaseResponse();
        if (StringUtils.isBlank(nodeId) || StringUtils.isBlank(managementId)) {
            baseResponse.setMsg("参数不完整");
            return baseResponse;
        }
        String loginUserId = ContextUtils.getLoginUserId();
        TTrainMyManagementRead tTrainMyManagementRead = new TTrainMyManagementRead();
        tTrainMyManagementRead.setId(IdHelper.getId32bit());
        tTrainMyManagementRead.setNodeId(nodeId);
        tTrainMyManagementRead.setFinishTime(new Date());
        tTrainMyManagementRead.setReadStatus("1");
        tTrainMyManagementRead.setLearner(loginUserId);
        if (learnWay.equals("2")) {
            tTrainMyManagementRead.setLearnWay("1");
        } else {
            tTrainMyManagementRead.setLearnWay("0");
        }
        tTrainMyManagementRead.setManagementId(managementId);
        int count = tTrainMyManagementReadService.count(new QueryWrapper<TTrainMyManagementRead>()
                .eq("node_id", nodeId).eq("learner", loginUserId).eq("management_id", managementId)
        );
        if (count == 0) {
            boolean update = tTrainMyManagementReadService.save(tTrainMyManagementRead);
            if (!update) {
                baseResponse.setMsg("失败");
            }
        }
        return baseResponse;
    }


    @SneakyThrows
    @ApiOperation(value = "获取 我的培训教育及考试 分页列表", notes = "List TTrainMyManagementQueryVO with page")
    @PostMapping(value = "/list")
    public BaseResponse<BaseResponseList<TTrainMyManagementQueryVO>> listEntity(@RequestBody TTrainMyManagementParam param) {
        BaseResponse<BaseResponseList<TTrainMyManagementQueryVO>> baseResponse = new BaseResponse<>();
        BaseResponseList<TTrainMyManagementQueryVO> baseResponseList = new BaseResponseList<>();
        List<TTrainMyManagementQueryVO> myManagementQueryVo = new ArrayList<>();
        if (StringUtils.isNotBlank(param.getCurrentStatus())) {
            TTrainMyManagementParam tTrainMyManagementParam = new TTrainMyManagementParam();
            BeanUtils.copyProperties(param, tTrainMyManagementParam);
            tTrainMyManagementParam.setLimit(String.valueOf(-1));
            List<TTrainMyManagementQueryVO> myManagementQueryVOS = buildList(tTrainMyManagementParam).getData().getData();
            List<TTrainMyManagementQueryVO> collect = myManagementQueryVOS.stream().filter(item -> item.getCurrentStatus().equals(param.getCurrentStatus())).collect(Collectors.toList());
            myManagementQueryVo.addAll(collect);
            baseResponse.setData(baseResponseList);
            List<TTrainMyManagementQueryVO> list = PageUtil.startPage(collect, Integer.valueOf(param.getPage()), Integer.valueOf(param.getLimit()));
            baseResponseList.setData(list);
            baseResponseList.setTotal(collect.size());
            baseResponse.setData(baseResponseList);
            return baseResponse;
        } else {
            return buildList(param);
        }
    }
/*        Long page = Long.valueOf(param.getPage());
        List<TTrainMyManagementQueryVO> myManagementQueryVo = new ArrayList<>();

        while (true) {
            List<TTrainMyManagementQueryVO> tTrainMyManagementQueryVOS = buildList(param);
            if (CollectionUtils.isEmpty(tTrainMyManagementQueryVOS)) {
                break;
            }
            if (StringUtils.isBlank(param.getCurrentStatus())) {
                myManagementQueryVo.addAll(tTrainMyManagementQueryVOS);
                break;
            }
            List<TTrainMyManagementQueryVO> collect = tTrainMyManagementQueryVOS.stream().filter(item -> item.getCurrentStatus().equals(param.getCurrentStatus())).collect(Collectors.toList());
            myManagementQueryVo.addAll(collect);
            //如果小于十条
            if (tTrainMyManagementQueryVOS.size() < 10) {
                page += 1;
                param.setPage(page.toString());
            } else {
                break;
            }
        }*/

    @SneakyThrows
    public BaseResponse<BaseResponseList<TTrainMyManagementQueryVO>> buildList(TTrainMyManagementParam param) {
        String loginUserId = ContextUtils.getLoginUserId();
        BaseResponse<BaseResponseList<TTrainMyManagementQueryVO>> baseResponse = new BaseResponse<>();
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TTrainMyManagement> resultPage = new Page<>(page, limit);
        QueryWrapper<TTrainMyManagement> queryWrapper = this.createQuery(param);
        Page<TTrainMyManagement> resultList = tTrainMyManagementService.page(resultPage, queryWrapper);
        BaseResponseList<TTrainMyManagementQueryVO> baseResponseList = new BaseResponseList<>();
        //考试
        if ("2".equals(param.getTabStatus())) {
            // 更新考试计划的当前状态
            List<TTrainMyManagement> listRecords = resultList.getRecords();
            listRecords.stream().forEach(item -> {
                if (!"3".equals(item.getLearnWay())) {
                    // 计划开始时间
                    LocalDateTime visitStartTime = DateUtil.dateToLocalDateTime(item.getVisitStartTime());
                    String startTime = "";
                    if (ObjectHelper.isNotEmpty(visitStartTime)) {
                        startTime = visitStartTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    }
                    // 计划结束时间
                    LocalDateTime visitEndTime = DateUtil.dateToLocalDateTime(item.getVisitEndTime());
                    String endTime = "";
                    if (ObjectHelper.isNotEmpty(visitEndTime)) {
                        endTime = visitEndTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    }
                    // 当前时间
                    String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    if (currentTime.compareTo(startTime) > 0 && currentTime.compareTo(endTime) < 0) {
                        item.setCurrentStatus("1");
                        tTrainMyManagementService.update(new UpdateWrapper<TTrainMyManagement>()
                                .eq(TTrainMyManagement.ID, item.getId()).set(TTrainMyManagement.CURRENT_STATUS, item.getCurrentStatus()));
                    }
                    if (currentTime.compareTo(startTime) < 0) {
                        item.setCurrentStatus("0");
                        tTrainMyManagementService.update(new UpdateWrapper<TTrainMyManagement>()
                                .eq(TTrainMyManagement.ID, item.getId()).set(TTrainMyManagement.CURRENT_STATUS, item.getCurrentStatus()));
                    }
                    if (currentTime.compareTo(endTime) > 0) {
                        item.setCurrentStatus("3");
                        tTrainMyManagementService.update(new UpdateWrapper<TTrainMyManagement>()
                                .eq(TTrainMyManagement.ID, item.getId()).set(TTrainMyManagement.CURRENT_STATUS, item.getCurrentStatus()));
                        if (StringHelper.isEmpty(item.getTestScore())) {
                            item.setPercentage("2");
                        }
                    }
                    SysDictDataResponse materials2 = sysDictDataController.getDictTypeDetail("", "EXAM_TYPE", item.getTaskType()).getData();
                    if (ObjectHelper.isNotEmpty(materials2)) {
                        String materials = materials2.getDictValue();
                        item.setTaskType(materials);
                    }
                }

            });
            List<TTrainMyManagementQueryVO> tTrainMyManagementQueryVOS = Beans.listToBean(listRecords, TTrainMyManagementQueryVO.class);
            baseResponseList.setData(tTrainMyManagementQueryVOS);
            baseResponseList.setTotal(resultList.getTotal());
            baseResponse.setData(baseResponseList);
            return baseResponse;
            //课程
        } else if ("1".equals(param.getTabStatus())) {
            List<TTrainMyManagement> records = resultPage.getRecords();
            processList(records, loginUserId);
        }
        List<TTrainMyManagement> records = resultList.getRecords();
        List<TTrainMyManagementQueryVO> beans = Beans.listToBean(records, TTrainMyManagementQueryVO.class);
        for (TTrainMyManagementQueryVO bean : beans) {
            int count = tTrainGradeService.count(new QueryWrapper<TTrainGrade>()
                    .eq("task_id", bean.getTaskId())
                    .eq("user_id", bean.getPersonId())
                    .eq("org_id", bean.getOrgId()));
            if (count > 0) {
                bean.setEvaluateStatus(1);
            } else if (count == 0) {
                bean.setEvaluateStatus(2);
            }
        }
        baseResponseList.setData(beans);
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }


    public void processList(List<TTrainMyManagement> records, String loginUserId) throws InterruptedException, ExecutionException {
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();

        for (TTrainMyManagement record : records) {
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                // 当前时间
                TTrainMyManagement tTrainMyManagement = new TTrainMyManagement();
                tTrainMyManagement.setId(record.getId());
                TTrainProject byId = tTrainProjectService.getById(record.getTaskId());
                List<String> courseIds = new ArrayList<>();
                if (byId != null) {
                    String courseId = byId.getCourseId();
                    if (courseId.contains(",")) {
                        courseIds = Arrays.asList(courseId.split(","));
                    } else {
                        courseIds.add(courseId);
                    }
                }

                List<Object> sectionAllIds = new ArrayList<>();
                for (String taskId : courseIds) {
                    //获取所有章节id
                    List<Object> sectionIds = tTrainSectionService.listObjs(new QueryWrapper<TTrainSection>().select("id").in("course_id", taskId).eq("status", "0"));
                    if (sectionIds.size() > 0) {
                        sectionAllIds.addAll(sectionIds);
                    }
                }
                if (sectionAllIds.size() != 0) {
                    //获取所有小节，完成时间从小到大排序
                    List<TTrainSmallNode> list = tTrainSmallNodeService.getExaminationInformation(sectionAllIds, loginUserId, record.getId());
                    if (list != null && list.size() > 0) {
                        //第一列数据
                        TTrainSmallNode tTrainSmallNode = list.get(0);
                        //最后一列数据
                        TTrainSmallNode lastSmallNode = list.get(list.size() - 1);
                        //如果当前时间还未到计划开始时间（在计划开始之前）
                        if (now.isBefore(DateUtil.dateToLocalDateTime(record.getVisitStartTime()))) {
                            //设置进度百分比
                            String percentage = tTrainSmallNodeDao.getPercentage(sectionAllIds, loginUserId, record.getId());
                            record.setPercentage(percentage);
                            //设置未开始
                            record.setCurrentStatus("0");
                        }
                        //如果第一列数据为空，证明没有学习完毕
                        if (tTrainSmallNode.getFinishTime() == null) {
                            //如果当前时间在结束计划之后
                            if (now.isAfter(DateUtil.dateToLocalDateTime(record.getVisitEndTime()))) {
                                //设置进度百分比
                                String percentage = tTrainSmallNodeDao.getPercentage(sectionAllIds, loginUserId, record.getId());
                                record.setPercentage(percentage);
                                //设置逾期
                                record.setCurrentStatus("5");
                            } else {
                                //设置进度百分比
                                String percentage = tTrainSmallNodeDao.getPercentage(sectionAllIds, loginUserId, record.getId());
                                record.setPercentage(percentage);
                                //设置进行中
                                record.setCurrentStatus("1");
                            }
                        }
                        //如果最后一列不为空
                        else {
                            //如果最后完成的小节时间在结束计划之后
                            if (tTrainSmallNode.getFinishTime().compareTo(record.getVisitEndTime())>0) {
                                //设置进度百分比
                                String percentage = tTrainSmallNodeDao.getPercentage(sectionAllIds, loginUserId, record.getId());
                                record.setPercentage(percentage);
                                //设置逾期
                                record.setCurrentStatus("5");
                            } else {
                                //设置进度百分比
                                String percentage = tTrainSmallNodeDao.getPercentage(sectionAllIds, loginUserId, record.getId());
                                record.setPercentage(percentage);
                                //设置已完成
                                record.setCurrentStatus("3");
                            }
                        }
                    }
                }
            });
            futures.add(future);
        }
        // 等待所有异步任务完成
        CompletableFuture<Void>[] futuresArray = futures.toArray(new CompletableFuture[0]);
        CompletableFuture<Void> allOf = CompletableFuture.allOf(futuresArray);
        allOf.get(); // 等待所有任务完成
    }


    //    @ApiOperation(value = "获取 我的培训教育及考试—安全培训教育 列表", notes = "List TTrainMyManagement all")
//    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TTrainMyManagement>> listAllEntity(TTrainMyManagementParam param) {
        BaseResponse<BaseResponseList<TTrainMyManagement>> baseResponse = new BaseResponse<>();
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TTrainMyManagement> queryWrapper = this.createQuery(param);
        List<TTrainMyManagement> resultList = tTrainMyManagementService.list(queryWrapper);
        BaseResponseList<TTrainMyManagement> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "成绩录入 ", notes = "传 id  和 成绩")
    @PostMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody List<TTrainMyManagement> updateRequest) {
        return tTrainMyManagementService.updateEntity(updateRequest);
    }

    //    @ApiOperation(value = "删除 我的培训教育及考试—安全培训教育 ", notes = "delete TTrainMyManagement By Id")
//    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TTrainMyManagementDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            TTrainMyManagement data = new TTrainMyManagement();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = tTrainMyManagementService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    //        @ApiOperation(value = "获取 我的培训教育及考试—安全培训教育 ", notes = "Get TTrainMyManagement By Id")
//    @GetMapping(value = "/get")
    public BaseResponse<TTrainMyManagement> getById(String id) {
        BaseResponse<TTrainMyManagement> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            // TODO 按需求添加业务异常判断
            TTrainMyManagement data = tTrainMyManagementService.getById(id);
            baseResponse.setData(data);
        }
        return baseResponse;
    }

    //    @ApiOperation(value = "批量删除我的培训教育及考试—安全培训教育", notes = "delete TTrainMyManagement by batch Id")
//    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TTrainMyManagementDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TTrainMyManagement> tTrainMyManagementList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TTrainMyManagement data = new TTrainMyManagement();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tTrainMyManagementList.add(data);
            }
            boolean result = tTrainMyManagementService.updateBatchById(tTrainMyManagementList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TTrainMyManagement> createQuery(TTrainMyManagementParam queryParam) {
        QueryWrapper<TTrainMyManagement> queryWrapper = new QueryWrapper<>();
        String userId = ContextUtils.getLoginUser().getUserId();
        queryWrapper.eq(TTrainMyManagement.PERSON_ID, userId);
        if (StringHelper.isNotEmpty(queryParam.getTabStatus())) {
            queryWrapper.eq(TTrainMyManagement.TAB_STATUS, queryParam.getTabStatus());
            if ("1".equals(queryParam.getTabStatus())) {
                queryWrapper.ne(TTrainMyManagement.LEARN_WAY, "1");
            }
        }
        if (ObjectHelper.isNotEmpty(queryParam.getVisitStartTime()) && ObjectHelper.isNotEmpty(queryParam.getVisitEndTime())) {
            String start = queryParam.getVisitStartTime().toString();
            String end = queryParam.getVisitEndTime().toString();
            start = start.replace("T", " ");
            end = end.replace("T", " ");
            queryWrapper.between(TTrainMyManagement.VISIT_START_TIME, start, end);
            queryWrapper.between(TTrainMyManagement.VISIT_END_TIME, start, end);
        } else {
            if (ObjectHelper.isNotEmpty(queryParam.getVisitStartTime())) {
                queryWrapper.eq(TTrainMyManagement.VISIT_START_TIME, queryParam.getVisitStartTime().toString());
            }
            if (ObjectHelper.isNotEmpty(queryParam.getVisitEndTime())) {
                queryWrapper.eq(TTrainMyManagement.VISIT_END_TIME, queryParam.getVisitEndTime().toString());
            }
        }
        if (StringHelper.isNotEmpty(queryParam.getPersonId())) {
            queryWrapper.eq(TTrainMyManagement.PERSON_ID, queryParam.getPersonId());
        }
        if (StringHelper.isNotEmpty(queryParam.getTaskId())) {
            queryWrapper.eq(TTrainMyManagement.TASK_ID, queryParam.getTaskId());
        }
        if (StringHelper.isNotEmpty(queryParam.getTaskType())) {
            queryWrapper.eq(TTrainMyManagement.TASK_TYPE, queryParam.getTaskType());
        }
        if (StringHelper.isNotEmpty(queryParam.getLearnWay())) {
            //1是自主 2是集体
            if (queryParam.getLearnWay().equals("1")) {
                queryWrapper.eq(TTrainMyManagement.LEARN_WAY, "2");
            } else {
                queryWrapper.ne(TTrainMyManagement.LEARN_WAY, "2").isNotNull(TTrainMyManagement.LEARN_WAY);
            }
        }
        if (StringHelper.isNotEmpty(queryParam.getPersonAffiliation())) {
            queryWrapper.eq(TTrainMyManagement.PERSON_AFFILIATION, queryParam.getPersonAffiliation());
        }
        if (StringHelper.isNotEmpty(queryParam.getCompany())) {
            queryWrapper.like(TTrainMyManagement.COMPANY, queryParam.getCompany());
        }
        if (StringHelper.isNotEmpty(queryParam.getDeptName())) {
            queryWrapper.like(TTrainMyManagement.DEPT_NAME, queryParam.getDeptName());
        }
        if (StringHelper.isNotEmpty(queryParam.getPersonNameId())) {
            queryWrapper.eq(TTrainMyManagement.PERSON_NAME_ID, queryParam.getPersonNameId());
        }
        if (StringHelper.isNotEmpty(queryParam.getPersonName())) {
            queryWrapper.like(TTrainMyManagement.PERSON_NAME, queryParam.getPersonName());
        }
/*        if (StringHelper.isNotEmpty(queryParam.getCurrentStatus())) {
            queryWrapper.eq(TTrainMyManagement.CURRENT_STATUS, queryParam.getCurrentStatus());
        }*/
        if (StringHelper.isNotEmpty(queryParam.getPercentage())) {
            queryWrapper.eq(TTrainMyManagement.PERCENTAGE, queryParam.getPercentage());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TTrainMyManagement.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(TTrainMyManagement.PROCESS_ID, queryParam.getProcessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TTrainMyManagement.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TTrainMyManagement.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TTrainMyManagement.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TTrainMyManagement.UPDATE_DATE);
        }
        queryWrapper.orderByDesc(TTrainMyManagement.CREATE_DATE);
        return queryWrapper;
    }

    /**
     * 获取所有试题及选项
     *
     * @param testQuestions 试题集合
     * @return
     */
    public List<TestQuestionsContent> getTestQuestions(List<TTrainTestQuestions> testQuestions) {
        List<TestQuestionsContent> testQuestionsContents = new ArrayList<>();
        int num = 0;
        for (TTrainTestQuestions tTrainTestQuestions : testQuestions) {
            String testQuestionsType = tTrainTestQuestions.getTestQuestionsType();
            //试题id
            String questionsId = tTrainTestQuestions.getId();
            num++;
            if ("SELECT".equals(testQuestionsType) || "MORE_SELECT".equals(testQuestionsType)) {
                // 每一个题目
                TestQuestionsContent testQuestionsContent = BeanHelper.beanToBean(tTrainTestQuestions, TestQuestionsContent.class);
                QueryWrapper<TTrainExamChoice> wrapper = new QueryWrapper<>();
                wrapper.eq(TTrainExamChoice.TEST_QUESTIONS_ID, questionsId);
                // 当前题目包含的所有选项
                List<TTrainExamChoice> list1 = tTrainExamChoiceService.list(wrapper);
                // 按照选项排序
                list1 = list1.stream().sorted(Comparator.comparing(TTrainExamChoice::getOptions))
                        .collect(Collectors.toList());
                List<Options> optionsList = new ArrayList<>();
                for (TTrainExamChoice tTrainExamChoice : list1) {
                    Options options = BeanHelper.beanToBean(tTrainExamChoice, Options.class);
                    String optionsTest = options.getOptions() + ": " + options.getOptionText();
                    options.setOptionText(optionsTest);
                    optionsList.add(options);
                }
                String testQuestionsContent1 = num + "." + testQuestionsContent.getTestQuestionsContent();
                testQuestionsContent.setTestQuestionsContent(testQuestionsContent1);
                testQuestionsContent.setOptions(optionsList);
                String score = "";
                testQuestionsContent.setScore(score);
                testQuestionsContent.setDictKey(testQuestionsType);
                testQuestionsContents.add(testQuestionsContent);
            }
            if ("JUDGE".equals(testQuestionsType)) {
                // 每一个题目
                TestQuestionsContent testQuestionsContent = BeanHelper.beanToBean(tTrainTestQuestions, TestQuestionsContent.class);
                QueryWrapper<TTrainExamJudgment> wrapper = new QueryWrapper<>();
                wrapper.eq(TTrainExamJudgment.TEST_QUESTIONS_ID, questionsId);
                // 当前题目包含的所有选项
                List<TTrainExamJudgment> list1 = tTrainExamJudgmentService.list(wrapper);
                // 按照选项排序
                list1 = list1.stream().sorted(Comparator.comparing(TTrainExamJudgment::getOptions))
                        .collect(Collectors.toList());
                List<Options> optionsList = new ArrayList<>();
                for (TTrainExamJudgment tTrainExamChoice : list1) {
                    Options options = BeanHelper.beanToBean(tTrainExamChoice, Options.class);
                    String optionsTest = options.getOptions() + ": " + options.getOptionText();
                    options.setOptionText(optionsTest);
                    optionsList.add(options);
                }
                String testQuestionsContent1 = num + "." + testQuestionsContent.getTestQuestionsContent();
                testQuestionsContent.setTestQuestionsContent(testQuestionsContent1);
                testQuestionsContent.setOptions(optionsList);
                String score = "";
                testQuestionsContent.setScore(score);
                testQuestionsContent.setDictKey(testQuestionsType);
                testQuestionsContents.add(testQuestionsContent);
            }
        }
        String userId = ContextUtils.getLoginUser().getUserId();
        List<TTrainTestQuestionsExercise> list = tTrainTestQuestionsExerciseService.list(new QueryWrapper<TTrainTestQuestionsExercise>()
                .eq(TTrainTestQuestionsExercise.PERSON_ID, userId)
                .eq(TTrainTestQuestionsExercise.IS_CORRECT, "0")
        );

        for (TestQuestionsContent test : testQuestionsContents) {
            for (TTrainTestQuestionsExercise tTrain : list) {
                if (test.getId().equals(tTrain.getTestQuestionsId())) {
                    test.setIsSelect("1");
                    test.setIsCorrect(tTrain.getIsCorrect());
                    String[] split = tTrain.getOptionsId().split(",");
                    for (Options option : test.getOptions()) {
                        for (String s : split) {
                            if (option.getId().equals(s)) {
                                option.setIsSelect("1");
                            }
                        }
                    }
                }
            }
        }
        return testQuestionsContents;
    }
}
