/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: TrExamOnlineReadOverController
 * Author:   phone
 * Date:     2018/3/29 20:37
 * Description: 阅卷
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.yizhi.application.exam.controller;


import com.yizhi.application.exam.constant.ExamConstant;
import com.yizhi.application.point.constant.MQqueuesEnum;
import com.yizhi.application.point.constant.PointEventEnum;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.event.EventWrapper;
import com.yizhi.core.application.publish.CloudEventPublisher;
import com.yizhi.core.application.task.AbstractTaskHandler;
import com.yizhi.core.application.task.TaskExecutor;
import com.yizhi.exam.application.feign.ExamAnswerClient;
import com.yizhi.exam.application.feign.ExamAuthorizeClient;
import com.yizhi.exam.application.feign.ExamClient;
import com.yizhi.exam.application.feign.ExamOnlineReadOverClient;
import com.yizhi.exam.application.vo.*;
import com.yizhi.exam.application.vo.domain.Exam;
import com.yizhi.exam.application.vo.domain.TrExamAuthorize;
import com.yizhi.point.application.feign.PointRedisFeignClients;
import com.yizhi.point.application.vo.PointParamVO;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.ReportClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.system.application.vo.ReportRangeAccountReqVO;
import com.yizhi.util.application.constant.QueueConstant;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.event.TrainingProjectEvent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 〈一句话功能简述〉<br>
 * 〈阅卷〉
 *
 * @author fanchunhui
 * @create 2018/3/29
 * @since 1.0.0
 */
@Api(tags = "管理端-阅卷接口", description = "管理端-阅卷接口")
@RestController
@RequestMapping("/manage/exam")
public class ExamOnlineReadOverController {

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

    @Autowired
    ExamOnlineReadOverClient examOnlineReadOverClient;

    @Autowired
    ExamClient examClient;

    @Autowired
    ExamAnswerClient examAnswerClient;

    @Autowired
    AccountClient accountClient;

    @Autowired
    ExamAuthorizeClient examAuthorizeClient;

    @Autowired
    PointRedisFeignClients pointRedisFeignClients;
/*
    @Autowired
    AmqpTemplate amqpTemplate;*/

    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private CloudEventPublisher cloudEventPublisher;

    @Autowired
    private ReportClient reportClient;

    @Value("${pc.host.url}")
    String pcHostUrl;

   /* @ApiOperation(value = "阅卷列表", notes = "阅卷列表",response = ExamDetailsMarkingVO.class)
    @GetMapping("/marking/list")
    public Response<ExamDetailsMarkingVO> getExamMarkingList(
            @ApiParam(value = "考试名称模糊查询") @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "每页条数，默认10") @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @ApiParam(value = "当前页数") @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo) {
        Pair<List<ExamDetailsMarkingVO>,Map<String,Integer>> pair;
        List<ExamDetailsMarkingVO> list = null;
        Map<String,Integer> page = null;
        try {
            Map<String,Object> map = examOnlineReadOverClient.getExamMarkingList(name,pageSize,pageNo,*//*ContextHolder.get().getCompanyId()*//*91L);
            if (null != map.get("list")){
                list = (List<ExamDetailsMarkingVO>) map.get("list");
            }
            if (null != map.get("page")){
                page = (Map<String, Integer>) map.get("page");
            }
            pair = new MutablePair<List<ExamDetailsMarkingVO>, Map<String, Integer>>(list, page);
            return Response.ok(pair);
        } catch (Exception e) {
            LOGGER.error("", e);
            // TODO Auto-generated catch block
            e.printStackTrace();
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }*/

    @ApiOperation(value = "答卷列表", notes = "答卷列表", response = ExamDetailsMarkingVO.class)
    @GetMapping("/marking/student/list")
    public Response<ExamOnlineReadOverVo> selectList(@ApiParam(value = "考试id", required = true) @RequestParam(name = "examId") Long examId,
                                                     @ApiParam(value = "用户名") @RequestParam(name = "userName", required = false) String userName,
                                                     @ApiParam(value = "姓名") @RequestParam(name = "name", required = false) String name,
                                                     @ApiParam(value = "部门") @RequestParam(name = "dept", required = false) String dept,
                                                     @ApiParam(value = "每页条数，默认10") @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                                     @ApiParam(value = "当前页数") @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo) {
        Pair<List<ExamOnlineReadOverVo>, Map<String, Integer>> pair;
        Map<String, Object> map;
        List<ExamOnlineReadOverVo> examOnlineReadOverVos = null;
        List<ExamOnlineReadOverVo> list = new ArrayList<ExamOnlineReadOverVo>();
        Map<Long, com.yizhi.system.application.vo.UserInfoVO> userInfoVOMap = null;
        try {
            com.yizhi.exam.application.vo.UserInfoVO userInfoVO = null;
            Map<String, Integer> page = new HashMap<String, Integer>();
            if (null != userName || null != name || null != dept) {
                userInfoVO = new com.yizhi.exam.application.vo.UserInfoVO();
                if (null != userName) {
                    userInfoVO.setName(userName);
                }
                if (null != name) {
                    userInfoVO.setFullName(name);
                }
                if (null != dept) {
                    userInfoVO.setOrgName(dept);
                }
                userInfoVO.setCompanyId(ContextHolder.get().getCompanyId());
                //根据查询条件查询所有用户信息
                com.yizhi.system.application.vo.UserInfoVO sysInfoVo = new com.yizhi.system.application.vo.UserInfoVO();
                BeanUtils.copyProperties(userInfoVO, sysInfoVo);
                userInfoVOMap = accountClient.getUser(sysInfoVo);
                if (null == userInfoVO || userInfoVOMap.size() == 0) {
                    return Response.ok(list, page);
                }
            }
            StudentListVO studentListVO = new StudentListVO();
            studentListVO.setExamId(examId);
            studentListVO.setPageNo(pageNo);
            studentListVO.setPageSize(pageSize);
            Map<Long, com.yizhi.exam.application.vo.UserInfoVO> examUserInfoVOMap = new HashMap<>();
            if (userInfoVOMap != null) {
                copyMapProperties(userInfoVOMap, examUserInfoVOMap);
            }
            studentListVO.setUserInfoVOMap(examUserInfoVOMap);
            //查询所有符合条件的答卷信息
            StudentListOutVO studentListOutVO = examOnlineReadOverClient.selectList(studentListVO);
            Map<Long, AccountVO> accountMapVO = new HashMap<Long, AccountVO>();
            if (studentListOutVO != null) {
                examOnlineReadOverVos = studentListOutVO.getExamOnlineReadOverVos();
                //遍历所有答卷根据AccountID获取用户名等信息
                for (ExamOnlineReadOverVo examOnlineReadOverVo : examOnlineReadOverVos) {
                    if (null != userInfoVO) {
                        //UserInfoVO userInfoVO1 = userInfoVOMap.get(examOnlineReadOverVo.getAccountId());
                        UserInfoVO userInfoVO1 = new UserInfoVO();
                        com.yizhi.system.application.vo.UserInfoVO examUserInfoVo = userInfoVOMap.get(examOnlineReadOverVo.getAccountId());
                        BeanUtils.copyProperties(examUserInfoVo, userInfoVO1);
                        if (null != userInfoVO1) {
                            examOnlineReadOverVo.setName(userInfoVO1.getFullName());
                            examOnlineReadOverVo.setUsername(userInfoVO1.getName());
                            examOnlineReadOverVo.setDepart(userInfoVO1.getOrgName());
                        }
                        list.add(examOnlineReadOverVo);
                        continue;
                    } else {
                        //将用户信息缓存起来，重复的就不调用服务接口
                        Long accountId = examOnlineReadOverVo.getAccountId();
                        AccountVO accountVO = accountMapVO.get(accountId);
                        if (accountVO == null) {
                            accountVO = accountClient.findById(accountId);
                            if (accountVO == null) {
                                accountMapVO.put(accountId, accountVO);
                            }
                        }
                        if (null != accountVO) {
                            examOnlineReadOverVo.setName(accountVO.getFullName());
                            examOnlineReadOverVo.setUsername(accountVO.getName());
                            examOnlineReadOverVo.setDepart(accountVO.getOrgName());
                        }
                        list.add(examOnlineReadOverVo);
                        continue;
                    }
                }
                Integer pageTotal = studentListOutVO.getPageTotal();
                page.put("pageNo", pageNo);
                page.put("pageSize", pageSize);
                page.put("pageTotal", pageTotal);
            }
            return Response.ok(list, page);
        } catch (Exception e) {
            LOGGER.error("", e);
            e.printStackTrace();
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(), ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

   /* public Response<ExamOnlineReadOverVo> getExamMarking(
            @ApiParam(value = "考试id", required = false) @RequestParam(name = "examId", required = true) Long examId,
            @ApiParam(value = "用户名", required = false) @RequestParam(name = "userName", required = false) String userName,
            @ApiParam(value = "姓名", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "部门", required = false) @RequestParam(name = "depart", required = false) String depart,
            @ApiParam(value = "每页条数，默认10", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @ApiParam(value = "当前页数", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo) {
        Pair<List<ExamOnlineReadOverVo>, Map<String, Integer>> pair = null;
        List<ExamOnlineReadOverVo> list = null;
        Map<String,Integer> page = null;
        try {
            Map<String,Object> map = examOnlineReadOverClient.getExamMarking(examId,userName,name,depart,pageSize,pageNo);
            if (null != map){
                if (map.containsKey("list")){
                    list = (List<ExamOnlineReadOverVo>) map.get("list");
                }
                if (map.containsKey("page")){
                    page = (Map<String, Integer>) map.get("page");
                }
            }else{
                return Response.fail(ReturnCode.RESOURCE_NOT_FOUND.getCode(),ReturnCode.RESOURCE_NOT_FOUND.getMsg());
            }
            pair = new MutablePair<List<ExamOnlineReadOverVo>, Map<String, Integer>>(list, page);
            return Response.ok(pair);
        } catch (Exception e) {
            LOGGER.error("", e);
            e.printStackTrace();
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }*/

    /**
     * 批阅答卷
     *
     * @return
     */
    @ApiOperation(value = "批阅答卷", notes = "批阅答卷", response = PaperInspectionVo.class)
    @GetMapping(value = "/marking/student")
    public Response<MarkStudentVO> findByExamVo(@RequestParam("id") Long id) {
        MarkStudentVO markStudentVO = null;
        try {
//            String accountName = ContextHolder.get().getAccountName();
            markStudentVO = examOnlineReadOverClient.markingStudent(id);
            if (null != markStudentVO && null != markStudentVO.getAccountId()) {
                AccountVO accountVO = accountClient.findById(markStudentVO.getAccountId());
                if (null != accountVO) {
                    markStudentVO.setAccountName(accountVO.getName());
                    markStudentVO.setName(accountVO.getFullName());
                    markStudentVO.setUserName(accountVO.getName());
                }
            }
            if (null != markStudentVO) {
                return Response.ok(markStudentVO);
            } else {
                return Response.fail(ReturnCode.RESOURCE_NOT_FOUND.getCode(), ReturnCode.RESOURCE_NOT_FOUND.getMsg());
            }

        } catch (Exception e) {
            LOGGER.error("", e);
            e.printStackTrace();
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(), ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    /**
     * 批阅答卷(保存)
     *
     * @return
     */
    @ApiOperation(value = "批阅答卷(保存)", notes = "批阅答卷(保存)")
    @PostMapping(value = "/marking/student/save")
    public Response<String> insertByFile(@RequestBody MarkStudentVO markStudentVO) {
        Integer point;
        try {
            Date time = new Date();
            RequestContext requestContext = ContextHolder.get();
            markStudentVO.setAccountId(requestContext.getAccountId());
            markStudentVO.setAccountName(requestContext.getAccountName());
            point = examOnlineReadOverClient.insertByFile(markStudentVO);
            MarkStudentVO over = examOnlineReadOverClient.getExamOnlineReadOverById(markStudentVO);
            if (over == null) {
                LOGGER.info("阅卷完毕发放积分失败，没找到答卷信息");
            }

            if (over != null) {
                LOGGER.info("阅卷完毕发放积分，开始");

                //考试通过发放积分
                try {
                    PointParamVO pointParamVO = new PointParamVO();
                    pointParamVO.setEventName(PointEventEnum.POINTEXAM.getKey());
                    pointParamVO.setActivityType("考试阅卷通过积分发放");
                    pointParamVO.setActivitySource("考试");
                    pointParamVO.setActivityName(over.getExamName());
                    pointParamVO.setScore(over.getSumScore().intValue());
                    pointParamVO.setReleaseCondition("范围发放");
                    pointParamVO.setReleaseRules("按照范围取积分");
                    pointParamVO.setCreatePointTime(time);
                    pointParamVO.setSourceId(over.getExamId());
                    pointParamVO.setOperatingPoint(point);
                    pointParamVO.setAccountId(over.getAccountId());
                    pointParamVO.setAccountName(over.getAccountName());
                    pointParamVO.setOrgId(requestContext.getOrgId());
                    pointParamVO.setSiteId(requestContext.getSiteId());
                    pointParamVO.setCompanyId(requestContext.getCompanyId());
                    String sitePointId = null;
                    if (null != point && point > 0) {
                        sitePointId = pointRedisFeignClients.addPointRedis(pointParamVO);
                    }

                    String sitePointId1 = pointRedisFeignClients.addPointRedis(pointParamVO);
                    if (null != sitePointId) {
                        //amqpTemplate.convertAndSend(MQqueuesEnum.EXAM.getKey(), sitePointId);
                    }
                    if (null != sitePointId1) {
                        //amqpTemplate.convertAndSend(MQqueuesEnum.EXPERIENCEEXAM.getKey(), sitePointId1);
                    }
                    LOGGER.info("阅卷完毕发放积分，成功");
                } catch (Exception ep) {
                    LOGGER.error("阅卷积分发放失败：", ep);
                }
            }

            // 阅卷完成,考试通过向培训项目发送消息，告知业务已经完成
            try {
                boolean isFinished;
                if (null != over & over.getIsQualified() == 1) {
                    isFinished = true;
                    LOGGER.error("阅卷:(" + over.getExamId() + ") 通过，给trainingProject发送消息");
                    Float value = over.getSumScore().floatValue();
                    boolean finalIsFinished = isFinished;
                    taskExecutor.asynExecute(new AbstractTaskHandler() {
                        @Override
                        public void handle() {
                            try {
                                cloudEventPublisher.publish(QueueConstant.TRAINING_PROJECT_EVENT_QUEUE,
                                        new EventWrapper<TrainingProjectEvent>(over.getExamId(),
                                                TrainingProjectEvent.getInstance(over.getExamId(), ExamConstant.EXAM_TRANINNING_TYPE,
                                                        over.getAccountId(), time,
                                                        requestContext.getSiteId(), value, finalIsFinished)));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }

            } catch (Exception e) {
                LOGGER.error("阅卷:(" + over.getExamId() + ") 通过，给trainingProject发送消息失败：", e);
            }

            if (null != point) {
                return Response.ok("保存成功！");
            } else {
                return Response.fail(ReturnCode.BIZ_FAIL.getCode(), ReturnCode.BIZ_FAIL.getMsg());
            }
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(), ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }
    /*@ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "答卷ID外键",paramType = "body"),
            @ApiImplicitParam(name = "answerQuestionId",value = "答案题目_ID，外键",paramType = "body"),
            @ApiImplicitParam(name = "accountId",value = "学员_ID",paramType = "body"),
            @ApiImplicitParam(name = "accountName",value = "学员_用户名",paramType = "body"),
            @ApiImplicitParam(name = "name",value = "学员_姓名",paramType = "body"),
            @ApiImplicitParam(name = "examId",value = "考试主键_ID，外键",paramType = "body"),
            @ApiImplicitParam(name = "subjectId",value = "题目主键_ID，外键",paramType = "body"),
            @ApiImplicitParam(name = "sumScore",value = "成绩总分数",paramType = "body"),
            @ApiImplicitParam(name = "score",value = "考试总分数",paramType = "body"),
            @ApiImplicitParam(name = "objectiveScore",value = "客观题分数，考试中单选题，多选题，判断题，不定项选择题的总分",paramType = "body"),
            @ApiImplicitParam(name = "subjectiveScore",value = "主观题分数，问答题总分",paramType = "body"),
            @ApiImplicitParam(name = "state",value = "状态，0待阅卷 1已阅卷，2重新阅卷 默认0",paramType = "body",defaultValue = "0"),
            @ApiImplicitParam(name = "listExam",value = "主观试题",paramType = "body"),
            @ApiImplicitParam(name = "readOveUserId",value = "阅卷人",paramType = "body"),
            @ApiImplicitParam(name = "readOveUserName",value = "阅卷人姓名",paramType = "body"),
            @ApiImplicitParam(name = "firstReadOveTime",value = "首次阅卷时间，只记录第一次阅卷的时间",paramType = "body"),
            @ApiImplicitParam(name = "readOveTime",value = "阅卷时间，多次阅卷更新此时间",paramType = "body"),
            @ApiImplicitParam(name = "sumNum",value = "阅卷合计次数",paramType = "body"),
    })
    @PostMapping(value = "/marking/student/save")
    public Response<String>  insertByFile(@RequestBody PaperInspectionVo paperInspectionVo){
        boolean result;
        try {
            RequestContext requestContext = ContextHolder.get();
            paperInspectionVo.setAccountId(requestContext.getAccountId());
            paperInspectionVo.setAccountName(requestContext.getAccountName());
            paperInspectionVo.setCompanyId(requestContext.getCompanyId());
            paperInspectionVo.setOrgId(requestContext.getOrgId());
            paperInspectionVo.setSiteId(requestContext.getSiteId());
            result = examOnlineReadOverClient.insertByFile(paperInspectionVo);
            return Response.ok(result);
        }catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }*/

    @ApiOperation(value = "阅卷列表", notes = "阅卷列表", response = ExamDetailsMarkingVO.class)
    @GetMapping("/marking/list")
    public Response<ExamDetailsMarkingVO> markAnswer(ContextAndPageSizeVO contextAndPageSizeVO) {
        List<ExamDetailsMarkingVO> examDetailsMarkingVOS = new ArrayList<ExamDetailsMarkingVO>();
        ExamDetailsMarkingVO examDetailsMarkingVO;
        Pair<List<ExamDetailsMarkingVO>, Map<String, Integer>> pair;
        int submitCount;
        int readCount;
        int shouldExamNum = 0;
        RequestContext requestContext = ContextHolder.get();
        Map<Long, Integer> countMap = new HashMap<Long, Integer>();
//        List<Long> orgAndAccountIds = new ArrayList<>();
        try {
            Long companyId = requestContext.getCompanyId();
            Long siteId = requestContext.getSiteId();
            List<Long> orgIds = null;
            List<Long> relationIds = new ArrayList<Long>();
            List<Long> accountIds = new ArrayList<Long>();
            contextAndPageSizeVO.setCompanyId(companyId);
            contextAndPageSizeVO.setSiteId(siteId);
            if (!requestContext.isAdmin() && !CollectionUtils.isEmpty(requestContext.getOrgIds())) {
                orgIds = requestContext.getOrgIds();
                contextAndPageSizeVO.setOrgIds(orgIds);
            }
            List<Exam> exams = examClient.selectExamListByName(contextAndPageSizeVO);   //根据考试名称查询所有符合条件的考试
            int pageTotal = examClient.selectExamListByNameCount(contextAndPageSizeVO);
            List<Long> examIds = exams.stream().map(Exam::getId).collect(Collectors.toList());
            Map<Long, Integer> qulifiedNumMap = new HashMap<>();

            //将合格人数装在map里,便于后面组装直接取数据 ding添加于2019.06.06
            if (CollectionUtils.isNotEmpty(examIds)) {
                qulifiedNumMap = examOnlineReadOverClient.getQualifiedNum(examIds);
            }
            Integer visibleRange = null;
            for (Exam exam : exams) {
                relationIds.clear();
                accountIds.clear();

                examDetailsMarkingVO = new ExamDetailsMarkingVO();
                examDetailsMarkingVO.setId(exam.getId());
                examDetailsMarkingVO.setName(exam.getName());
                examDetailsMarkingVO.setStartTime(exam.getStartTime());
                examDetailsMarkingVO.setEndTime(exam.getEndTime());
                examDetailsMarkingVO.setCreateTime(exam.getCreateTime());

                //如果map里有合格人数直接取出来,否则就直接赋值0
                if (null != qulifiedNumMap && null != qulifiedNumMap.get(exam.getId())) {
                    examDetailsMarkingVO.setQualifidNum(qulifiedNumMap.get(exam.getId()));
                } else {
                    examDetailsMarkingVO.setQualifidNum(0);
                }
                submitCount = examAnswerClient.submitCount(exam.getId()); //查询交卷人数
                examDetailsMarkingVO.setCommitExamNum(submitCount);
                readCount = examOnlineReadOverClient.readCount(exam.getId());//查询阅卷人数
                examDetailsMarkingVO.setIsReadExamNum(readCount);


                //可见范围为空，默认全平台可见
                visibleRange = exam.getVisibleRange();
                if (visibleRange == null) {
                    visibleRange = 1;
                }
                //全平台可见
                if (visibleRange == 1) {
                    Long examCompanyId = exam.getCompanyId();
                    Long examSiteId = exam.getSiteId();
                    Integer count = countMap.get(examSiteId);
                    if (count == null) {
                        count = accountClient.getSiteAccountNum(examSiteId, examCompanyId);
                        countMap.put(examSiteId, count);
                    }
                    shouldExamNum = count;
                    LOGGER.info("************ 全平台可见 examCompanyId:{},examSiteId{},shouldExamNum{}", examCompanyId, examSiteId, shouldExamNum);
                } else if (exam.getVisibleRange() == 2) {
                    //指定学员可见
                    List<TrExamAuthorize> trExamAuthorizes = examAuthorizeClient.examCount(exam.getId());//查询应考人数列表
                    if (CollectionUtils.isNotEmpty(trExamAuthorizes)) {
                        List<Long> rangeAccountIds = new ArrayList();
                        List<Long> rangeOrgIds = new ArrayList();
                        for (TrExamAuthorize trExamAuthorize : trExamAuthorizes) {
                            //1组织,2用户
                            if (trExamAuthorize.getType() == 1) {
                                rangeOrgIds.add(trExamAuthorize.getRelationId());
                            } else if (trExamAuthorize.getType() == 2) {
                                rangeAccountIds.add(trExamAuthorize.getRelationId());
                            }
                        }
                        ReportRangeAccountReqVO reqVO = new ReportRangeAccountReqVO();
                        reqVO.setSiteId(exam.getSiteId());
                        reqVO.setAccountIds(rangeAccountIds);
                        reqVO.setOrgIds(rangeOrgIds);
                        LOGGER.info("-------------指定范围 siteId:{},setOrgIdsAndAccountIds:{}", exam.getSiteId(), accountIds, orgIds);
                        shouldExamNum = Math.toIntExact(reportClient.getRangeAccountCountNum(reqVO));
                    }
//                    for (TrExamAuthorize trExamAuthorize : trExamAuthorizes) {
//                        switch (trExamAuthorize.getType()) {
//                            case 1:
//                                relationIds.add(trExamAuthorize.getRelationId());
//                                break;
//                            case 2:
//                                accountIds.add(trExamAuthorize.getRelationId());
//                                break;
//                            default:
//                                break;
//                        }
//                    }
//                    try {
//                        SiteOrgIdModel model = new SiteOrgIdModel();
//                        model.setSiteId(requestContext.getSiteId());
//                        model.setOrgIds(relationIds);
//                        Integer count = accountClient.getSiteOrgWithChildAccountNum(model);
//                        shouldExamNum = accountIds.size();
//                        if(count != null){
//                        	 shouldExamNum += count;
//                        }
//                    //LOGGER.info("************ 指定学员可见 getSiteId:{},examSiteId{},shouldExamNum{}", requestContext.getSiteId(), orgIds.toString(), shouldExamNum);
//                } catch(Exception e){
//                    e.printStackTrace();
//                    LOGGER.error("调用accountClient.getSiteOrgWithChildAccountNum接口失败", e);
//                }
                }
                examDetailsMarkingVO.setShouldExamNum(shouldExamNum);
                examDetailsMarkingVOS.add(examDetailsMarkingVO);
            }
            Map<String, Integer> page = new HashMap<String, Integer>();
            page.put("pageNo", contextAndPageSizeVO.getPageNo());
            page.put("pageSize", contextAndPageSizeVO.getPageSize());
            page.put("pageTotal", pageTotal);
            pair = new MutablePair<List<ExamDetailsMarkingVO>, Map<String, Integer>>(examDetailsMarkingVOS, page);
            return Response.ok(pair);
        } catch (
                Exception e) {
            e.printStackTrace();
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "导出考试结果", notes = "导出考试结果")
    @GetMapping("/marking/export")
    public Response<String> studentExamExport(@ApiParam(name = "examId", required = true) @RequestParam(name = "examId", required = true) Long examId) {
        String serialNo = examOnlineReadOverClient.studentExamExport(examId);
        String fileUril = pcHostUrl+"/api/v1/buckets/upload/objects/download/?preview=true&prefix="+serialNo+".xlsx";
        return Response.ok(fileUril);
    }


    //copy map properties
    public void copyMapProperties(Object source, Object target) {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Map<Long, Object> sourceMap = (Map<Long, Object>) source;
        Map<Long, Object> targetMap = (Map<Long, Object>) target;
        sourceMap.forEach((key, value) -> {
            targetMap.put(key, value);
        });
    }
}
