<?php
namespace app\modules\glexam\controllers;

use Yii;
use yii\web\Controller;
use app\models\Config;
use app\models\Exam;
use app\models\Exam_stem;
use app\models\Exam_option;
use app\models\Questi_stem;
use app\models\Questi_option;
use app\models\Questi_type;
use app\models\Specialty;
use app\models\Resour_course;
use app\components\AccessControl;
use app\components\WarningHelper;
use app\components\SafetyHelper;

class QuestionController extends Controller
{
	
	private $userobj; //考试登录信息
	private $request; //Yii::$app->request对象
	private $editstep = "question";
	
    public function init(){
		$this->userobj = AccessControl::isLogin();
		$this->request = Yii::$app->request;
	}
	
	public function beforeAction($action) {
		$this->view->params["navicode"] = "glexam";
		$this->view->params["navicode_two"] = "glexam_manage";
		$this->view->params["meta_title"] = "考试管理 - ";
		return true;
	}
	
	//试题管理
	public function actionIndex(){
		$examid = $this->request->get("id");
		$examid = htmlspecialchars(strip_tags(trim($examid)));
		if(empty($examid) || !is_numeric($examid)){
			WarningHelper::warning("参数错误", ""); die();
		}
		$exam = Exam::find()->where("id=". $examid)->one();
		if(empty($exam)){
			WarningHelper::warning("考试不存在", ""); die();
		}
		if($this->userobj->roleid!=1){
			if($exam->userid!=$this->userobj->id){
				WarningHelper::warning("无权访问", ""); die();
			}
		}
		$exam->course = Resour_course::find()->where("id=". $exam->courseid)->one();
		$exstems = Exam_stem::find()->where("examid=". $exam->id)->orderby("typechild asc,id asc")->all();
		foreach ($exstems as $onestem) {
			$onestem->options = Exam_option::find()->where("examid=". $exam->id ." and stemid=". $onestem->id)->orderby("code asc")->all();
		}
		if(empty($exam->qtypejson)){
			$qtypejson = [];
			$qtypes = Questi_type::find()->where("parentid>0")->all();
			foreach($qtypes as $onetype){
				$qtypejson[] = ["id"=>$onetype->id, "name"=>$onetype->name, "questnum"=>0, "onepoints"=>0, "partpoints"=>0];
			}
			$exam->qtypejson = json_encode($qtypejson);
		}
		return $this->render("index", ["exam"=>$exam, "exstems"=>$exstems, "editstep"=>$this->editstep]);
	}

	//组卷方式，保存
	public function actionBasicok(){
		$examid = $this->request->post("examid");
		$examid = htmlspecialchars(strip_tags(trim($examid)));
		$questway = $this->request->post("questway");
		$questway = htmlspecialchars(strip_tags(trim($questway)));
		$chouti_courseid = $this->request->post("rand_courseid");
		$chouti_courseid = htmlspecialchars(strip_tags(trim($chouti_courseid)));
		$chouti_coursename = $this->request->post("rand_coursename");
		$chouti_coursename = htmlspecialchars(strip_tags(trim($chouti_coursename)));
		$chouti_treeid = $this->request->post("rand_treeid");
		$chouti_treeid = htmlspecialchars(strip_tags(trim($chouti_treeid)));
		$chouti_treename = $this->request->post("rand_treename");
		$chouti_treename = htmlspecialchars(strip_tags(trim($chouti_treename)));
		$maxchouti = $this->request->post("maxchouti");
		$maxchouti = htmlspecialchars(strip_tags(trim($maxchouti)));
		$typechildarr = $this->request->post("typechild");
		$typenamearr = $this->request->post("typename");
		$questnumarr = $this->request->post("questnum");
		$onepointsarr = $this->request->post("onepoints");
		if(empty($examid) || is_numeric($examid)==false){
			echo json_encode(["code"=>"failed", "msg"=>"参数错误"]);
			die();
		}
		if(empty($questway) || is_numeric($questway)==false){
			$questway = 0;
		}
		if($questway>0){
			echo json_encode(["code"=>"failed", "msg"=>"更多功能请至官网http://oa.iefeel.com体验"]);
			die();
		}
		if(empty($chouti_courseid) || !is_numeric($chouti_courseid)){
			$chouti_courseid = 0;
			$chouti_coursename = "";
		}
		if(empty($chouti_treeid) || !is_numeric($chouti_treeid)){
			$chouti_treeid = 0;
			$chouti_treename = "";
		}
		if(empty($maxchouti) || !is_numeric($maxchouti)){
			$maxchouti = 0;
		}
		if($chouti_courseid>0 && empty($chouti_coursename)){
			$chouti_course = Resour_course::find()->where("id=". $chouti_courseid)->one();
			if(!empty($chouti_course)){
				$chouti_coursename = $chouti_course->name;
			}
		}
		if($chouti_treeid>0 && empty($chouti_treename)){
			$chouti_tree = Resour_tree::find()->where("id=". $chouti_treeid)->one();
			if(!empty($chouti_tree)){
				$chouti_treename = $chouti_tree->name;
			}
		}
		if($questway>0){
			$qtypejson = [];
			$typenum = 0;
			foreach($typechildarr as $onekey => $onechildid){
				if(empty($onechildid) || !is_numeric($onechildid)){
					continue;
				}
				$typename = $typenamearr[$onekey];
				$questnum = $questnumarr[$onekey];
				$onepoints = $onepointsarr[$onekey];
				if(empty($questnum) || !is_numeric($questnum)){
					$questnum = 0;
				}
				if(empty($onepoints) || !is_numeric($onepoints)){
					$onepoints = 0;
				}
				if($questnum>0 && $onepoints<=0){
					echo json_encode(["code"=>"failed", "msg"=>"请填写每道题的分数"]);
					die();
				}
				if($questnum>0){
					$typenum ++;
				}
				$qtypejson[] = ["id"=>$onechildid, "name"=>$typename, "questnum"=>$questnum, "onepoints"=>$onepoints, "partpoints"=>$questnum*$onepoints];
			}
			if($typenum==0){
				echo json_encode(["code"=>"failed", "msg"=>"请填写题目数量"]);
				die();
			}
		}
		$exam = Exam::find()->where("id=". $examid)->one();
		if(empty($exam)){
			echo json_encode(["code"=>"failed", "msg"=>"考试不存在"]);
			die();
		}
		if($this->userobj->roleid!=1){
			if($exam->userid!=$this->userobj->id){
				echo json_encode(["code"=>"failed", "msg"=>"无权访问"]);
				die();
			}
		}
		$exam->questway = $questway;
		$exam->chouti_courseid = $chouti_courseid;
		$exam->chouti_coursename = $chouti_coursename;
		$exam->chouti_treeid = $chouti_treeid;
		$exam->chouti_treename = $chouti_treename;
		$exam->maxchouti = $maxchouti;
		if($questway>0){
			$exam->qtypejson = json_encode($qtypejson);
		}
		$exam->save();
		echo json_encode(["code"=>"success","msg"=>"成功"]);
	}

	//题库选取，保存
	public function actionQubankok(){
		$examid = $this->request->post("examid");
		$examid = htmlspecialchars(strip_tags(trim($examid)));
		$resouridarr = $this->request->post("resourid");
		if(empty($examid) || is_numeric($examid)==false){
			echo json_encode(["code"=>"failed", "msg"=>"参数错误"]);
			die();
		}
		$exam = Exam::find()->where("id=". $examid)->one();
		if(empty($exam)){
			echo json_encode(["code"=>"failed", "msg"=>"考试不存在"]);
			die();
		}
		if(empty($resouridarr)){
			echo json_encode(["code"=>"failed", "msg"=>"请选择题目"]);
			die();
		}
		foreach ($resouridarr as $oneresourid) {
			if(empty($oneresourid) || !is_numeric($oneresourid)){
				$oneresourid = 0;
			}
			$oneresourid = SafetyHelper::KillDangerCode($oneresourid);
			$oneresourid = htmlspecialchars(strip_tags(trim($oneresourid)));
		}
		$resouridstr = implode(",", $resouridarr);
		$qustems = Questi_stem::find()->where("id in (". $resouridstr .")")->orderby("id asc")->all();
		$pingjunfen = 10;
		$stemnum = count($qustems);
		if($stemnum>0){
			$pingjunfen = round($exam->points/$stemnum);
		}
		$this->CopyQuestStems2Exam($exam, $qustems, $pingjunfen);
		$this->CalcStemTotalPoints($examid);
		echo json_encode(["code"=>"success","msg"=>"成功"]);
	}

	//保存题目分值
	function actionExpointsok(){
		$examid = $this->request->post("examid");
		$examid = htmlspecialchars(strip_tags(trim($examid)));
		if(empty($examid) || is_numeric($examid)==false){
			echo json_encode(["code"=>"failed", "msg"=>"参数错误"]);
			die();
		}
		$exstemidarr = $this->request->post("exstemid");
		$expointsarr = $this->request->post("expoints");
		if(empty($exstemidarr) || empty($expointsarr)){
			echo json_encode(["code"=>"failed", "msg"=>"还没有添加题目"]);
			die();
		}
		foreach ($exstemidarr as $onekey => $onestemid) {
			if(empty($expointsarr[$onekey]) || !is_numeric($expointsarr[$onekey]) || $expointsarr[$onekey]<0){
				$expointsarr[$onekey] = 10;
			}
			Exam_stem::updateAll(["points"=>$expointsarr[$onekey]], "id=". $onestemid);
		}
		$this->CalcStemTotalPoints($examid);
		echo json_encode(["code"=>"success","msg"=>"成功"]);
	}

	//随机组卷，保存
	function actionQrandomok(){
		echo json_encode(["code"=>"failed", "msg"=>"更多功能请至官网http://oa.iefeel.com体验"]);
	}

	//删除题目
	function actionDelete(){
		$exstemidarr = $this->request->post("exstemidel");
		foreach ($exstemidarr as $onestemid) {
			if(empty($onestemid) || !is_numeric($onestemid)){
				$onestemid = 0;
			}
		}
		$exstemidstr = implode(",", $exstemidarr);
		Exam_option::deleteAll("stemid in (". $exstemidstr .")");
		Exam_stem::deleteAll("id in (". $exstemidstr .")");
		$qstems = Questi_stem::find()->where("id in (select qbank_stemid from exam_stem where id in (". $exstemidstr ."))")->all();
		foreach($qstems as $onestem){
			$onestem->reusage -= 1;
			if($onestem->reusage < 0){
				$onestem->reusage = 0;
			}
			$onestem->save();
		}
		echo json_encode(["code"=>"success","msg"=>"成功"]);
	}

	//获取可用题目数量
	public function actionMaxquest(){
		$questway = $this->request->post("questway");
		$questway = htmlspecialchars(strip_tags(trim($questway)));
		$rand_courseid = $this->request->post("rand_courseid");
		$rand_courseid = htmlspecialchars(strip_tags(trim($rand_courseid)));
		$rand_treeid = $this->request->post("rand_treeid");
		$rand_treeid = htmlspecialchars(strip_tags(trim($rand_treeid)));
		if(empty($rand_courseid) || !is_numeric($rand_courseid)){
			echo json_encode(["code"=>"failed", "msg"=>"请选择组卷范围"]);
			die();
		}
		$condition = "islocked=0 and courseid=". $rand_courseid;
		if($questway!=2){
			$condition .= " and (maxreusage=0 or reusage<maxreusage)";
		}
		if(!empty($rand_treeid) && is_numeric($rand_treeid)){
			$condition .= " and find_in_set('". $rand_treeid ."',treepath)";
		}
		$maxquest = [];
		$qtypes = Questi_type::find()->where("parentid>0")->all();
		foreach($qtypes as $onetype){
			$onetype->questnum = Questi_stem::find()->where("typechild=". $onetype->id ." and ". $condition)->count();
			$maxquest[] = ["id"=>$onetype->id, "name"=>$onetype->name, "questnum"=>$onetype->questnum];
		}
		echo json_encode(["code"=>"success", "msg"=>"成功", "data"=>$maxquest]);
	}

	//复制题库题目到考试
	public function CopyQuestStems2Exam($exam, $qustems, $epoints){
		if(empty($qustems)){return 0;}
		if(empty($epoints) || is_numeric($epoints)==false){$epoints = 10;}
		foreach($qustems as $oneqstem){
			$samestem = Exam_stem::find()->where("examid=". $exam->id ." and qbank_stemid=". $oneqstem->id)->one();
			if(!empty($samestem)){continue;}
			$ex_stem = new Exam_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->save();
			$oneqstem->options = Questi_option::find()->where("stemid=". $oneqstem->id)->orderby("code asc")->all();
			foreach ($oneqstem->options as $oneqoption) {
				$ex_option = new Exam_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->save();
			}
			$oneqstem->reusage += 1;
			$oneqstem->save();
		}
	}

	//计算题目总分
	public function CalcStemTotalPoints($examid){
		if(empty($examid) || !is_numeric($examid)){
			return false;
		}
		$exam = Exam::find()->where("id=". $examid)->one();
		if(empty($exam)){
			return false;
		}
		$dbh = Yii::$app->db;
		//题目总数
		$sql = "select count(*) as totalquest from exam_stem where examid=". $examid;
		$cmd = $dbh->createCommand($sql);
		$row = $cmd->queryOne();
		$totalquest = $row["totalquest"];
		if(empty($totalquest)){
			$totalquest = 0;
		}
		//试卷总分
		$sql = "select sum(points) as totalpoints from exam_stem where examid=". $examid;
		$cmd = $dbh->createCommand($sql);
		$row = $cmd->queryOne();
		$totalpoints = $row["totalpoints"];
		if(empty($totalpoints)){
			$totalpoints = 0;
		}
		//每道题分数
		$pingjunfen = 0;
		if($totalquest>0){
			$pingjunfen = round($totalpoints/$totalquest);
		}
		if(empty($exam->qtypejson)){
			$qtypejson = [];
			$qtypes = Questi_type::find()->where("parentid>0")->all();
			foreach($qtypes as $onetype){
				$qtypejson[] = ["id"=>$onetype->id, "name"=>$onetype->name, "questnum"=>0, "onepoints"=>$pingjunfen, "partpoints"=>0];
			}
			$exam->qtypejson = json_encode($qtypejson);
		}
		$qtypejson = json_decode($exam->qtypejson);
		foreach($qtypejson as $onetype){
			$questnum = Exam_stem::find()->where("examid=". $exam->id ." and typechild=". $onetype->id)->count();
			$sql = "select sum(points) as partpoints from exam_stem where examid=". $exam->id ." and typechild=". $onetype->id;
			$cmd = $dbh->createCommand($sql);
			$row = $cmd->queryOne();
			$partpoints = $row["partpoints"];
			if(empty($partpoints)){
				$partpoints = 0;
			}
			$onetype->questnum = $questnum;
			$onetype->partpoints = $partpoints;
		}
		$exam->questnum = $totalquest;
		$exam->points = $totalpoints;
		$exam->qtypejson = json_encode($qtypejson);
		$exam->save();
	}
		
}
?>