package com.yizhi.application.exam.controller;

import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.application.exam.constant.ExamError;
import com.yizhi.application.exam.vo.ImportVO;
import com.yizhi.application.util.TaskSendMessage;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.exam.application.feign.ExamClient;
import com.yizhi.exam.application.feign.ExamQuestionClient;
import com.yizhi.exam.application.vo.ContextAndPageSizeVO;
import com.yizhi.exam.application.vo.ExamDetailsMarkingVO;
import com.yizhi.exam.application.vo.ExamViewVO;
import com.yizhi.exam.application.vo.QuestionExamVO;
import com.yizhi.exam.application.vo.exam.ExamAnswerVO;
import com.yizhi.exam.application.vo.exam.ExamDetailsVO;
import com.yizhi.exam.application.vo.exam.ExamIdVO;
import com.yizhi.exam.application.vo.exam.QuestionSortVO;
import com.yizhi.training.application.feign.TpPlanActivityClient;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.*;
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.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


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

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

    @Autowired
    private ExamClient examClient;
    @Autowired
    private ExamQuestionClient examQuestionClient;

//    @Autowired
//	SystemMessageClient systemMessageClient;

    @Autowired
    TpPlanActivityClient tpPlanActivityClient;
    @Autowired
    private TaskSendMessage taskSendMessage;

    /**
     * 显示考试信息列表
     *
     * @return
     */
    @ApiOperation(value = "显示考试信息列表", notes = "显示考试信息列表",response = ExamDetailsVO.class)
    @GetMapping("/list")
    public Response<ExamDetailsVO> getExamList(@RequestParam(value = "currentTime",name = "currentTime",required = false)String  currentTime,
                                               ContextAndPageSizeVO contextAndPageSizeVO) {
        List<ExamDetailsVO> list = null;
        Map<String,Integer> page = null;
        try {
            RequestContext requestContext = ContextHolder.get();
            Long companyId = requestContext.getCompanyId();
            Long siteId = requestContext.getSiteId();
            List<Long> orgIds = null;
            contextAndPageSizeVO.setCompanyId(companyId);
            contextAndPageSizeVO.setSiteId(siteId);
            if(!requestContext.isAdmin() && !CollectionUtils.isEmpty(requestContext.getOrgIds())){
                orgIds = requestContext.getOrgIds();
                contextAndPageSizeVO.setOrgIds(orgIds);
            }
            Map<String,Object> map = examClient.getExamList(currentTime,contextAndPageSizeVO);
            if(map == null){
                return Response.ok(new ArrayList<ExamDetailsVO>());
            }
            if (map.containsKey("listvo")){
                list = (List<ExamDetailsVO>) map.get("listvo");
            }
            if (map.containsKey("page")){
                page = (Map<String, Integer>) map.get("page");
            }
            Pair<List<ExamDetailsVO>,Map<String,Integer>> pair = new MutablePair<List<ExamDetailsVO>,Map<String,Integer>>(list,page);;
            if (null != list){
                return Response.ok(pair);
            }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 = "考试统计列表",response = ExamDetailsMarkingVO.class) // 统计列表和阅卷列表其实是一样的
    @GetMapping("/count/list")
    public Response<ExamDetailsMarkingVO> countList(
            @ApiParam(value = "考试名称模糊查询", required = false) @RequestParam(name = "name", required = false) String name,
            @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){
        List<ExamDetailsMarkingVO> list = null;
        Map<String,Integer> page = null;
        try {
            Long companyId = ContextHolder.get().getCompanyId();
            Map<String,Object> map = examClient.countList(name,pageSize,pageNo,companyId);
            
            if(map == null){
                return Response.ok(new ArrayList<ExamDetailsMarkingVO>());
            }

            if(null != map.get("list")){
                list = (List<ExamDetailsMarkingVO>) map.get("list");
            }
            if (null != map.get("page")){
                page = (Map<String, Integer>) map.get("page");
            }
            Pair<List<ExamDetailsMarkingVO>,Map<String,Integer>> pair = new MutablePair<List<ExamDetailsMarkingVO>,Map<String,Integer>>(list,page);
            if (null != list){
                return Response.ok(pair);
            }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 = "考试批量删除") // registered
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idArr", value = "考试ID集合",paramType = "body")
    })
    @PostMapping("/deletes")
    public Response<String> deleteExam(@RequestBody Long[] idArr){
        try {
            boolean result = examClient.deleteExam(idArr);
            if (result){
                return Response.ok(ReturnCode.SUCCESS);
            }else {
                return Response.fail(ReturnCode.DELETE_FAIL.getCode(),ReturnCode.DELETE_FAIL.getMsg());
            }
        }catch (Exception e){
            LOGGER.error("批量删除考试失败",e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "考试上架", notes = "考试上架")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试ID",paramType = "body")
    })
    @PostMapping("/put/up")
    public Response<String> examPutUp(
            @RequestBody ExamIdVO examIdVO) {
        try {
            int count = examQuestionClient.selectQuestionCountByExamId(examIdVO.getExamId());
            if (count <= 0){
                return Response.fail(ExamError.EXAM_PUT_UP_NOT_QUESTION_CODE,ExamError.EXAM_PUT_UP_NOT_QUESTION_CODE_MSG);
            }
            Long examId=examIdVO.getExamId();
            String s=examClient.checkScore(examId);
            boolean result;
            if(!s.equals("ok")) {
                return Response.fail(s);
            }else {
                result= examClient.examPutUp(examIdVO);
            }
            if (result){
//            	try {
//            		result = systemMessageClient.up(examIdVO.getExamId());
//            		if(!result){
//            			LOGGER.info("开启考试{}提醒失败", examIdVO.getExamId());
//            		}
//            	} catch(Exception e){
//            		LOGGER.error("开启考试{}提醒异常", examIdVO.getExamId());
//            		e.printStackTrace();
//            	}

                return Response.ok(ReturnCode.SUCCESS);
            }else {
                return Response.fail(ReturnCode.UPDATE_FAIL.getCode(),ReturnCode.UPDATE_FAIL.getMsg());
            }
        }catch (Exception e){
            LOGGER.error("考试上架失败",e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "考试下架", notes = "考试下架") // registered
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试ID",paramType = "body")
    })
    @PostMapping("/put/down")
    public Response<String> examPutDown(
            @RequestBody ExamIdVO examIdVO) {
        try {
            List<Long> ids = new ArrayList<Long>();
            ids.add(examIdVO.getExamId());
            Set<String> tpNames = tpPlanActivityClient.checkBizIsExistInTpNames(ids);
            String tpName = "";
            boolean isUp = false;
            if(!CollectionUtils.isEmpty(tpNames)){
                for(String s : tpNames){
                    tpName = s;
                }
                isUp = true;
            }
            if(isUp){
                return Response.fail("10000", InternationalEnums.RESEARCHCONTROLLER3.getName()+tpName+InternationalEnums.RESEARCHCONTROLLER4.getName());
            }
            boolean result = examClient.examPutDown(examIdVO);
            if (result){
//            	try {
//            		result = systemMessageClient.down(examIdVO.getExamId());
//            		if(!result){
//            			LOGGER.info("关闭考试{}提醒失败", examIdVO.getExamId());
//            		}
//            	} catch(Exception e){
//            		LOGGER.error("关闭考试{}提醒异常", examIdVO.getExamId());
//            		e.printStackTrace();
//            	}
                return Response.ok(ReturnCode.SUCCESS);
            }else {
                return Response.fail(ReturnCode.UPDATE_FAIL.getCode(),ReturnCode.UPDATE_FAIL.getMsg());
            }
        }catch (Exception e){
            LOGGER.error("考试下架失败",e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "导出答卷", notes = "导出答卷",response = QuestionExamVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试ID",paramType = "body")
    })
    @PostMapping("/export/answer")
    public Response<QuestionExamVO> exportAnswer(com.yizhi.application.exam.vo.ExamVO exam){
        try {
            List<QuestionExamVO> list;
            if(exam.getExamId() != null) {
                list = examClient.exportAnswer(exam.getExamId());
            }else{
                return Response.fail(ReturnCode.PARAM_INVALID);
            }
            return Response.ok(list);
        }catch (Exception e){
            LOGGER.error("导出答卷失败",e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "获得考试详情",notes = "考试详情",response = ExamAnswerVO.class)
    @GetMapping("/count/account")
    public Response<ExamAnswerVO> getExamAnswers(
            @ApiParam(name = "examId",value = "考试id",required = true)@RequestParam(name = "examId",required = true) Long examId,
            @ApiParam(name = "pageNo",value = "当前页数")@RequestParam(name = "pageNo",required = false,defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize",value = "页面数据个数")@RequestParam(name = "pageSize",required = false,defaultValue = "20") Integer pageSize,
            @ApiParam(name = "accountIdList",value = "用户id集合")@RequestParam(name = "accountIdList",required = false) List<Long> accountIdList,
            @ApiParam(name = "orgIdList",value = "组织id集合")@RequestParam(name = "orgIdList",required = false) List<Long> orgIdList,
            @ApiParam(name = "state",value = "是否通过,0未通过，1通过")@RequestParam(name = "state",required = false) Integer state,
            @ApiParam(name = "tstart",value = "考试开始时间")@RequestParam(name = "tstart",required = false) String tstart,
            @ApiParam(name = "tend",value = "考试结束时间")@RequestParam(name = "tend",required = false) String tend){
        List<ExamAnswerVO> list = null;
        Map<String,Integer> page = null;
        try{
            Map<String,Object> map = examClient.getExamAnswers(examId,pageNo,pageSize,accountIdList,orgIdList,state,tstart,tend);
            if (null != map.get("list")){
                list = (List<ExamAnswerVO>) map.get("list");
            }
            if (null != map.get("page")){
                page = (Map<String, Integer>) map.get("page");
            }
            Pair<List<ExamAnswerVO>,Map<String,Integer>> pair = new MutablePair<List<ExamAnswerVO>,Map<String,Integer>>(list,page);
            if (null != list){
                return Response.ok(pair);
            }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.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "考试查看",notes = "考试查看",response = ExamViewVO.class)
    @GetMapping("/view")
    public Response<ExamViewVO> examView(
            @ApiParam(name = "examId",value = "考试id")@RequestParam(name = "examId") Long examId
    ){
        try {
        	ExamViewVO examView = examClient.selectExam(examId);

            if (null != examView){
                return Response.ok(examView);
            }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.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }

    }

    @ApiOperation(value = "导入考试试题", notes = "导入考试试题")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileDir",value = "上传文件路径",paramType = "body"),
            @ApiImplicitParam(name = "fileName",value = "文件名",paramType = "body"),
            @ApiImplicitParam(name = "id",value = "考试ID",paramType = "body")
    })
    @PostMapping(value = "/question/export")
    public Response<String> insertByFile(@RequestBody ImportVO importVO) {
        Boolean result = false;
        try {
            result = examClient.insertByFile(importVO.getFileDir(),importVO.getFileName(),importVO.getId());
            if (result){
                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.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation("新增试题排序接口")
    @PostMapping("/question/select/list")
    public Response<String> insertSort(@RequestBody QuestionSortVO questionSortVO){
        Boolean result = false;
        RequestContext requestContext = ContextHolder.get();
        try {
            questionSortVO.setAccountId(requestContext.getAccountId());
            questionSortVO.setAccountName(requestContext.getAccountName());
            result = examClient.insertQuestionSort(questionSortVO);
            if (result){
                return Response.ok(ReturnCode.SUCCESS);
            }else{
                return Response.fail(ReturnCode.SAVE_FAIL.getCode(),ReturnCode.SAVE_FAIL.getMsg());
            }
        }catch (Exception e){
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation("校验考试名称是否存在 true存在false不存在")
    @GetMapping("/name/exist")
    public Response<String> nameIsExist(@RequestParam("name") String name){
        try {
            boolean result = examClient.nameIsExist(name);
            return Response.ok(result);
        }catch (Exception e){
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

}
