package com.zcloud.service.paper.impl;

import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.mapper.datasource.paper.StageexampaperMapper;
import com.zcloud.service.courseware.QuestionService;
import com.zcloud.service.paper.StageExamPaperCoursewareService;
import com.zcloud.service.paper.StageExamPaperQuestionService;
import com.zcloud.service.paper.StageexampaperInputService;
import com.zcloud.service.paper.StageexampaperService;
import com.zcloud.service.task.StageStudentRelationService;
import com.zcloud.util.DateUtil;
import com.zcloud.util.Jurisdiction;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 说明：阶段考试试卷表
 * 作者：luoxiaobao
 * 时间：2021-07-04
 * 官网：www.zcloudchina.com
 */
@Service
@Transactional //开启事物
public class StageexampaperServiceImpl implements StageexampaperService {

	@Autowired
	private StageexampaperMapper stageexampaperMapper;
	@Autowired
	private QuestionService questionService;
//	@Autowired
//	private StageexammiddleService stageexammiddleService;
	@Autowired
	private StageExamPaperQuestionService stageExamPaperQuestionService;
	@Autowired
	private StageExamPaperCoursewareService stageExamPaperCoursewareService;
	@Autowired
	private StageStudentRelationService stageStudentRelationService;

	@Autowired
	private StageexampaperInputService stageexampaperInputService;



	/**新增
	 * @param pd
	 * @throws Exception
	 */
	public void save(PageData pd)throws Exception{
		stageexampaperMapper.save(pd);
		stageExamPaperCoursewareService.saveFromPager(pd); //保存所选课件范围
		stageStudentRelationService.saveFromPager(pd); //保存所选考试人员

		int QUESTIONSCORE = 100 / Integer.parseInt(pd.getString("QUESTIONNUM"));	//创建试卷试题（按照试卷试题数随机抽取课程习题）
		List<PageData> questions = questionService.findForStageByQuestionNum(pd);
		pd.put("QUESTIONSCORE", QUESTIONSCORE);
		//保存抽取后的试题数据
		stageExamPaperQuestionService.saveAll(pd, questions);
	}

	/**删除
	 * @param pd
	 * @throws Exception
	 */
	public void delete(PageData pd)throws Exception{
		stageExamPaperCoursewareService.deleteByExamPaper(pd);
		stageStudentRelationService.deleteByExamPaper(pd);
		stageExamPaperQuestionService.deleteByExamPaper(pd);
		stageexampaperMapper.delete(pd);
	}

	/**修改
	 * @param pd
	 * @throws Exception
	 */
	public void edit(PageData pd)throws Exception{
		stageexampaperMapper.edit(pd);
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	public List<PageData> list(Page page)throws Exception{
		return stageexampaperMapper.datalistPage(page);
	}

	/**列表（课程为主体的列表信息）
	 * @param page
	 * @throws Exception
	 */
	public List<PageData> listCurriculum(Page page)throws Exception{
		return stageexampaperMapper.listCurriculumPage(page);
	}

	/**列表(全部)
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> listAll(PageData pd)throws Exception{
		return stageexampaperMapper.listAll(pd);
	}

	/**通过id获取数据
	 * @param pd
	 * @throws Exception
	 */
	public PageData findById(PageData pd)throws Exception{
		PageData data = stageexampaperMapper.findById(pd);
		List<PageData> questionList = stageExamPaperQuestionService.findByExamPaper(pd);
		data.put("QUESTIONLIST", questionList);

		//获取所选考试人员
		List<PageData> userList = stageStudentRelationService.findByExamPaper(pd);
		String CURRICULUMUSERS = "";
		for (PageData user : userList) {
			CURRICULUMUSERS += user.getString("USER_ID") + ",";
		}
		data.put("CURRICULUMUSERS", StringUtils.isNotBlank(CURRICULUMUSERS) ? CURRICULUMUSERS.substring(0, CURRICULUMUSERS.length()-1) : "");
		//获取所选课件
		List<PageData> coursewareList = stageExamPaperCoursewareService.findByExamPaper(pd);
		String COURSEWARES = "";
		for (PageData courseware : coursewareList) {
			COURSEWARES += courseware.getString("COURSEWARE_ID") + "_" + courseware.getString("COURSEWARETYPE") + ",";
		}
		data.put("COURSEWARES", StringUtils.isNotBlank(COURSEWARES) ? COURSEWARES.substring(0, COURSEWARES.length()-1) : "");
		return data;
	}

	/**批量删除
	 * @param pd
	 * @throws Exception
	 */
	public void deleteAll(PageData pd)throws Exception{
		stageexampaperMapper.deleteAll(pd);
	}

	/**列表(根据所选ID获取数据)
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> findByIds(PageData pd) throws Exception {
		return stageexampaperMapper.findByIds(pd);
	}

	/**删除(根据课程ID删除试题数据)
	 * @param pd
	 * @throws Exception
	 */
	@Override
	public void deleteByCurriculumIds(PageData pd) throws Exception {
		stageexampaperMapper.deleteByCurriculumIds(pd);
	}

	/**
	 * 通过试卷ID获取数据
	 * @param pd
	 * @throws Exception
	 */
	@Override
	public PageData getExam(PageData pd) throws Exception {
		PageData data = stageexampaperMapper.findById(pd);
		List<PageData> questionList = stageExamPaperQuestionService.findByExamPaper(pd);
		Object[] ANSWER = new Object[questionList.size()];
		String[] QUESTION_ID = new String[questionList.size()];
		String[] QUESTIONTYPE = new String[questionList.size()];
		String[] QUESTIONSCORE = new String[questionList.size()];
		String[] COURSEWAREID = new String[questionList.size()];
		String[] COURSEWARETYPE = new String[questionList.size()];
		String[] ANSWERRIGHT = new String[questionList.size()];
		String[] QUESTIONSCOREAll = new String[questionList.size()];
		for (int i = 0; i < questionList.size(); i++) {
			if ("2".equals(questionList.get(i).getString("QUESTIONTYPE"))) {	//多选
				String[] multipleANSWER = new String[questionList.get(i).getString("ANSWER").length()];
				for (int j = 0; j < multipleANSWER.length; j++) {
					multipleANSWER[j] = "";
				}
				ANSWER[i] = multipleANSWER;
			} else {
				ANSWER[i] = "";
			}
			QUESTION_ID[i] = questionList.get(i).getString("QUESTION_ID");
			QUESTIONTYPE[i] = questionList.get(i).getString("QUESTIONTYPE");
			QUESTIONSCORE[i] = questionList.get(i).getString("QUESTIONSCORE");
			COURSEWAREID[i] = questionList.get(i).getString("COURSEWARE_ID");
			COURSEWARETYPE[i] = questionList.get(i).getString("COURSEWARETYPE");
			ANSWERRIGHT[i] = questionList.get(i).getString("ANSWER");
			QUESTIONSCOREAll[i] = questionList.get(i).getString("QUESTIONSCORE");
		}
		data.put("ANSWER", ANSWER);
		data.put("QUESTION_ID", QUESTION_ID);
		data.put("QUESTIONTYPE", QUESTIONTYPE);
		data.put("QUESTIONSCORE", QUESTIONSCORE);
		data.put("COURSEWAREID", COURSEWAREID);
		data.put("COURSEWARETYPE", COURSEWARETYPE);
		data.put("ANSWERRIGHT", ANSWERRIGHT);
		data.put("QUESTIONSCOREAll", QUESTIONSCOREAll);
		data.put("QUESTIONLIST", questionList);
		return data;
	}

	/**
	 * 考试开考或者考试人员已考试，试卷不能再变动
	 * @param pd
	 * @throws Exception
	 */
	@Override
	public void updateExamState(PageData pd) throws Exception {
		stageexampaperMapper.updateExamState(pd);
	}

	/**列表（考试结果列表）
	 * @param page
	 * @throws Exception
	 */
	@Override
	public List<PageData> listSummary(Page page)throws Exception{
		return stageexampaperMapper.listSummarylistPage(page);
	}
	/**新增
	 * @param pd
	 * @throws Exception
	 */
	public void saveV2(PageData pd)throws Exception{
		PageData inputPd = new PageData();
		inputPd.put("STAGEEXAMPAPERINPUT_ID",pd.getString("INPUT_ID"));
		PageData input = stageexampaperInputService.findById(inputPd);

		PageData savePd = new PageData();
		String date = DateUtil.date2Str(new Date());
		savePd.put("STAGEEXAMPAPER_ID", pd.getString("STAGEEXAMPAPER_ID"));	//主键
		savePd.put("CREATOR", Jurisdiction.getUsername());	//添加人
		savePd.put("CREATTIME", date);	//添加时间
		savePd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		savePd.put("OPERATTIME", date);	//修改时间
		savePd.put("EXAMSTATE", "0");	//试卷状态(0:初始 1：已考试)
		savePd.put("ISDELETE", "0");	//是否删除(0:有效 1：删除)
		savePd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID

		savePd.put("EXAMNAME", pd.getString("kaoshoName"));	//试卷名称 kaoshoName
		savePd.put("STUDYTASK_ID", pd.getString("STUDYTASK_ID"));	//任务id
		savePd.put("INPUT_ID", pd.getString("INPUT_ID"));	// 阶段试卷id
		savePd.put("NUMBER_OF_EXAMINATIONS", pd.getString("NUMBER_OF_EXAMINATIONS"));
		savePd.put("EXAMTIME", pd.getString("PEIXUE_START_TIME"));	//考试时间（开始时间）
		savePd.put("ANSWERSHEETTIME", pd.getString("ANSWERSHEETTIME"));	//答卷时间（持续时间）
		savePd.put("EXAMSCORE", input.getString("EXAMSCORE"));	//试卷分数
		savePd.put("QUESTIONNUM",  pd.getString("QUESTIONNUM"));//试题数量
		savePd.put("PASSSCORE",  input.getString("PASSSCORE"));//合格分数
		stageexampaperMapper.save(savePd); // 保存试卷表
	}
	public PageData getDataById(PageData pd)throws Exception{
		return stageexampaperMapper.findById(pd);
	}

	public List<PageData> findByTaskId(PageData pd)throws Exception{
		return stageexampaperMapper.findByTaskId(pd);
	}
}

