package com.zcloud.controller.task;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.task.StageExamService;
import com.zcloud.service.task.StudyTaskService;
import com.zcloud.util.DateUtil;
import com.zcloud.util.Jurisdiction;
import com.zcloud.util.ObjectExcelView;
import com.zcloud.util.Tools;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 说明：阶段考试
 * 作者：luoxiaobao
 * 时间：2021-09-15
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/stageexam")
public class StageExamController extends BaseController {

	@Autowired
	private StageExamService stageexamService;
	@Autowired
	private StudyTaskService studytaskService;
	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
//	// @RequiresPermissions("stageexam:add")
	@ResponseBody
	public Object add() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("STAGEEXAM_ID", this.get32UUID());	//主键
		pd.put("USER_ID", Jurisdiction.getUSER_ID());	//添加人
		String nowDate = DateUtil.date2Str(new Date());
		pd.put("EXAMTIMEBEGIN", nowDate);	//考试时间
		pd.put("EXAMQUESTIONRIGHT", "0");	//考试对题数
		pd.put("EXAMQUESTIONWRONG", "0");	//考试错题数
		pd.put("EXAMSCORE", "0");	//考试得分
		pd.put("CREATOR", Jurisdiction.getUsername());	//添加人
		pd.put("CREATTIME", nowDate);	//添加时间
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", nowDate);	//修改时间
		pd.put("ISDELETE", "0");	//是否删除(0:有效 1：删除)
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		stageexamService.save(pd);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	// @RequiresPermissions("stageexam:del")
	@ResponseBody
	public Object delete() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		stageexamService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
//	// @RequiresPermissions("stageexam:edit")
	@ResponseBody
	public Object edit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		stageexamService.edit(pd);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	// @RequiresPermissions("stageexam:list")
	@ResponseBody
	public Object list(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		page.setPd(pd);
		List<PageData>	varList = stageexamService.list(page);	//列出StageExam列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	// @RequiresPermissions("stageexam:edit")
	@ResponseBody
	public Object goEdit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = stageexamService.findById(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	 /**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	// @RequiresPermissions("stageexam:del")
	@ResponseBody
	public Object deleteAll() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		String DATA_IDS = pd.getString("DATA_IDS");
		if(Tools.notEmpty(DATA_IDS)){
			String[] ArrayDATA_IDS = DATA_IDS.split(",");
			pd.put("ArrayDATA_IDS", ArrayDATA_IDS);	//待删除ids
			stageexamService.deleteAll(pd);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}


	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/excel")
	// @RequiresPermissions("toExcel")
	public ModelAndView exportExcel() throws Exception{
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		Map<String,Object> dataMap = new HashMap<String,Object>();
		List<String> titles = new ArrayList<String>();
		titles.add("课程ID");	//1
		titles.add("阶段考试试卷ID");	//2
		titles.add("学员ID");	//3
		titles.add("考试时间");	//4
		titles.add("考试交卷时间");	//5
		titles.add("考试总题数");	//6
		titles.add("考试对题数");	//7
		titles.add("考试错题数");	//8
		titles.add("考试得分");	//9
		titles.add("添加人");	//10
		titles.add("添加时间");	//11
		titles.add("修改人");	//12
		titles.add("修改时间");	//13
		titles.add("是否删除(0:有效 1：删除)");	//14
		titles.add("企业ID");	//15
		dataMap.put("titles", titles);
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		List<PageData> varOList = stageexamService.listAll(pd);
		List<PageData> varList = new ArrayList<PageData>();
		for(int i=0;i<varOList.size();i++){
			PageData vpd = new PageData();
			vpd.put("var1", varOList.get(i).getString("CURRICULUM_ID"));	    //1
			vpd.put("var2", varOList.get(i).getString("STAGEEXAMPAPER_ID"));	    //2
			vpd.put("var3", varOList.get(i).getString("USER_ID"));	    //3
			vpd.put("var4", varOList.get(i).getString("EXAMTIMEBEGIN"));	    //4
			vpd.put("var5", varOList.get(i).getString("EXAMTIMEEND"));	    //5
			vpd.put("var6", varOList.get(i).getString("EXAMQUESTIONNUM"));	    //6
			vpd.put("var7", varOList.get(i).getString("EXAMQUESTIONRIGHT"));	    //7
			vpd.put("var8", varOList.get(i).getString("EXAMQUESTIONWRONG"));	    //8
			vpd.put("var9", varOList.get(i).getString("EXAMSCORE"));	    //9
			vpd.put("var10", varOList.get(i).getString("CREATOR"));	    //10
			vpd.put("var11", varOList.get(i).getString("CREATTIME"));	    //11
			vpd.put("var12", varOList.get(i).getString("OPERATOR"));	    //12
			vpd.put("var13", varOList.get(i).getString("OPERATTIME"));	    //13
			vpd.put("var14", varOList.get(i).getString("ISDELETE"));	    //14
			vpd.put("var15", varOList.get(i).getString("CORPINFO_ID"));	    //15
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}

	/**交卷
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/submit")
//	// @RequiresPermissions( value = {"stageexam:edit", "curriculum:edit"}, logical = Logical.OR)
	@ResponseBody
	@LogAnno(menuType= "教育培训",menuServer= "在线学习与考试",instructionsOperate = "我的任务",instructionsType = "交卷")
	public Object submit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String nowDate = DateUtil.date2Str(new Date());
		pd.put("STAGEEXAM_ID", this.get32UUID());	//主键
		pd.put("USER_ID", Jurisdiction.getUSER_ID());	//添加人
		pd.put("EXAMTIMEEND", nowDate);	//考试时间
		pd.put("EXAMQUESTIONRIGHT", "0");	//考试对题数
		pd.put("EXAMQUESTIONWRONG", "0");	//考试错题数
		pd.put("EXAMSCORE", "0");	//考试得分

		pd.put("CREATOR", Jurisdiction.getUsername());	//添加人
		pd.put("CREATTIME", nowDate);	//添加时间
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", nowDate);	//修改时间
		pd.put("ISDELETE", "0");	//是否删除(0:有效 1：删除)
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		pd = stageexamService.submit(pd);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**试卷答题展示
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/findResult")
//	// @RequiresPermissions("stageexam:edit")
	@ResponseBody
	@LogAnno(menuType= "教育培训",menuServer= "在线学习与考试",instructionsOperate = "我的任务",instructionsType = "试卷答题展示")
	public Object findResult() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		if(pd.get("STUDYTASK_ID")!=null){
			PageData task = this.studytaskService.findById(pd);
			pd.put("STAGEEXAMPAPER_ID",task.getString("STAGEEXAMPAPER_ID"));
		}
		if(Tools.isEmpty(pd.get("USER_ID"))){
			pd.put("USER_ID",Jurisdiction.getUSER_ID());
		}
		pd = stageexamService.findResult(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}
	/**根据任务id获取全部用户的全部考试成绩
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getUserExamScoreByStudystaskId")
	@ResponseBody
	@LogAnno(menuType= "教育培训",menuServer= "档案管理",instructionsOperate = "一人一档",instructionsType = "根据任务id获取全部用户的全部考试成绩")
	public Object getUserExamScoreByStudystaskId() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		List<PageData> valList =  stageexamService.getUserExamScoreByStudystaskId(pd);
//		找到 List<PageData> 中最大的EXAMSCORE 的EXAMTIMEBEGIN
		Optional<String> maxScoreMap = valList.stream()
				.max(Comparator.comparingInt(mapx ->  Integer.parseInt(mapx.getString("EXAMSCORE"))))
				.map(mapx -> mapx.getString("EXAMTIMEBEGIN"))
				;
        maxScoreMap.ifPresent(s -> map.put("EXAMTIMEBEGIN", s));
		Map<String,String> userExamScore = new HashMap<>(); // key 用户id  val 第一高成绩，第二高成绩
		for (PageData pageData : valList){
			String userId = pageData.getString("USER_ID");
			Integer examScore = Integer.parseInt(pageData.getString("EXAMSCORE"));
			Integer[] exaArrayInt = new Integer[2];
			if (!userExamScore.containsKey(userId)){
				exaArrayInt[0] = examScore;
				exaArrayInt[1] = 0;
			}else{
				String [] exaArrayString = userExamScore.get(userId).toString().split(",");
				exaArrayInt[0] = Integer.parseInt(exaArrayString[0]);
				exaArrayInt[1] =Integer.parseInt(exaArrayString[1]);
				if(examScore> exaArrayInt[0]){
					exaArrayInt[1] = exaArrayInt[0];
					exaArrayInt[0] = examScore;
				}else if(examScore> exaArrayInt[1]){
					exaArrayInt[1] = examScore;
				}
			}
			String examScoreString = exaArrayInt[0] + "," +exaArrayInt[1];
			userExamScore.put(userId,examScoreString);
		}
//		map.put("valList", valList);
		map.put("USER_SIGN_PATH", !valList.isEmpty() ?valList.get(0).getString("USER_SIGN_PATH"):"");
		map.put("userExamScore", userExamScore);
		map.put("result", errInfo);
		return map;
	}
}
