<?php

class StudentController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column_exam';
	public $str_fullname;
	public $str_photo;
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','create','captcha','get_classroom_list'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('update','exam','receive','examlist'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	public function actionExamlist()
	{
		
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$this->layout='//layouts/column1';
		if($this->register)
		{
			Yii::app()->user->setFlash('reg_offed','注册已关闭！');
			$this->render('reg_offed');
			Yii::app()->end();
		}
		$model=new Student('create');

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Student']))
		{
				$model->attributes=$_POST['Student'];
				if($model->validate()){
					$photo=$model->photo=CUploadedFile::getInstance($model,'photo');
					if(isset($model->photo)){
						$filename=uniqid(); 
						$fileExtensionName=$photo->getExtensionName(); 				
						//$filename1=iconv("utf-8", "gb2312", $model->photo);
						//这里是处理中文的问题，非中文不需要   
						$uploadfile=Yii::app()->basePath."/../myfiles/students_photo/".$filename.".$fileExtensionName";  
						$model->photo->saveAs($uploadfile,true);//上传操作
						$model->photo="/myfiles/students_photo/".$filename.".$fileExtensionName"; 	
					}else
					{
						unset($model->photo);
					}				
				}

			if($model->save())
				//$this->redirect(array('view','id'=>$model->id));
				//$this->redirect(array('site/login'));
				{
				Yii::app()->user->setFlash('registered','注册成功！');
				$this->refresh();//当用户刷新时去掉提示，而不是重复提交。
				}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{	$this->layout='//layouts/column1';
		if(!isset(Yii::app()->user->id))
		{
			$this->redirect(array('site/login'));
		}
		else
		{
			//$model=$this->loadModel($id);
			$model=$this->loadModel(Yii::app()->user->id);
			//$model->scenario='update';
			//$model->setScenario('update');
			//unset($model->confirmPassword);
			$model->confirmPassword='';
			$model->password='';
		}
		//$model=$this->loadModel($id);
		//unset($model->password);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Student']))
		{
			$model->attributes=$_POST['Student'];
			
			if($model->password==""){unset($model->password);}
			if($model->validate()){
				$photo=$model->photo=CUploadedFile::getInstance($model,'photo');
				if(isset($model->photo)){
					$filename=uniqid(); 
					$fileExtensionName=$photo->getExtensionName(); 				
					//$filename1=iconv("utf-8", "gb2312", $model->photo);
					//这里是处理中文的问题，非中文不需要   
					$uploadfile=Yii::app()->basePath."/../myfiles/students_photo/".$filename.".$fileExtensionName";  
					$model->photo->saveAs($uploadfile,true);//上传操作
					$model->photo="/myfiles/students_photo/".$filename.".$fileExtensionName"; 	
				}else
				{
					unset($model->photo);
				}
			}
			
			if($model->save()){
				Yii::app()->user->setFlash('updated','修改成功！');
				$this->refresh();//当用户刷新时去掉提示，而不是重复提交。
				}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Student');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Student('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Student']))
			$model->attributes=$_GET['Student'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Student::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='student-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	public function actionGet_classroom_list($pid)
	{
		$model = Student::model()->getClassroomList($pid);

        foreach($model as $value=>$name)
        {
            echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
        }
	}
	/*开始考试，要求有考试id和用户id
	如果在myexam中有记录，则读取，如果没有则从exammanage中读取
	*/
	public function actionExam($exam_id)
	{	
		//echo $_SERVER['HTTP_REFERER'];
		//if($_SERVER['HTTP_REFERER']<>Yii::app()->request->hostInfo.'/exammanage/index')
		
		
		$session=new CHttpSession;
		$session->open();
		
		if($session['noback']=='noback')
		{
			unset($session['noback']);
			$this->redirect(array('/exammanage/index'));
		}
		/*
		if($session['exam_id']<>$exam_id)
		{
			Yii::app()->user->setFlash('shutoff','您已在考，稍后再试！');
			$this->render('shutoff');
			Yii::app()->end();
		}
		*/
	
		Yii::app()->clientScript->registerCoreScript('jquery');
		
		$session['exam_id']=$exam_id;
		$user_id=Yii::app()->user->id;

	
		/*如果myexam中有，则读取*/
		$data=Myexam::model()->find('exam_id=:exam_id and student_id=:user_id',array(':exam_id'=>$exam_id,':user_id'=>$user_id));
		$data3=Score::model()->find('exam_id=:exam_id and student_id=:user_id',array(':exam_id'=>$exam_id,':user_id'=>$user_id));

			
		
		//学生信息
		$data_student=Student::model()->find("id='$user_id'");	
		$this->str_fullname=$data_student->fullname;
		$this->str_photo=$data_student->photo;
		
		/*myexam中没有，从exammanage中读取*/
		if(isset($data)){
			if((isset($data3))?$data3->reexam:0)
			{
				Yii::app()->user->setFlash('reexamed','您已补考过！');
				$this->render('reexam');
				Yii::app()->end();
			}else
			{		/*
					if(isset($data3) && !$session['reexam'])
					{
						header("Content-type: text/html; charset=utf-8");
						echo 
						'
						<script type="text/javascript">  
							var r=confirm("真的要开始补考呢？\n点《确定》开始补考，点《取消》回到考试中心。")
						if (!r)
							{
							window.location.href="/exammanage/index"
							} 
						</script>  
						';
						//Yii::app()->end();
					}					
					$session['reexam']=true;
					*/
					$data2=Exammanage::model()->find('id='.$exam_id);
					$examtime=$data2->examTime;
					//各试题分值,要在前台显示
					$fenzhi_arr=explode(',',$data2->testScore);
					$dan_fenzhi=$fenzhi_arr[0];
					$duo_fenzhi=$fenzhi_arr[1];
					$pan_fenzhi=$fenzhi_arr[2];
					$cao_fenzhi=$fenzhi_arr[3];
					
					//补考取题及清除提交标志
					//清除提交标志
					$model_jk=Invigilator::model()->find('student_id=:user_id and exam_id=:exam_id',array(':user_id'=>$user_id,':exam_id'=>$exam_id));
					if($model_jk->submitmark)
					{
						$jiankao['submitmark']=false;
						$jiankao['starttime']=date("Y-m-d H:i:s",time()+8*3600);
						$model_jk->attributes=$jiankao;
						$model_jk->save(false);
					}else
					{
						$examtime=$model_jk->remaintime;
					}
					
					$dan_list=$singlechoicelist=$data->singlechoicelist;
					$duo_list=$multichoicelist=$data->multichoicelist;
					$pan_list=$judgelist=$data->judgelist;
					$cao_list=$operatelist=$data->operatelist;
					//总分是多少：
					$session['totalscore']=$totalscore=$data->totalScore;
					//取得单选试题
					$criteria=new CDbCriteria;
					$criteria->addInCondition('id',explode(',',$singlechoicelist));
					$data_danxuan=Singlechoice::model()->findAll($criteria);

					//取得多选试题
					$criteria=new CDbCriteria;
					$criteria->addInCondition('id',explode(',',$multichoicelist));
					$data_duoxuan=Multichoice::model()->findAll($criteria);

					//取得判断试题
					$criteria=new CDbCriteria;
					$criteria->addInCondition('id',explode(',',$judgelist));
					$data_panduan=Judge::model()->findAll($criteria);
					
					//取得操作试题
					$criteria=new CDbCriteria;
					$criteria->addInCondition('id',explode(',',$operatelist));
					$data_caozuo=Operation::model()->findAll($criteria);
					//如果score中没有数据的话，那么reexam不是false;
					if(!isset($data3)) $reexam_=false; else $reexam_=true;
					$model=new Score;
					$this->render('exam',array(
						'data_danxuan'=>$data_danxuan,
						'data_duoxuan'=>$data_duoxuan,
						'data_panduan'=>$data_panduan,
						'data_caozuo'=>$data_caozuo,
						'title'=>$data2->title,
						'exammode'=>$data2->examMode,
						'examtime'=>$examtime,
						'beforesubmit'=>$data2->beforeSubmit,
						'exam_id'=>$exam_id,
						'dan_list'=>$dan_list,
						'duo_list'=>$duo_list,
						'pan_list'=>$pan_list,
						'model'=>$model,
						'reexam'=>$reexam_,
						'dan_fenzhi'=>$dan_fenzhi,
						'duo_fenzhi'=>$duo_fenzhi,
						'pan_fenzhi'=>$pan_fenzhi,
						'cao_fenzhi'=>$cao_fenzhi,
						'totalscore'=>$totalscore,
					));			
			}


		}else
		{
			$data=Exammanage::model()->find('id='.$exam_id);
			$singlechoicelist=$data->singlechoicelist;
			$multichoicelist=$data->multichoicelist;
			$judgelist=$data->judgelist;
			$operatelist=$data->operatelist;
			$testScore=$data->testScore;
			$testCount=$data->testCount;
			$testRand=$data->testRand;
			$title=$data->title;
			$exammode=$data->examMode;
			$examtime=$data->examTime;
			$beforesubmit=$data->beforeSubmit;
			
			//各试题分值,要在前台显示
			$fenzhi_arr=explode(',',$testScore);
			$dan_fenzhi=$fenzhi_arr[0];
			$duo_fenzhi=$fenzhi_arr[1];
			$pan_fenzhi=$fenzhi_arr[2];
			$cao_fenzhi=$fenzhi_arr[3];
			
			//试题数量
			$test_count=explode(',',$testCount);
			$danxuan_count=$test_count[0];
			$duoxuan_count=$test_count[1];
			$panduan_count=$test_count[2];
			$caozuo_count=$test_count[3];
			//是否乱序
			$danxuan_rand=substr($testRand,0,1);
			$duoxuan_rand=substr($testRand,2,1);
			$panduan_rand=substr($testRand,4,1);
			$caozuo_rand=substr($testRand,6,1);
			
			//取得单选试题
			$criteria=new CDbCriteria;
			$criteria->addInCondition('id',explode(',',$singlechoicelist));
			$data_danxuan=Singlechoice::model()->findAll($criteria);
			//shuffle($data_danxuan);如果限制数量的话，则按数量取出
			if($danxuan_count!=0){
				$data_danxuan = array_slice($data_danxuan,0,$danxuan_count);
			}
			//如果要打乱顺序的话
			if($danxuan_rand){
				shuffle($data_danxuan);
			}
			$dan_list='';
			foreach($data_danxuan as $k=>$v)
			{
				(empty($dan_list))?$dan_list=$v['id']:$dan_list.=','.$v['id'];
			}
			//单选总分值
			$dan_total=count($data_danxuan)*$dan_fenzhi;
			//取得多选试题
			$criteria=new CDbCriteria;
			$criteria->addInCondition('id',explode(',',$multichoicelist));
			$data_duoxuan=Multichoice::model()->findAll($criteria);
			if($duoxuan_count!=0){
				$data_duoxuan = array_slice($data_duoxuan,0,$duoxuan_count);
			}
			//如果要打乱顺序的话
			if($duoxuan_rand){
				shuffle($data_duoxuan);
			}
			$duo_list='';
			foreach($data_duoxuan as $k=>$v)
			{
				(empty($duo_list))?$duo_list=$v['id']:$duo_list.=','.$v['id'];
			}
			//多选总分值
			$duo_total=count($data_duoxuan)*$duo_fenzhi;
			//取得判断试题
			$criteria=new CDbCriteria;
			$criteria->addInCondition('id',explode(',',$judgelist));
			$data_panduan=Judge::model()->findAll($criteria);
			//shuffle($data_danxuan);如果限制数量的话，则按数量取出
			if($panduan_count!=0){
				$data_panduan = array_slice($data_panduan,0,$panduan_count);
			}
			//如果要打乱顺序的话
			if($panduan_rand){
				shuffle($data_panduan);
			}
			$pan_list='';
			foreach($data_panduan as $k=>$v)
			{
				(empty($pan_list))?$pan_list=$v['id']:$pan_list.=','.$v['id'];
			}
			//判断总分值
			$pan_total=count($data_panduan)*$pan_fenzhi;
			//取得操作试题
			$criteria=new CDbCriteria;
			$criteria->addInCondition('id',explode(',',$operatelist));
			$data_caozuo=Operation::model()->findAll($criteria);
			//shuffle($data_caozuo);如果限制数量的话，则按数量取出
			if($caozuo_count!=0){
				$data_caozuo = array_slice($data_caozuo,0,$caozuo_count);
			}
			//如果要打乱顺序的话
			if($caozuo_rand){
				shuffle($data_caozuo);
			}
			$cao_list='';
			foreach($data_caozuo as $k=>$v)
			{
				(empty($cao_list))?$cao_list=$v['id']:$cao_list.=','.$v['id'];
			}
			//操作总分值
			$cao_total=count($data_caozuo)*$cao_fenzhi;
			$model=new Myexam;
			$data_myexam=array();
			$data_myexam['student_id']=Yii::app()->user->id;
			$data_myexam['exam_id']=$exam_id;
			$data_myexam['singlechoicelist']=$dan_list;
			$data_myexam['multichoicelist']=$duo_list;
			$data_myexam['judgelist']=$pan_list;
			$data_myexam['operatelist']=$cao_list;
			$session['totalscore']=$totalscore=$data_myexam['totalScore']=$dan_total+$duo_total+$pan_total+$cao_total;
			$model->attributes=$data_myexam;
			$model->save(false);
			
			
		/*监考相关，如果已经有数据，则更新，如果没有数据，则写入
		*/
		$data_jk=Invigilator::model()->find('student_id=:user_id and exam_id=:exam_id',array(':user_id'=>$user_id,':exam_id'=>$exam_id));//('studentid='.$sid);

		if(isset($data_jk))
		{//如果用户刷新浏览器的话，从这里取时间，使得时间不至于还是原来的给定时间。
			$examtime=$data_jk->remaintime;
		}else
		{//只有第一次进来，才执行这条语句，如果是再次进来或刷新则使用上面的语句。
			//写入监考
			$banji=Student::model()->find('id='.Yii::app()->user->id);
			$banji2=Classroom::model()->find('id='.$banji->classroom_id);
			$jiankao['student_id']=Yii::app()->user->id;
			$jiankao['exam_id']=$exam_id;
			$jiankao['classroom_id']=$banji->classroom_id;
			$jiankao['remaintime']=$examtime;
			$jiankao['starttime']=date("Y-m-d H:i:s",time()+8*3600);
			$model=new Invigilator;
			$model->attributes=$jiankao;
			$model->save(false);
	
		}			
			
			

			
			
			$model=new Score;
			$this->render('exam',array(
				'data_danxuan'=>$data_danxuan,
				'data_duoxuan'=>$data_duoxuan,
				'data_panduan'=>$data_panduan,
				'data_caozuo'=>$data_caozuo,
				'title'=>$title,
				'exammode'=>$exammode,
				'examtime'=>$examtime,
				'beforesubmit'=>$beforesubmit,
				'exam_id'=>$exam_id,
				'dan_list'=>$dan_list,
				'duo_list'=>$duo_list,
				'pan_list'=>$pan_list,
				'model'=>$model,
				'reexam'=>false,
				'dan_fenzhi'=>$dan_fenzhi,
				'duo_fenzhi'=>$duo_fenzhi,
				'pan_fenzhi'=>$pan_fenzhi,
				'cao_fenzhi'=>$cao_fenzhi,
				'totalscore'=>$totalscore,
			));		
		
		}

	}
	//传真考试
	public function actionExam3($exam_id)
	{	
		//echo $_SERVER['HTTP_REFERER'];
		//if($_SERVER['HTTP_REFERER']<>Yii::app()->request->hostInfo.'/exammanage/index')
		
		
		$session=new CHttpSession;
		$session->open();
		
		if($session['noback']=='noback')
		{
			unset($session['noback']);
			$this->redirect(array('/exammanage/index'));
		}
		/*
		if($session['exam_id']<>$exam_id)
		{
			Yii::app()->user->setFlash('shutoff','您已在考，稍后再试！');
			$this->render('shutoff');
			Yii::app()->end();
		}
		*/
	
		Yii::app()->clientScript->registerCoreScript('jquery');
		
		$session['exam_id']=$exam_id;
		$user_id=Yii::app()->user->id;

	
		/*如果myexam中有，则读取*/
		$data=Myexam::model()->find('exam_id=:exam_id and student_id=:user_id',array(':exam_id'=>$exam_id,':user_id'=>$user_id));
		$data3=Score::model()->find('exam_id=:exam_id and student_id=:user_id',array(':exam_id'=>$exam_id,':user_id'=>$user_id));

			
		
		//学生信息
		$data_student=Student::model()->find("id='$user_id'");	
		$this->str_fullname=$data_student->fullname;
		$this->str_photo=$data_student->photo;
		
		/*myexam中没有，从exammanage中读取*/
		if(isset($data)){//如果myexam中已经有了
			if((isset($data3))?$data3->reexam:0)
			{
				Yii::app()->user->setFlash('reexamed','您已补考过！');
				$this->render('reexam');
				Yii::app()->end();
			}else
			{		/*
					if(isset($data3) && !$session['reexam'])
					{
						header("Content-type: text/html; charset=utf-8");
						echo 
						'
						<script type="text/javascript">  
							var r=confirm("真的要开始补考呢？\n点《确定》开始补考，点《取消》回到考试中心。")
						if (!r)
							{
							window.location.href="/exammanage/index"
							} 
						</script>  
						';
						//Yii::app()->end();
					}					
					$session['reexam']=true;
					*/
					$data2=Exammanage::model()->find('id='.$exam_id);
					$examtime=$data2->examTime;
					//各试题分值,要在前台显示
					$fenzhi_arr=explode(',',$data2->testScore);
					$dan_fenzhi=$fenzhi_arr[0];
					$duo_fenzhi=$fenzhi_arr[1];
					$pan_fenzhi=$fenzhi_arr[2];
					$cao_fenzhi=$fenzhi_arr[3];
					
					//补考取题及清除提交标志
					//清除提交标志
					$model_jk=Invigilator::model()->find('student_id=:user_id and exam_id=:exam_id',array(':user_id'=>$user_id,':exam_id'=>$exam_id));
					if($model_jk->submitmark)
					{
						$jiankao['submitmark']=false;
						$jiankao['starttime']=date("Y-m-d H:i:s",time()+8*3600);
						$model_jk->attributes=$jiankao;
						$model_jk->save(false);
					}else
					{
						$examtime=$model_jk->remaintime;
					}
					
					$dan_list=$singlechoicelist=$data->singlechoicelist;
					$duo_list=$multichoicelist=$data->multichoicelist;
					$pan_list=$judgelist=$data->judgelist;
					$cao_list=$operatelist=$data->operatelist;
					//总分是多少：
					$session['totalscore']=$totalscore=$data->totalScore;
					//取得单选试题
					$criteria=new CDbCriteria;
					$criteria->addInCondition('id',explode(',',$singlechoicelist));
					$data_danxuan=Singlechoice::model()->findAll($criteria);

					//取得多选试题
					$criteria=new CDbCriteria;
					$criteria->addInCondition('id',explode(',',$multichoicelist));
					$data_duoxuan=Multichoice::model()->findAll($criteria);

					//取得判断试题
					$criteria=new CDbCriteria;
					$criteria->addInCondition('id',explode(',',$judgelist));
					$data_panduan=Judge::model()->findAll($criteria);
					
					//取得操作试题
					$criteria=new CDbCriteria;
					$criteria->addInCondition('id',explode(',',$operatelist));
					$data_caozuo=Operation::model()->findAll($criteria);
					//如果score中没有数据的话，那么reexam不是false;
					if(!isset($data3)) $reexam_=false; else $reexam_=true;
					$model=new Score;
					$this->render('exam',array(
						'data_danxuan'=>$data_danxuan,
						'data_duoxuan'=>$data_duoxuan,
						'data_panduan'=>$data_panduan,
						'data_caozuo'=>$data_caozuo,
						'title'=>$data2->title,
						'exammode'=>$data2->examMode,
						'examtime'=>$examtime,
						'beforesubmit'=>$data2->beforeSubmit,
						'exam_id'=>$exam_id,
						'dan_list'=>$dan_list,
						'duo_list'=>$duo_list,
						'pan_list'=>$pan_list,
						'model'=>$model,
						'reexam'=>$reexam_,
						'dan_fenzhi'=>$dan_fenzhi,
						'duo_fenzhi'=>$duo_fenzhi,
						'pan_fenzhi'=>$pan_fenzhi,
						'cao_fenzhi'=>$cao_fenzhi,
						'totalscore'=>$totalscore,
					));			
			}


		}else//myexam中没有
		{
			$data=Exammanage::model()->find('id='.$exam_id);
			$singlechoicelist=$data->singlechoicelist;
			$multichoicelist=$data->multichoicelist;
			$judgelist=$data->judgelist;
			$operatelist=$data->operatelist;
			$testScore=$data->testScore;
			$testCount=$data->testCount;
			$testRand=$data->testRand;
			$title=$data->title;
			$exammode=$data->examMode;
			$examtime=$data->examTime;
			$beforesubmit=$data->beforeSubmit;
			
			//各试题分值,要在前台显示
			$fenzhi_arr=explode(',',$testScore);
			$dan_fenzhi=$fenzhi_arr[0];
			$duo_fenzhi=$fenzhi_arr[1];
			$pan_fenzhi=$fenzhi_arr[2];
			$cao_fenzhi=$fenzhi_arr[3];
			
			//试题数量
			$test_count=explode(',',$testCount);
			$danxuan_count=$test_count[0];
			$duoxuan_count=$test_count[1];
			$panduan_count=$test_count[2];
			$caozuo_count=$test_count[3];
			//是否乱序
			$danxuan_rand=substr($testRand,0,1);
			$duoxuan_rand=substr($testRand,2,1);
			$panduan_rand=substr($testRand,4,1);
			$caozuo_rand=substr($testRand,6,1);
			
			//取得单选试题
			$criteria=new CDbCriteria;
			$criteria->addInCondition('charpter_id',explode(',',$singlechoicelist));
			$data_danxuan=Singlechoice::model()->findAll($criteria);
			//shuffle($data_danxuan);如果限制数量的话，则按数量取出
			if($danxuan_count!=0){
				$data_danxuan = array_slice($data_danxuan,0,$danxuan_count);
			}
			//如果要打乱顺序的话
			if($danxuan_rand){
				shuffle($data_danxuan);
			}
			$dan_list='';
			foreach($data_danxuan as $k=>$v)
			{
				(empty($dan_list))?$dan_list=$v['id']:$dan_list.=','.$v['id'];
			}
			//单选总分值
			$dan_total=count($data_danxuan)*$dan_fenzhi;
			//取得多选试题
			$criteria=new CDbCriteria;
			$criteria->addInCondition('charpter_id',explode(',',$multichoicelist));
			$data_duoxuan=Multichoice::model()->findAll($criteria);
			if($duoxuan_count!=0){
				$data_duoxuan = array_slice($data_duoxuan,0,$duoxuan_count);
			}
			//如果要打乱顺序的话
			if($duoxuan_rand){
				shuffle($data_duoxuan);
			}
			$duo_list='';
			foreach($data_duoxuan as $k=>$v)
			{
				(empty($duo_list))?$duo_list=$v['id']:$duo_list.=','.$v['id'];
			}
			//多选总分值
			$duo_total=count($data_duoxuan)*$duo_fenzhi;
			//取得判断试题
			$criteria=new CDbCriteria;
			$criteria->addInCondition('charpter_id',explode(',',$judgelist));
			$data_panduan=Judge::model()->findAll($criteria);
			//shuffle($data_danxuan);如果限制数量的话，则按数量取出
			if($panduan_count!=0){
				$data_panduan = array_slice($data_panduan,0,$panduan_count);
			}
			//如果要打乱顺序的话
			if($panduan_rand){
				shuffle($data_panduan);
			}
			$pan_list='';
			foreach($data_panduan as $k=>$v)
			{
				(empty($pan_list))?$pan_list=$v['id']:$pan_list.=','.$v['id'];
			}
			//判断总分值
			$pan_total=count($data_panduan)*$pan_fenzhi;
			//取得操作试题
			$criteria=new CDbCriteria;
			$criteria->addInCondition('charpter_id',explode(',',$operatelist));
			$data_caozuo=Operation::model()->findAll($criteria);
			//shuffle($data_caozuo);如果限制数量的话，则按数量取出
			if($caozuo_count!=0){
				$data_caozuo = array_slice($data_caozuo,0,$caozuo_count);
			}
			//如果要打乱顺序的话
			if($caozuo_rand){
				shuffle($data_caozuo);
			}
			$cao_list='';
			foreach($data_caozuo as $k=>$v)
			{
				(empty($cao_list))?$cao_list=$v['id']:$cao_list.=','.$v['id'];
			}
			//操作总分值
			$cao_total=count($data_caozuo)*$cao_fenzhi;
			$model=new Myexam;
			$data_myexam=array();
			$data_myexam['student_id']=Yii::app()->user->id;
			$data_myexam['exam_id']=$exam_id;
			$data_myexam['singlechoicelist']=$dan_list;
			$data_myexam['multichoicelist']=$duo_list;
			$data_myexam['judgelist']=$pan_list;
			$data_myexam['operatelist']=$cao_list;
			$session['totalscore']=$totalscore=$data_myexam['totalScore']=$dan_total+$duo_total+$pan_total+$cao_total;
			$model->attributes=$data_myexam;
			$model->save(false);
			
			
		/*监考相关，如果已经有数据，则更新，如果没有数据，则写入
		*/
		$data_jk=Invigilator::model()->find('student_id=:user_id and exam_id=:exam_id',array(':user_id'=>$user_id,':exam_id'=>$exam_id));//('studentid='.$sid);

		if(isset($data_jk))
		{//如果用户刷新浏览器的话，从这里取时间，使得时间不至于还是原来的给定时间。
			$examtime=$data_jk->remaintime;
		}else
		{//只有第一次进来，才执行这条语句，如果是再次进来或刷新则使用上面的语句。
			//写入监考
			$banji=Student::model()->find('id='.Yii::app()->user->id);
			$banji2=Classroom::model()->find('id='.$banji->classroom_id);
			$jiankao['student_id']=Yii::app()->user->id;
			$jiankao['exam_id']=$exam_id;
			$jiankao['classroom_id']=$banji->classroom_id;
			$jiankao['remaintime']=$examtime;
			$jiankao['starttime']=date("Y-m-d H:i:s",time()+8*3600);
			$model=new Invigilator;
			$model->attributes=$jiankao;
			$model->save(false);
	
		}			
			
			

			
			
			$model=new Score;
			$this->render('exam',array(
				'data_danxuan'=>$data_danxuan,
				'data_duoxuan'=>$data_duoxuan,
				'data_panduan'=>$data_panduan,
				'data_caozuo'=>$data_caozuo,
				'title'=>$title,
				'exammode'=>$exammode,
				'examtime'=>$examtime,
				'beforesubmit'=>$beforesubmit,
				'exam_id'=>$exam_id,
				'dan_list'=>$dan_list,
				'duo_list'=>$duo_list,
				'pan_list'=>$pan_list,
				'model'=>$model,
				'reexam'=>false,
				'dan_fenzhi'=>$dan_fenzhi,
				'duo_fenzhi'=>$duo_fenzhi,
				'pan_fenzhi'=>$pan_fenzhi,
				'cao_fenzhi'=>$cao_fenzhi,
				'totalscore'=>$totalscore,
			));		
		
		}

	}

	public function actionReceive()
	{
		$this->layout='//layouts/column1';
		$arr_az=array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
		$session=new CHttpSession;
		$session->open();
		$exam_id=$id=$session['exam_id'];
		$totalscore=$session['totalscore'];
		$user_id=Yii::app()->user->id;
		$session['noback']='noback';
		//取得各题型分值
		$data_fenzhi=Exammanage::model()->findByAttributes(array('id'=>$id));
		$fenzhi_arr=explode(',',$data_fenzhi->testScore);
		$dan_fenzhi=$fenzhi_arr[0];
		$duo_fenzhi=$fenzhi_arr[1];
		$pan_fenzhi=$fenzhi_arr[2];

		$data_sc=Score::model()->find('exam_id='.$id.' and '.'student_id='.Yii::app()->user->id);
		$data_sc2=Score::model()->find('exam_id='.$id.' and '.'student_id='.Yii::app()->user->id.' and reexam=1');

		if((isset($data_sc) && !$_POST['reexam']) || isset($data_sc2))
		{
			
			Yii::app()->user->setFlash('received','您已提交成功！');
			$this->render('receive',array(
				'totalscore'=>$totalscore,
				'mytotalscore'=>$data_sc->totalScore,				
			));
			Yii::app()->end();
			//$this->refresh();
		}
		//取得试题列表
		//echo $_POST['dan_list'];exit;
		$dan_arr=explode(',',$_POST['dan_list']);
		$duo_arr=explode(',',$_POST['duo_list']);
		$pan_arr=explode(',',$_POST['pan_list']);
		//取学生单选答案
		if(isset($_POST['singlechoice']))
		$dan_answer=$_POST['singlechoice'];
		else
		$dan_answer=array();
		
		//取单选答案------------------------------------判分
		$criteria=new CDbCriteria;
		$criteria->addInCondition('id',$dan_arr);
		$data_single=Singlechoice::model()->findAll($criteria);
		//echo "<pre>";
		//print_r($data_single);
		//对比答案
		$dan_score=0;//单选题总分
		$dan_error='';//单选题错题列表
		$dan_right='';//单选题对题列表
		$onoff=false;
		foreach($data_single as $k=>$v)
		{
			foreach($dan_answer as $k2=>$v2)
			{
				if($v['id']==$k2 && $v['answer']==$arr_az[$v2])
				{//如果正确，则判分
					$dan_score+=$dan_fenzhi;
					(empty($dan_right))?$dan_right=$v['id']:$dan_right.=','.$v['id'];//加入对题列表
					$onoff=true;
				}
			}
			if(!$onoff)(empty($dan_error))?$dan_error=$v['id']:$dan_error.=','.$v['id'];//否则加入错题列表
			$onoff=false;//得重新置回去
		}
		//echo $dan_error;
		//echo "<pre>";echo $dan_score;
		//print_r($dan_answer);exit;
		
		if(isset($_POST['multichoice']))
		{
			$qq=$_POST['multichoice'];
			foreach($qq as $key => $value)
			{	
				$str_='';
				foreach($value as $k_=>$v_)
				{
					$str_.=$arr_az[$v_];
				}
				$duo_answer[$key]=$str_;//implode('',$value);
			}
		}
		else
		$duo_answer=array();
		//echo "<pre>";
		//print_r($duo_answer);exit;
		
		//取多选答案------------------------------------判分
		$criteria=new CDbCriteria;
		$criteria->addInCondition('id',$duo_arr);
		$data_multi=Multichoice::model()->findAll($criteria);
		//echo "<pre>";
		//print_r($data_single);
		//对比答案
		$duo_score=0;//多选题总分
		$duo_error='';//多选题错题列表
		$duo_right='';//多选题对题列表
		$onoff=false;
		foreach($data_multi as $k=>$v)
		{
			foreach($duo_answer as $k2=>$v2)
			{
				if($v['id']==$k2 && $v['answer']==$v2)
				{//如果正确，则判分
					$duo_score+=$duo_fenzhi;
					(empty($duo_right))?$duo_right=$v['id']:$duo_right.=','.$v['id'];//加入对题列表
					$onoff=true;
				}
			}
			if(!$onoff)(empty($duo_error))?$duo_error=$v['id']:$duo_error.=','.$v['id'];//否则加入错题列表
			$onoff=false;//得重新置回去
		}
		//echo $duo_error;
		//echo "<pre>";echo $duo_score;
		//print_r($dan_answer);exit;
		
		
		if(isset($_POST['judge']))
			$pan_answer=$_POST['judge'];
		else
			$pan_answer=array();
		//echo "<pre>";
		//print_r($pan_answer);exit;
		
		//取判断答案------------------------------------判分
		$criteria=new CDbCriteria;
		$criteria->addInCondition('id',$pan_arr);
		$data_judge=Judge::model()->findAll($criteria);
		//echo "<pre>";
		//print_r($data_judge);
		//对比答案
		$pan_score=0;//判断题总分
		$pan_error='';//判断题错题列表
		$pan_right='';//判断题对题列表
		$onoff=false;
		foreach($data_judge as $k=>$v)
		{
			foreach($pan_answer as $k2=>$v2)
			{
				if($v['id']==$k2 && $v['answer']==$v2)
				{//如果正确，则判分
					$pan_score+=$pan_fenzhi;
					(empty($pan_right))?$pan_right=$v['id']:$pan_right.=','.$v['id'];//加入对题列表
					$onoff=true;
				}
			}
			if(!$onoff)(empty($pan_error))?$pan_error=$v['id']:$pan_error.=','.$v['id'];//否则加入错题列表
			$onoff=false;//得重新置回去
		}
		//echo $pan_error;
		//echo "<pre>";echo $pan_score;
		//print_r($pan_answer);exit;		
		
		//上传操作题
		if($_POST['reexam'])
		{//如果是重考，则更新
			$model=Score::model()->find('exam_id=:exam_id and student_id=:user_id',array(':exam_id'=>$exam_id,':user_id'=>$user_id));
		}else
		{//如果不是重考，则新建
			$model=new Score;		
		}
		$operateAnswer=$model->operateAnswer=CUploadedFile::getInstances($model,'operateAnswer');
		//echo "<pre>";
		//print_r($operateAnswer);
		$str_operate_answer='';
		foreach($operateAnswer as $k=>$v){
			$filename=uniqid(); 
			$fileExtensionName=$v->getExtensionName(); 				
			$uploadfile=Yii::app()->basePath."/../myfiles/operation_answer/".$filename.".$fileExtensionName";  
			$v->saveAs($uploadfile,true);//上传操作
			$str_="/myfiles/operation_answer/".$filename.".$fileExtensionName";
			empty($str_operate_answer)?$str_operate_answer=$str_:$str_operate_answer.=','.$str_;
		}
		//echo $str_operate_answer;
		$user_id=Yii::app()->user->id;
		$student=Student::model()->findByAttributes(array('id'=>$user_id));
				
		$dataScore_arr['student_id']=$user_id;
		$dataScore_arr['classroom_id']=$student->classroom_id;
		$dataScore_arr['grade_id']=$student->grade_id;
		$dataScore_arr['exam_id']=$session['exam_id'];
		$dataScore_arr['singlechoiceScore']=$dan_score;
		$dataScore_arr['multichoiceScore']=$duo_score;
		$dataScore_arr['judgeScore']=$pan_score;
		$mytotalscore=$dataScore_arr['totalScore']=$dan_score+$duo_score+$pan_score;
		$dataScore_arr['singlechoiceError']=$dan_error;
		$dataScore_arr['multichoiceError']=$duo_error;
		$dataScore_arr['judgeError']=$pan_error;
		$dataScore_arr['operateAnswer']=$str_operate_answer;
		$dataScore_arr['reexam']=$_POST['reexam'];
		$model->attributes=$dataScore_arr;
		//----------->提交时写入监考表
		$model_jk=Invigilator::model()->find('student_id=:user_id and exam_id=:exam_id',array(':user_id'=>$user_id,':exam_id'=>$exam_id));
		$jiankao['submitmark']=true;
		$jiankao['submittime']=date("Y-m-d H:i:s",time()+8*3600);
		$model_jk->attributes=$jiankao;
		$model_jk->save(false);
		//-----------结束
		//------------>更新难度，只要错了就减一,做对了就加一
		//单选难度更新
		$criteria=new CDbCriteria;
		$criteria->addInCondition('id',explode(',',$dan_error));
		Singlechoice::model()->updateCounters(array('difficulty'=>-1),$criteria);//自动-1
		
		$criteria=new CDbCriteria;
		$criteria->addInCondition('id',explode(',',$dan_right));
		Singlechoice::model()->updateCounters(array('difficulty'=>1),$criteria);//自动+1
		//多选难度更新
		$criteria=new CDbCriteria;
		$criteria->addInCondition('id',explode(',',$duo_error));
		Multichoice::model()->updateCounters(array('difficulty'=>-1),$criteria);//自动-1
		
		$criteria=new CDbCriteria;
		$criteria->addInCondition('id',explode(',',$duo_right));
		Multichoice::model()->updateCounters(array('difficulty'=>1),$criteria);//自动+1
		//判断难度更新
		$criteria=new CDbCriteria;
		$criteria->addInCondition('id',explode(',',$pan_error));
		Judge::model()->updateCounters(array('difficulty'=>-1),$criteria);//自动-1
		
		$criteria=new CDbCriteria;
		$criteria->addInCondition('id',explode(',',$pan_right));
		Judge::model()->updateCounters(array('difficulty'=>1),$criteria);//自动+1
		//------------>结束
		//更新错题集--------------------->开始
		
		$student_id=Yii::app()->user->id;
			//如果不存在此记录
			//更新单选errorset
			$model_ctj=Errorset::model()->find("student_id=$student_id");$str='';
			if(empty($model_ctj))
			{
				$model_ctj=new Errorset();
				$model_ctj->attributes=array('singleError'=>$dan_error,'student_id'=>$student_id);
				$model_ctj->save(false);
			}else
			{//如果已经存在此记录
				if(empty($model_ctj->singleError))
				{$str=$dan_error;}
				else
				{
    				//
					$arr_dan_error=explode(',',$dan_error);
					$arr_single_error=explode(',',$model_ctj->singleError);
					$arr3=array_merge($arr_dan_error,$arr_single_error);
					$arr4=array_unique($arr3);

    				$str=implode(',',$arr4);
				
				}
				$model_ctj->attributes=array('singleError'=>$str);
				$model_ctj->update();			
			}
			//更新多选errorset
			$model_ctj=Errorset::model()->find("student_id=$student_id");$str='';
			if(empty($model_ctj))
			{
				$model_ctj=new Errorset();
				$model_ctj->attributes=array('multiError'=>$duo_error,'student_id'=>$student_id);
				$model_ctj->save(false);
			}else
			{//如果已经存在此记录
				if(empty($model_ctj->multiError))
				{$str=$duo_error;}
				else
				{
    				//
					$arr_dan_error=explode(',',$duo_error);
					$arr_single_error=explode(',',$model_ctj->multiError);
					$arr3=array_merge($arr_dan_error,$arr_single_error);
					$arr4=array_unique($arr3);

    				$str=implode(',',$arr4);
				
				}
				$model_ctj->attributes=array('multiError'=>$str);
				$model_ctj->update();			
			}
			//更新判断errorset
			$model_ctj=Errorset::model()->find("student_id=$student_id");$str='';
			if(empty($model_ctj))
			{
				$model_ctj=new Errorset();
				$model_ctj->attributes=array('judgeError'=>$pan_error,'student_id'=>$student_id);
				$model_ctj->save(false);
			}else
			{//如果已经存在此记录
				if(empty($model_ctj->judgeError))
				{$str=$pan_error;}
				else
				{
    				//
					$arr_dan_error=explode(',',$pan_error);
					$arr_single_error=explode(',',$model_ctj->judgeError);
					$arr3=array_merge($arr_dan_error,$arr_single_error);
					$arr4=array_unique($arr3);

    				$str=implode(',',$arr4);
				
				}
				$model_ctj->attributes=array('judgeError'=>$str);
				$model_ctj->update();			
			}
			
		//------------------------------->结束
		if($model->save(false)){//用false取消验证。
						
				Yii::app()->user->setFlash('received','提交成功！');
				//unset($session['exam_id']);
				//$session['reexam']=false;
				$this->render('receive',array(
					'totalscore'=>$totalscore,
					'mytotalscore'=>$mytotalscore,
				));
				//$this->refresh();//当用户刷新时去掉提示，而不是重复提交。
				}	
	}

}
