<?php
namespace app\components;

use Yii;
use app\models\Resour_course;
use app\models\Doexam;
use app\models\Doexam_answer;
use app\models\Exam;
use app\models\Person_option;
use app\models\Person_stem;
use app\models\Questi_option;
use app\models\Questi_stem;
use app\models\Questi_type;
use app\models\User;

class ExamchouHelper{
	
	//生成随机试卷
	public static function randQuestStemsPerson($exam, $studentid){
		$condition = "courseid=". $exam->chouti_courseid ." and islocked=0";
		if(!empty($exam->chouti_treeid)){
			$condition .= " and find_in_set('". $exam->chouti_treeid ."',treepath)";
		}
		$qtypejson = json_decode($exam->qtypejson);
		foreach($qtypejson as $onetype){
			if($onetype->questnum>0){
				$qustems = Questi_stem::find()->where($condition ." and typechild=". $onetype->id)->orderby("rand()")->limit($onetype->questnum)->all();
				self::CopyQuestStems2Exam($exam, $qustems, $onetype->onepoints, $studentid);
			}
		}
	}

	//复制题库题目到考试
	public static function CopyQuestStems2Exam($exam, $qustems, $epoints, $studentid){
		if(empty($qustems)){return 0;}
		if(empty($epoints) || is_numeric($epoints)==false){$epoints = 10;}
		foreach($qustems as $oneqstem){
			$samestem = Person_stem::find()->where("examid=". $exam->id ." and qbank_stemid=". $oneqstem->id ." and studentid=". $studentid)->one();
			if(!empty($samestem)){continue;}
			$ex_stem = new Person_stem();
			$ex_stem->specialid = $exam->specialid;
			$ex_stem->courseid = $exam->courseid;
			$ex_stem->examid = $exam->id;
			$ex_stem->typeid = $oneqstem->typeid;
			$ex_stem->typechild = $oneqstem->typechild;
			$ex_stem->levels = $oneqstem->levels;
			$ex_stem->points = $epoints;
			$ex_stem->optionnum = $oneqstem->optionnum;
			$ex_stem->qbank_stemid = $oneqstem->id;
			$ex_stem->content = $oneqstem->content;
			$ex_stem->answer = $oneqstem->answer;
			$ex_stem->explains = $oneqstem->explains;
			$ex_stem->studentid = $studentid;
			$ex_stem->save();
			$oneqstem->options = Questi_option::find()->where("stemid=". $oneqstem->id)->orderby("code asc")->all();
			foreach ($oneqstem->options as $oneqoption) {
				$ex_option = new Person_option();
				$ex_option->specialid = $exam->specialid;
				$ex_option->courseid = $exam->courseid;
				$ex_option->examid = $exam->id;
				$ex_option->stemid = $ex_stem->id;
				$ex_option->code = $oneqoption->code;
				$ex_option->content = $oneqoption->content;
				$ex_option->isanswer = $oneqoption->isanswer;
				$ex_option->studentid = $studentid;
				$ex_option->save();
			}
		}
	}

}
?>