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

import com.baomidou.mybatisplus.plugins.Page;

import com.yizhi.application.accountUtil.AuthorizeQueryAccount;
import com.yizhi.application.exam.vo.ExamVO;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.exam.application.feign.ExamAuthorizeClient;
import com.yizhi.exam.application.feign.ExamClient;
import com.yizhi.exam.application.feign.ExamManageClient;
import com.yizhi.exam.application.vo.*;
import com.yizhi.exam.application.vo.domain.Exam;
import com.yizhi.exam.application.vo.exam.ExamQuestionListVO;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.GroupClient;
import com.yizhi.system.application.system.remote.OrganizationClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.system.application.vo.OrgVO;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 〈考试,管理端〉<br>
 * 〈〉
 *
 * @author fanchunhui
 * @create 2018/3/29
 * @since 1.0.0
 */

@Api(tags = "管理端-考试接口", description = "管理端-考试接口")
@RestController("webExamManageController")
@RequestMapping("/manage/exam")
public class ExamManageController {

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

    @Autowired
    ExamManageClient examManageClient;

    @Autowired
    AccountClient accountClient;

    @Autowired
    GroupClient groupClient;

    @Autowired
    OrganizationClient organizationClient;

//    @Autowired
//    SystemMessageClient systemMessageClient;

    @Autowired
    ExamClient examClient;

    @Autowired
    ExamAuthorizeClient examAuthorizeClient;

    @Autowired
    private AuthorizeQueryAccount queryAccount;


    @ApiOperation(value="创建考试-基本信息新增, 编辑", notes="返回考试id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "考试名称",paramType = "body"),
            @ApiImplicitParam(name = "description",value = "考试说明",paramType = "body"),
            @ApiImplicitParam(name = "startTime",value = "开始时间，字符串， 2018-3-14 14:08",paramType = "body"),
            @ApiImplicitParam(name = "endTime",value = "结束时间，字符串， 2018-3-14 14:08",paramType = "body"),
            @ApiImplicitParam(name = "duration",value = "答卷时长，0无限制 >0有限制(分钟)",paramType = "body"),
            @ApiImplicitParam(name = "answerNum",value = "答题次数，0无限制 >0有限次(次)",paramType = "body"),
            @ApiImplicitParam(name = "examNum",value = "考试次数，允许考试参加的次数",paramType = "body"),
            @ApiImplicitParam(name = "qualifiedScore",value = "合格分，本次考试的合格分",paramType = "body"),
            @ApiImplicitParam(name = "makeStrategy",value = "出题策略，1手动出题 2系统出题",paramType = "body"),
            @ApiImplicitParam(name = "trainingProjectId",value = "培训项目ID",paramType = "body")
    })
    @PostMapping(value={"/info/insert", "/info/update"})
    public Response<Long> insertOrUpdateBaseInfo(@RequestBody BaseInfoVO vo){
        Long examId;
        try{

        	RequestContext requestContext = ContextHolder.get();
        	if(null == requestContext){
        		return  Response.fail(ReturnCode.SAVE_FAIL.getCode(),ReturnCode.SAVE_FAIL.getMsg());
        	}

        	vo.setAccountId(requestContext.getAccountId());
        	vo.setAccountName(requestContext.getAccountName());
        	vo.setCompanyId(requestContext.getCompanyId());
        	vo.setSiteId(requestContext.getSiteId());
        	vo.setOrgId(requestContext.getOrgId());
            examId = examManageClient.insertOrUpdateBaseInfo(vo);
            if (examId > 0){
                return Response.ok(examId);
            }else {
                return  Response.fail(ReturnCode.SAVE_FAIL.getCode(),ReturnCode.SAVE_FAIL.getMsg());
            }
        }catch (Exception e) {
            LOGGER.error("创建考试-基本信息保存:" + e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

   /* @ApiOperation(value="创建考试-添加试题保存", notes="返回考试id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysMakeStrategy",value = "系统出题_出题策略，1手动出题（每个学员使用同一份试卷） 2系统出题（每个学员使用不同试卷）",paramType = "body"),
            @ApiImplicitParam(name = "stemSort",value = "题干排序，1默认排序 2题型排序 3随机排序",paramType = "body"),
            @ApiImplicitParam(name = "optionSort",value = "选项排序，1默认排序 2随机排序",paramType = "body"),
            @ApiImplicitParam(name = "examQuestionVoList",value = "试题列表",paramType = "body"),
            @ApiImplicitParam(name = "trExamSystemQuestionVoList",value = "系统出题规则",paramType = "body"),
            @ApiImplicitParam(name = "trExamQuestionSortVoList",value = "题型排序",paramType = "body")
    })
    @PostMapping("/question/select/insert")
    public Response<Long> updateExamQuestion(@RequestBody AddQuestionVO vo){
        Long examId;
        try{
            examId = examManageClient.updateExamQuestion(vo);
            if (examId > 0){
                return Response.ok(examId);
            }else {
                return  Response.fail(ReturnCode.SAVE_FAIL.getCode(),ReturnCode.SAVE_FAIL.getMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("创建考试-基本信息保存:" + e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }*/

    @ApiOperation(value="创建考试-添加试题-出题规则列表", notes="返回出题规则列表", response= TrExamSystemQuestionVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId",value = "考试ID",paramType = "body")
    })
    @PostMapping("/system/list")
    public Response<TrExamSystemQuestionVO> listTrExamSystemQuestion(
            @ApiParam(name = "examId", value = "考试id", required = true)@RequestBody ExamVO exam){
        List<TrExamSystemQuestionVO> list = null;
        try{
            list = examManageClient.listTrExamSystemQuestion(exam.getExamId());
            if (list.size() > 0){
                return Response.ok(list);
            }else{
                return Response.fail(ReturnCode.RESOURCE_NOT_FOUND.getCode(),ReturnCode.RESOURCE_NOT_FOUND.getMsg());
            }
        }catch (Exception e) {
            LOGGER.error("创建考试:" + e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value="创建考试-添加试题-题干排序-题型排序列表", notes="返回题型排序", response= TrExamQuestionSortVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId",value = "考试ID",paramType = "body",required = true)
    })
    @PostMapping("/question/sort/list")
    public Response<TrExamQuestionSortVO> listTrExamQuestionSort(@RequestBody ExamVO exam){
        List<TrExamQuestionSortVO> list = null;
        try{
            list = examManageClient.listTrExamQuestionSort(exam.getExamId());
            if (list.size() > 0){
                return Response.ok(list);
            }else{
                return Response.fail(ReturnCode.RESOURCE_NOT_FOUND.getCode(),ReturnCode.RESOURCE_NOT_FOUND.getMsg());
            }
        }catch (Exception e) {
            LOGGER.error("创建考试-添加试题-题干排序-题型排序列表:" + e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value="创建考试-考试策略 列表", notes="返回考试策略 列表", response= ExamStrategyVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId",value = "考试ID",paramType = "body",required = true)
    })
    @PostMapping("/strategy/list")
    public Response<ExamStrategyVO> listExamStrategy(@RequestBody ExamVO exam){
        ExamStrategyVO examStrategyVo = null;
        try{
            examStrategyVo = examManageClient.listExamStrategy(exam.getExamId());
            if (null != examStrategyVo){
                return Response.ok();
            }else {
                return Response.fail(ReturnCode.RESOURCE_NOT_FOUND.getCode(),ReturnCode.RESOURCE_NOT_FOUND.getMsg());
            }
        }catch (Exception e) {
            LOGGER.error("创建考试-考试策略 列表:" + e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value="创建考试-考试策略 保存, 预览", notes="返回考试Id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "visibleRange",value = "考试范围，1平台用户可见 2指定用户可见",paramType = "body"),
            @ApiImplicitParam(name = "pageMode",value = "呈现样式，1整页呈现 2逐题呈现",paramType = "body"),
            @ApiImplicitParam(name = "isAnswerPaper",value = "显示答卷，0不显示 1交卷后显示 2考试结束后显示",paramType = "body"),
            @ApiImplicitParam(name = "isScore",value = "显示成绩，0不显示 1交卷后显示 2考试结束后显示",paramType = "body"),
            @ApiImplicitParam(name = "isAnswer",value = "显示答案，0不显示 1交卷后显示 2考试结束后显示",paramType = "body"),
            @ApiImplicitParam(name = "isAnalysis",value = "显示解析，0不显示 1交卷后显示 2考试结束后显示",paramType = "body"),
            @ApiImplicitParam(name = "isPaperid",value = "显示通用分评价，0不显示 1交卷后显示 2考试结束后显示",paramType = "body"),
            @ApiImplicitParam(name = "isPoint",value = "是否使用积分，0不使用 1使用，默认0",paramType = "body",defaultValue = "0"),
            @ApiImplicitParam(name = "remind",value = "提醒设置，0否 1是，默认0",paramType = "body",defaultValue = "0"),
            @ApiImplicitParam(name = "trExamAuthorizeVoList",value = "考试人员范围",paramType = "body"),
            @ApiImplicitParam(name = "trExamScoreEvaluateVoList",value = "考试分数通用评价",paramType = "body"),
            @ApiImplicitParam(name = "trExamPointVoList",value = "考试积分",paramType = "body"),
            @ApiImplicitParam(name = "trExamRemindVO",value = "提醒设置",paramType = "body")
    })
    @PostMapping(value={"/strategy/insert", "/preview"})
    public Response<Long> updateExamStrategy(@RequestBody ExamStrategyVO vo){
        Long examId = null;
        try{
        	SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            RequestContext context = ContextHolder.get();
            Long accountId = context.getAccountId();
            String accountName = context.getAccountName();
            vo.setAccountId(accountId);
            vo.setAccountName(accountName);
            if(vo.getVisibleRange() == 1){
                RequestContext requestContext = ContextHolder.get();
                vo.setSiteId(requestContext.getSiteId());
            }

            examId = examManageClient.updateExamStrategy(vo);
//            if(examId != null){
//            	//判断是否设置了提醒（0否 1是）
//            	Integer remind = vo.getRemind();
//                if(null != vo.getTrExamRemindVO() && remind != null && remind != 0){
//                	try{
//    	                MessageReceiverVO messageReceiverVO;
//    	                List<Integer> sendTypes = null;
//    	                List<MessageReceiverVO> messageReceiverVOS = null;
//    	                MessageVO messageVO;
//    	                List<TrExamRemindTimeVO> trExamRemindTimeVoList = vo.getTrExamRemindVO().getTrExamRemindTimeVoList();
//    	                Exam exam = examClient.selectExamById(vo.getId());
//    	                List<MessageVO> messageVOS = new ArrayList<MessageVO>();
//    	                String content = null;
//    	                //循环发送提醒
//    	                for (TrExamRemindTimeVO trExamRemindTimeVO: trExamRemindTimeVoList) {
//    	                	sendTypes = new ArrayList<Integer>();
//    	                    messageVO = new MessageVO();
//    	                    messageVO.setSubject(exam.getName());            					//消息标题
//    	                    messageVO.setMessageType(Integer.valueOf(MessageType.KS.getKey())); //消息类型(0自定义消息1学习计划2考试3调研4投票5报名6作业7签到8项目)
//    	                    messageVO.setTaskId(vo.getId());                                    //关联业务id,自定义消息为0
//    	                    content = vo.getTrExamRemindVO().getContent();
//    	                    content = replaceContent(content, exam, formatDate.format(exam.getStartTime()), formatDate.format(exam.getEndTime()));
//    	                    messageVO.setContext(content);          //消息内容
//    	                    int type = trExamRemindTimeVO.getType();
//    	                    //1开始前发送  2结束前发送  3自定义时间  (发生时间)
//    	                    messageVO.setAheadType(trExamRemindTimeVO.getTriggerTime());        //提前时间类型
//    	                    if(type == 1){
//    	                        messageVO.setHappenTime(exam.getStartTime());
//    	                    }else if(type == 2){
//    	                        messageVO.setHappenTime(exam.getEndTime());
//    	                    }else if(type == 3){
//    	                    	if(!StringUtils.isBlank(trExamRemindTimeVO.getCustomDate())){
//    	                    		 messageVO.setHappenTime(formatDate.parse(trExamRemindTimeVO.getCustomDate()));
//    	                    	}
//    	                        messageVO.setAheadType(AheadType.ONTIME.getCode()); //时间是自定义时，设置默认值
//    	                        LOGGER.info("now:{} ~ getCustomDate:{} ~ getCustomDateFormat:{}", new Date(), trExamRemindTimeVO.getCustomDate(), formatDate.parse(trExamRemindTimeVO.getCustomDate()));
//    	                    }
//
//    	                    //1全平台可见 2指定用户可见
//    	                    if(exam.getVisibleRange() == 1){
//    	                        messageVO.setVisibleRange(Integer.valueOf(VisibleRange.ALL.getKey()));
//    	                    }else if(exam.getVisibleRange() == 2){
//    	                        List<TrExamAuthorize> trExamAuthorizes = examAuthorizeClient.examCount(vo.getId());
//    	                        messageReceiverVOS = new ArrayList<MessageReceiverVO>();
//    	                        for (TrExamAuthorize examAuthorize:trExamAuthorizes){
//    	                            messageReceiverVO = new MessageReceiverVO();
//    	                            if(examAuthorize.getType() == 1){//用户
//    	                                messageReceiverVO.setType(2);
//    	                            }else if(examAuthorize.getType() == 2){//部门
//    	                                messageReceiverVO.setType(1);
//    	                            }else if(examAuthorize.getType() == 3){//用户组
//    	                                messageReceiverVO.setType(3);
//    	                            }
//    	                            messageReceiverVO.setReceiverId(examAuthorize.getRelationId());
//    	                            messageReceiverVOS.add(messageReceiverVO);
//    	                        }
//    	                        messageVO.setReceiverVOs(messageReceiverVOS);       //关联人列表
//    	                    }
//
//    	                    //添加提醒消息类型
//    	                    String msgTypes = vo.getTrExamRemindVO().getType();
//    	                    if(msgTypes != null){
//    	                        List<String> strs = Arrays.asList(msgTypes.split(","));
//                                for (String str: strs) {
//                                    sendTypes.add(Integer.valueOf(str));
//                                }
//                                messageVO.setSendTypes(sendTypes);
//    	                    }
//
//    	                    messageVOS.add(messageVO);
//    	                }
//
//    	                LOGGER.info("调用考试提醒服务");
//    	                systemMessageClient.add(messageVOS);
//    	                LOGGER.info("调用考试提醒服务，成功");
//    	            }catch (Exception e){
//                    	LOGGER.info("调用考试提醒服务，失败");
//                        e.printStackTrace();
//                    }
//                } else {
//                	//删除提醒服务的内容
//
//                }
//            }
            return Response.ok(examId);
        }catch (Exception e) {
            LOGGER.error("创建考试-考试策略 保存:" + e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value="复制考试", notes="返回考试基本信息", response=BaseInfoVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId",value = "考试ID")
    })
    @PostMapping("/copy")
    public Response<String> copyExamRelated(@RequestBody Exam exam){
        boolean result = false;
        RequestContext requestContext = ContextHolder.get();
        try{
            Long accountId = requestContext.getAccountId();
            String accountName = requestContext.getAccountName();
            exam.setCreateByName(accountName);
            exam.setCreateById(accountId);
            result = examManageClient.copyExamRelated(exam);
            return Response.ok(result);
        }catch (Exception e) {
            LOGGER.error("创建考试-复制考试:" + e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value="发布考试", notes="返回考试id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "主键ID",paramType = "body"),
            @ApiImplicitParam(name = "visibleRange",value = "考试范围，1平台用户可见 2指定用户可见",paramType = "body"),
            @ApiImplicitParam(name = "pageMode",value = "呈现样式，1整页呈现 2逐题呈现",paramType = "body"),
            @ApiImplicitParam(name = "isAnswerPaper",value = "显示答卷，0不显示 1交卷后显示 2考试结束后显示",paramType = "body"),
            @ApiImplicitParam(name = "isScore",value = "显示成绩，0不显示 1交卷后显示 2考试结束后显示",paramType = "body"),
            @ApiImplicitParam(name = "isAnswer",value = "显示答案，0不显示 1交卷后显示 2考试结束后显示",paramType = "body"),
            @ApiImplicitParam(name = "isAnalysis",value = "显示解析，0不显示 1交卷后显示 2考试结束后显示",paramType = "body"),
            @ApiImplicitParam(name = "isPaperid",value = "显示通用分评价，0不显示 1交卷后显示 2考试结束后显示",paramType = "body"),
            @ApiImplicitParam(name = "isPoint",value = "是否使用积分，0不使用 1使用，默认0",paramType = "body",defaultValue = "0"),
            @ApiImplicitParam(name = "remind",value = "提醒设置，0否 1是，默认0",paramType = "body",defaultValue = "0"),
            @ApiImplicitParam(name = "trExamAuthorizeVoList",value = "考试人员范围",paramType = "body"),
            @ApiImplicitParam(name = "trExamScoreEvaluateVoList",value = "考试分数通用评价",paramType = "body"),
            @ApiImplicitParam(name = "trExamPointVoList",value = "考试积分",paramType = "body"),
            @ApiImplicitParam(name = "trExamRemindVO",value = "提醒设置",paramType = "body")
    })
    @PostMapping(value={"/release"})
    public Response<Long> releaseExamRelated(@RequestBody ExamStrategyVO vo){
        Long examId = null;
        try{
        	SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        	RequestContext requestContext = ContextHolder.get();
        	Long accountId =1314L; //requestContext.getAccountId();
        	String accountName ="1314"; //requestContext.getAccountName();
        	vo.setAccountName(accountName);
        	vo.setAccountId(accountId);
            examId=examManageClient.updateExamStrategy(vo);//先保存
        	String s=examClient.checkScore(examId);
            if(!s.equals("ok"))
                return Response.fail(s);
            examId = examManageClient.releaseExamRelated(vo);
            if(examId != null){
            	//判断是否设置了提醒（0否 1是）
            	Integer remind = vo.getRemind();
//                if(null != vo.getTrExamRemindVO() && remind != null && remind != 0){
//                	try{
//    	                MessageReceiverVO messageReceiverVO;
//    	                List<Integer> sendTypes = null;
//    	                List<MessageReceiverVO> messageReceiverVOS = null;
//    	                MessageVO messageVO;
//    	                List<TrExamRemindTimeVO> trExamRemindTimeVoList = vo.getTrExamRemindVO().getTrExamRemindTimeVoList();
//    	                Exam exam = examClient.selectExamById(vo.getId());
//    	                List<MessageVO> messageVOS = new ArrayList<MessageVO>();
//    	                String content = null;
//    	                //循环发送提醒
//    	                for (TrExamRemindTimeVO trExamRemindTimeVO: trExamRemindTimeVoList) {
//    	                	sendTypes = new ArrayList<Integer>();
//    	                    messageVO = new MessageVO();
//    	                    messageVO.setSubject(exam.getName());            					//消息标题
//    	                    messageVO.setMessageType(Integer.valueOf(MessageType.KS.getKey())); //消息类型(0自定义消息1学习计划2考试3调研4投票5报名6作业7签到8项目)
//    	                    messageVO.setTaskId(vo.getId());                                    //关联业务id,自定义消息为0
//    	                    content = vo.getTrExamRemindVO().getContent();
//    	                    content = replaceContent(content, exam, formatDate.format(exam.getStartTime()), formatDate.format(exam.getEndTime()));
//    	                    messageVO.setContext(content);          //消息内容
//    	                    int type = trExamRemindTimeVO.getType();
//    	                    //1开始前发送  2结束前发送  3自定义时间  (发生时间)
//    	                    messageVO.setAheadType(trExamRemindTimeVO.getTriggerTime());        //提前时间类型
//    	                    if(type == 1){
//    	                        messageVO.setHappenTime(exam.getStartTime());
//    	                    }else if(type == 2){
//    	                        messageVO.setHappenTime(exam.getEndTime());
//    	                    }else if(type == 3){
//    	                    	if(!StringUtils.isBlank(trExamRemindTimeVO.getCustomDate())){
//    	                    		Date happTime = formatDate.parse(trExamRemindTimeVO.getCustomDate());
//    	                    		 messageVO.setHappenTime(happTime);
//    	                    		 LOGGER.info("getCustomDate String ~ {}", trExamRemindTimeVO.getCustomDate());
//    	                    		 LOGGER.info("getCustomDate format ~ {}", happTime);
//    	                    	}
//    	                        messageVO.setAheadType(AheadType.ONTIME.getCode()); //时间是自定义时，设置默认值
//    	                    }
//
//    	                    //1全平台可见 2指定用户可见
//    	                    if(exam.getVisibleRange() == 1){
//    	                        messageVO.setVisibleRange(Integer.valueOf(VisibleRange.ALL.getKey()));
//    	                    }else if(exam.getVisibleRange() == 2){
//    	                        List<TrExamAuthorize> trExamAuthorizes = examAuthorizeClient.examCount(vo.getId());
//    	                        messageReceiverVOS = new ArrayList<MessageReceiverVO>();
//    	                        for (TrExamAuthorize examAuthorize:trExamAuthorizes){
//    	                            messageReceiverVO = new MessageReceiverVO();
//    	                            if(examAuthorize.getType() == 1){//用户
//    	                                messageReceiverVO.setType(2);
//    	                            }else if(examAuthorize.getType() == 2){//部门
//    	                                messageReceiverVO.setType(1);
//    	                            }else if(examAuthorize.getType() == 3){//用户组
//    	                                messageReceiverVO.setType(3);
//    	                            }
//    	                            messageReceiverVO.setReceiverId(examAuthorize.getRelationId());
//    	                            messageReceiverVOS.add(messageReceiverVO);
//    	                        }
//    	                        messageVO.setReceiverVOs(messageReceiverVOS);       //关联人列表
//    	                    }
//
//    	                    //添加提醒消息类型
//    	                    String msgTypes = vo.getTrExamRemindVO().getType();
//    	                    if(msgTypes != null){
//    	                        List<String> strs = Arrays.asList(msgTypes.split(","));
//                                for (String str: strs) {
//                                    sendTypes.add(Integer.valueOf(str));
//                                }
//                                messageVO.setSendTypes(sendTypes);
//    	                    }
//
//    	                    messageVOS.add(messageVO);
//    	                }
//
//    	                LOGGER.info("调用考试提醒服务");
//    	                systemMessageClient.add(messageVOS);
//    	                LOGGER.info("调用考试提醒服务，成功");
//    	            }catch (Exception e){
//                    	LOGGER.info("调用考试提醒服务，失败");
//                        e.printStackTrace();
//                    }
//                } else {
                	//删除提醒服务的内容

                }

                //开启考试提醒Job
//                try {
//            		boolean result = systemMessageClient.up(examId);
//            		if(!result){
//            			LOGGER.info("开启考试{}提醒失败", examId);
//            		}
//            	} catch(Exception e){
//            		LOGGER.error("开启考试{}提醒异常", examId);
//            		e.printStackTrace();
//            	}
//            }
            return Response.ok(examId);
        }catch (Exception e) {
           e.printStackTrace();
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value="考试试题列表", notes="返回考试试题列表", response= LibrarySubjectVO.class)
    @GetMapping("/question/select/list")
    public Response<LibrarySubjectVO> listExamQuestion(
            ContextAndPageSizeVO contextAndPageSizeVO){
        Page<SelectQuestionVO> list = null;
        Map<String, Object> map = new HashMap<String, Object>();
        try{
            RequestContext requestContext = ContextHolder.get();
            Long companyId = requestContext.getCompanyId();
            Long siteId = requestContext.getSiteId();
            List<Long> orgIds = null;
            contextAndPageSizeVO.setSiteId(siteId);
            contextAndPageSizeVO.setCompanyId(companyId);
            if(!requestContext.isAdmin() && !CollectionUtils.isEmpty(requestContext.getOrgIds())){
                contextAndPageSizeVO.setOrgIds(requestContext.getOrgIds());
            }
            map = examManageClient.listExamQuestion(contextAndPageSizeVO);
            List<LibrarySubjectVO> librarySubjectVOS = null;
            Integer count = null;
            if(null != map){
                librarySubjectVOS = (List<LibrarySubjectVO>) map.get("list");
                count = (Integer) map.get("pageTotal");
            }
            Map<String, Integer> page = new HashMap<String, Integer>();
            page.put("pageNo",contextAndPageSizeVO.getPageNo());
            page.put("pageSize",contextAndPageSizeVO.getPageSize());
            page.put("pageTotal",count);
            return Response.ok(librarySubjectVOS,page);
        }catch (Exception e) {
            e.printStackTrace();;
            LOGGER.error("考试试题列表:" + e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value="创建考试-添加考试试题", notes="创建考试-添加考试试题")
    @PostMapping("/question/insertall")
    public Response<String> insertExamQuestion(@RequestBody ExamQuestionListVO examQuestionListVO){
       try {
           RequestContext requestContext = ContextHolder.get();
           examQuestionListVO.setAccountId(requestContext.getAccountId());
           examQuestionListVO.setAccountName(requestContext.getAccountName());
           boolean result = examManageClient.insertExamQuestion(examQuestionListVO);
           if (result){
               return Response.ok(ReturnCode.SUCCESS);
           }else{
               return  Response.fail(ReturnCode.SAVE_FAIL.getCode(),ReturnCode.SAVE_FAIL.getMsg());
           }
       }catch (Exception e){
           e.printStackTrace();
           return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
       }
    }

    @ApiOperation(value = "查询考试人员范围", notes = "查询考试人员范围", response = TrExamAuthorizeVO.class)
    @GetMapping("/authorize/list")
    public Response<TrExamAuthorizeVO> selectAuthorizeList(@RequestParam("examId") Long examId) {
        List<TrExamAuthorizeVO> ranges;
        try {
            ranges = examManageClient.selectAuthorizeVO(examId);
            if (!CollectionUtils.isEmpty(ranges)) {
                List<Long> accountIds = new ArrayList<>(ranges.size());
                List<Long> orgIds = new ArrayList<>(ranges.size());
                ranges.forEach(a -> {
                    if (a.getType().equals(1)) {
                        orgIds.add(a.getRelationId());
                    } else {
                        accountIds.add(a.getRelationId());
                    }
                });
                Map<Long, AccountVO> accountMap = queryAccount.queryAccountByIds(accountIds);
                Map<Long, OrgVO> orgMap = queryAccount.queryOrgByIds(orgIds);
                ranges.forEach(a -> {
                    if (null != accountMap) {
                        AccountVO accountVO = accountMap.get(a.getRelationId());
                        if (null != accountVO && a.getType().equals(2)) {
                            a.setWorkNum(accountVO.getWorkNum());
                            a.setFullName(accountVO.getFullName());
                            a.setName(accountVO.getName());
                        }
                    }
                    if (null != orgMap) {
                        OrgVO orgVO = orgMap.get(a.getRelationId());
                        if (null != orgVO && a.getType().equals(1)) {
                            a.setName(orgVO.getName());
                        }
                    }
                });
            }

            return Response.ok(ranges);
        }catch (Exception e){
            e.printStackTrace();
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation(value="新增考试人员范围", notes="新增考试人员范围")
    @PostMapping("/insert/authorize/list")
    public Response<String> insertAllAuthorize(@RequestBody List<TrExamAuthorizeVO> trExamAuthorizeVOS){
        boolean result;
        try {
            RequestContext requestContext = ContextHolder.get();
            Long accountId = requestContext.getAccountId();
            String accountName = requestContext.getAccountName();
            Long siteId = requestContext.getSiteId();
            result = examManageClient.insertAllAuthorize(trExamAuthorizeVOS,accountId,accountName,siteId);
            if (result){
                return Response.ok();
            }else{
                return  Response.fail(ReturnCode.SAVE_FAIL.getCode(),ReturnCode.SAVE_FAIL.getMsg());
            }
        }catch (Exception e){
            e.printStackTrace();
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    /**
     * 提醒关键字替换
     * @param value
     * @param exam
     * @return
     */
    private String replaceContent(String value, Exam exam, String startTime, String endTime){
    	if(!StringUtils.isBlank(value)){
    		value = value.replace("{考试名称}", exam.getName());
    		value = value.replace("{开始时间}", startTime);
    		value = value.replace("{结束时间}", endTime);
        }
    	/*
    	LOGGER.info("Exam ~ {}",exam.toString());
    	LOGGER.info("getStartTime ~ {} ~ {} ~ {}",exam.getStartTime().toString(), exam.getStartTime().toGMTString(), formatDate.format(exam.getStartTime()));
    	LOGGER.info("now ~ {} ~ {} ~ {}",new Date().toString(), new Date().toGMTString(), formatDate.format(new Date()));*/
    	return value;
    }
}
