package com.zcloud.controller.onlinexxks;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.service.onlinexxks.QuestionService;
import com.zcloud.util.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 说明：习题管理
 * 作者：luoxiaobao
 * 时间：2021-07-03
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/question")
public class QuestionController extends BaseController {

	@Autowired
	private QuestionService questionService;

	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	@RequiresPermissions( value = {"question:add" , "courseware:add"}, logical = Logical.OR)
	@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("QUESTION_ID", this.get32UUID());	//主键
		pd.put("CREATOR", Jurisdiction.getUsername());	//添加人
		pd.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		pd.put("ISDELETE", "0");	//是否删除(0:有效 1：删除)
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		Integer max = questionService.maxQuestionNumber(pd);
		max ++;
		pd.put("QUESTIONNUMBER",max); //题号
		questionService.save(pd);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	@RequiresPermissions( value = {"question:del" , "courseware:del"}, logical = Logical.OR)
	@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()));	//修改时间
		questionService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	@RequiresPermissions( value = {"question:edit" , "courseware:edit"}, logical = Logical.OR)
	@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()));	//修改时间
		questionService.edit(pd);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	@RequiresPermissions( value = {"question:list" , "courseware:list"}, logical = Logical.OR)
	@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 = questionService.list(page);	//列出Question列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	@RequiresPermissions( value = {"question:edit" , "courseware:edit"}, logical = Logical.OR)
	@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 = questionService.findById(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	@RequiresPermissions( value = {"question:del" , "courseware:del"}, logical = Logical.OR)
	@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
			questionService.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("题号");	//1
		titles.add("试题类型（单选题、多选题、判断题）");	//2
		titles.add("题干");	//3
		titles.add("选项A");	//4
		titles.add("选项B");	//5
		titles.add("选项C");	//6
		titles.add("选项D");	//7
		titles.add("答案");	//8
		titles.add("课件类型");	//9
		titles.add("课件ID");	//10
//		titles.add("添加人");	//11
//		titles.add("添加时间");	//12
//		titles.add("修改人");	//13
//		titles.add("修改时间");	//14
//		titles.add("是否删除(0:有效 1：删除)");	//15
//		titles.add("企业ID");	//16
		dataMap.put("titles", titles);
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		List<PageData> varOList = questionService.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("QUESTIONNUMBER"));	    //1
			vpd.put("var2", varOList.get(i).getString("QUESTIONTYPE"));	    //2
			vpd.put("var3", varOList.get(i).getString("QUESTIONDRY"));	    //3
			vpd.put("var4", varOList.get(i).getString("OPTIONA"));	    //4
			vpd.put("var5", varOList.get(i).getString("OPTIONB"));	    //5
			vpd.put("var6", varOList.get(i).getString("OPTIONC"));	    //6
			vpd.put("var7", varOList.get(i).getString("OPTIOND"));	    //7
			vpd.put("var8", varOList.get(i).getString("ANSWER"));	    //8
			vpd.put("var9", varOList.get(i).getString("COURSEWARETYPE"));	    //9
			vpd.put("var10", varOList.get(i).getString("COURSEWARENAME"));	    //10
//			vpd.put("var11", varOList.get(i).getString("CREATOR"));	    //11
//			vpd.put("var12", varOList.get(i).getString("CREATTIME"));	    //12
//			vpd.put("var13", varOList.get(i).getString("OPERATOR"));	    //13
//			vpd.put("var14", varOList.get(i).getString("OPERATTIME"));	    //14
//			vpd.put("var15", varOList.get(i).get("ISDELETE").toString());	//15
//			vpd.put("var16", varOList.get(i).getString("CORPINFO_ID"));	    //16
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}

	/**列表(根据课程所选课件获取习题数据)
	 * @param  	课件ID
	 * @throws Exception
	 */
	@RequestMapping(value="/countByCourseware")
	@ResponseBody
	public Object countByCourseware() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = questionService.countByCourseware(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**列表(根据阶段考试所选课件范围获取习题数据)
	 * @param  COURSEWARES	课件ID+课件分类
	 * @throws Exception
	 */
	@RequestMapping(value="/countByStageExamCourseware")
	@ResponseBody
	public Object countByStageExamCourseware() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("COURSEWARE_IDS",pd.getString("COURSEWARES").split(","));
		pd = questionService.countByStageExamCourseware(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	@RequestMapping(value="/hasQuestionNumber")
	@ResponseBody
	public Object hasQuestionNumber() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData(); // COURSEWAREID

		Integer count = questionService.hasQuestionNumber(pd);
		pd.put("count",count);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}
	/**下载模版
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/downExcel")
	public void downExcel(HttpServletResponse response)throws Exception{
		FileDownload.fileDownload(response, PathUtil.getProjectpath() + Const.FILEPATHFILE + "questionExcelTemplate.xls", "习题导入模板.xls");
	}
	/**从EXCEL导入到数据库
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/readExcel")
	@SuppressWarnings("unchecked")
	@ResponseBody
	@Transactional
	public Object readExcel2(@RequestParam(value="FFILE",required=false) MultipartFile file) throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		StringBuffer errorStr = new StringBuffer();
		PageData pd = new PageData();
		pd = this.getPageData(); // COURSEWAREID

		if (null != file && !file.isEmpty()) {
			String filePath = PathUtil.getProjectpath() + Const.FILEPATHFILE + "question/";
			String fileName =  FileUpload.fileUp(file, filePath, this.get32UUID());//执行上传
			List<PageData> listPd = (List) ObjectExcelRead.readExcel(filePath, fileName, 1, 0, 0);			//执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
			/**
			 * var0 :序号
			 * var1 :试题类型
			 * var2 :题干
			 * var3 :选项A
			 * var4 :选项B
			 * var5 :选项C
			 * var6 :选项D
			 * var7 :答案
			 */
			List<String> header = new ArrayList<>();
			header.add("序号");header.add("试题类型");header.add("题干");header.add("选项A");header.add("选项B");
			header.add("选项C");header.add("选项D");header.add("答案");
			try {
				if(listPd.size()>0) {
					/**
					 *  判断是否填写必填
					 *  判断excel是有有重复数据
					 *  判断数据库是否有重复数据
					 *  导入
					 *  判断题的CD 为空 ( 多选题 单选题 判断题 )
					 *  答案是否正确
					 *  长度
					 */
					List<PageData> listAll = new ArrayList<>();

					Integer number =0;//行数，用于提示用户
					for(PageData lpd:listPd) {
						number++;
						for(int i=0;i<7;i++) {
							if(i==0) { // var0 :序号 非必填
								continue;
							}
							if(!lpd.containsKey("var"+i) || Tools.isEmpty(lpd.get("var"+i))) {
								if( "判断题".equals(lpd.get("var1"))){
									if(i==5 || i==6 || i==3 || i==4){ //判断题没有选项
										continue;
									}
								}else{
									errorStr.append("第"+number+"行的"+header.get(i)+"无数据;\n");
									continue;
								}
							}
							if(lpd.get("var"+i).toString().length() >= 250){ //限制内容长度
								errorStr.append("第"+number+"行的 \""+header.get(i)+"\"字符长度超出,请精简的250内;\n");
								continue;
							}

						}

						PageData pageData = new PageData();
						String QUESTIONTYPE = Tools.isEmpty(lpd.get("var1"))?"": Tools.excelHandle(lpd.get("var1"));
						if("单选题".equals(QUESTIONTYPE)){
							pageData.put("QUESTIONTYPE","1");//试题类型
						}else if("多选题".equals(QUESTIONTYPE)){
							pageData.put("QUESTIONTYPE","2");//试题类型
						}else if("判断题".equals(QUESTIONTYPE)){
							pageData.put("QUESTIONTYPE","3");//试题类型
						}
						pageData.put("QUESTIONDRY", Tools.isEmpty(lpd.get("var2"))?"":lpd.get("var2").toString());//题干
						pageData.put("OPTIONA", Tools.isEmpty(lpd.get("var3"))?"": Tools.excelHandle(lpd.get("var3")));//选项A
						pageData.put("OPTIONB", Tools.isEmpty(lpd.get("var4"))?"": Tools.excelHandle(lpd.get("var4")));//选项B
						pageData.put("OPTIONC", Tools.isEmpty(lpd.get("var5"))?"": Tools.excelHandle(lpd.get("var5")));//选项C
						pageData.put("OPTIOND", Tools.isEmpty(lpd.get("var6"))?"": Tools.excelHandle(lpd.get("var6")));//选项D
						pageData.put("ANSWER", Tools.isEmpty(lpd.get("var7"))?"": Tools.excelHandle(lpd.get("var7")));//答案
						listAll.add(pageData);

						HashMap<String,String> chongfuOPTION = new HashMap<>(4);
						chongfuOPTION.put(Tools.isEmpty(lpd.get("var3"))?"":Tools.excelHandle(lpd.get("var3")),"");
						chongfuOPTION.put(Tools.isEmpty(lpd.get("var4"))?"":Tools.excelHandle(lpd.get("var4")),"");
						chongfuOPTION.put(Tools.isEmpty(lpd.get("var5"))?"":Tools.excelHandle(lpd.get("var5")),"");
						chongfuOPTION.put(Tools.isEmpty(lpd.get("var6"))?"":Tools.excelHandle(lpd.get("var6")),"");

						String questionTypeAllVal = "单选题,多选题,判断题";
						boolean status = questionTypeAllVal.contains(Tools.excelHandle(lpd.get("var1"))); //习题类型是否正确
						if(!status){
							errorStr.append("第"+number+"行的试题类型错误,系统只支持单选题,多选题,判断题;\n");
							continue;
						}
						if("3".equals(pageData.getString("QUESTIONTYPE"))){// 判断题
							String  str2 = Tools.isEmpty(lpd.get("var7"))?"": Tools.excelHandle(lpd.get("var7"));// 对和错
							String JudQueType = "对,错";
							boolean JudQueTypeStatus = JudQueType.contains(str2); //判断题的答案选项是否填入了 '对'，'错'
							if (!JudQueTypeStatus) { //不全是大写字母
								errorStr.append("第"+number+"行的答案类型错误,判断题只有对和错选项;\n");
								continue;
							}
							pageData.put("OPTIONA","对");//选项A
							pageData.put("OPTIONB","错");//选项B
							if(str2.equals("对")){
								pageData.put("ANSWER","A");
							}else if(str2.equals("错")){
								pageData.put("ANSWER","B");
							}
						}else{
							String str2 = Tools.isEmpty(lpd.get("var7"))?"": Tools.excelHandle(lpd.get("var7"));//是否是ABCD 的大写字母
							Pattern pattern2 = Pattern.compile("[A-D]*");
							Matcher matcher2 = pattern2.matcher(str2);
							if (!matcher2.matches()) { //不全是大写字母
								errorStr.append("第"+number+"行的答案类型错误;\n");
								continue;
							}
							if(chongfuOPTION.size() <4){ // 查看判断题的选项是否重复
								errorStr.append("第"+number+"行的选项重复;\n");
								continue;
							}
							if("1".equals(pageData.getString("QUESTIONTYPE"))){ //如果是单选题，答案必须是一个
								if(str2.length()>1){
									errorStr.append("第"+number+"行的,习题是单选题,只能有一个答案;\n");
									continue;
								}
							}
							if("2".equals(pageData.getString("QUESTIONTYPE"))){ //如果是多选题，答案必须是一个
								if(str2.length() ==1){
									errorStr.append("第"+number+"行的,习题是多选题,不能只能有一个答案;\n");
									continue;
								}
							}
						}
					}
					if(Tools.isEmpty(errorStr.toString())) {
						Integer max = questionService.maxQuestionNumber(pd);
						for (PageData pageData : listAll) {
							max ++;
							pageData.put("QUESTIONNUMBER",max); //题号
							pageData.put("COURSEWARETYPE",pd.get("COURSEWARETYPE")); //课件类型(1:视频课件、2:资料课件)
							pageData.put("COURSEWAREID",pd.get("COURSEWAREID"));//COURSEWAREID	课件ID
							pageData.put("QUESTION_ID", this.get32UUID());	//主键
							pageData.put("CREATOR", Jurisdiction.getUsername());	//添加人
							pageData.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
							pageData.put("OPERATOR", Jurisdiction.getUsername());	//修改人
							pageData.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
							pageData.put("ISDELETE", "0");	//是否删除(0:有效 1：删除)
							pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
							questionService.save(pageData);
						}
						errorStr.append("成功导入"+listAll.size()+"条数据!");
					}else {
						errInfo = "error";
					}
					File old = new File(filePath, fileName);
					old.delete();
				}else {
					map.put("result", "error");				//返回结果
					map.put("msg", "Excel数据为空，请检查数据后，重新上传！");
					File old = new File(filePath, fileName);
					old.delete();
					return map;
				}
			}catch (Exception e) {
				map.put("result", "fail");				//返回结果
				map.put("msg", e.toString());
				e.printStackTrace();
				return map;
			}

		}
		map.put("result", errInfo);				//返回结果
		map.put("msg",errorStr.toString());				//返回结果
		map.put("isExcel","1");				//返回类型
		map.put("resultStr", errorStr.toString());
		return map;
	}
	@RequestMapping(value="/getCountByQuestionType")
	@ResponseBody
	public Object getCountByQuestionType() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData(); // COURSEWAREID
		List<PageData> varList = questionService.getCountByQuestionType(pd);
		map.put("varList",varList);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}
}
