<?php

class InvigilatorController 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='common2';
	public $assetsUrl;
	public function init()
	{
		//$this->assetsUrl=$this->module->assetsUrl;
		//不再注册核心脚本，因为要生成两次Yii jquery 文件。
		//Yii::app()->getClientScript()->registerCoreScript('jquery');
	}
	/**
	 * @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
		);
	}

	/**
	 * 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'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'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('*'),
			),
		);
	}

	/**
	 * 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()
	{
		$model=new Invigilator;

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

		if(isset($_POST['Invigilator']))
		{
			$model->attributes=$_POST['Invigilator'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$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($id)
	{
		$model=$this->loadModel($id);

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

		if(isset($_POST['Invigilator']))
		{
			$model->attributes=$_POST['Invigilator'];
			if($model->save())
			{
				Yii::app()->user->setFlash('updated','延时成功！');
				$this->refresh();
			}
				//$this->redirect(array('view','id'=>$model->id));
		}

		$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('Invigilator');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

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

		$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=Invigilator::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']==='invigilator-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	public function actionUpdatetime()
	{
		$session=new CHttpSession;
		$session->open();
		$exam_id=$id=$session['exam_id'];
		$user_id=Yii::app()->user->id;
		$model_jk=Invigilator::model()->find('student_id=:user_id and exam_id=:exam_id',array(':user_id'=>$user_id,':exam_id'=>$exam_id));
		$jiankao['remaintime']=$_POST['newtime'];
		$model_jk->attributes=$jiankao;
		$model_jk->save(false);
	}
	public function actionList($classroom_id){
		$data=Exammanage::model()->findAll();
		$this->render('admin',array(
			'classroom_id'=>$classroom_id,
			'data'=>$data,
		));
	}
	//取所有数据
	public function actionQq($classroom_id){
		$order=Yii::app()->request->getPost('order');
		$sort=Yii::app()->request->getPost('sort');
		$page=Yii::app()->request->getPost('page');
		$rows=Yii::app()->request->getPost('rows');
		
		$fullname=Yii::app()->request->getPost('fullname');//查询学生姓名
		$exam_id=Yii::app()->request->getPost('exam_id');//考试id
		$condition_1="classroom_id='$classroom_id'";
		$condition_2="classroom_id='$classroom_id' and fullname='$fullname'";
		$condition=(empty($fullname))?$condition_1:$condition_2;
		
		$model=new Student;
		$criteria=new CDbCriteria(array(
			'order'=>"$sort $order",
			//'select'=>array('id','title'),//'id,title',
			//'select'=>'knowledgepoint.title,t.id,t.title',
			'condition'=>$condition,
			'limit'=>$rows,
			'offset'=>($page-1)*$rows,
		));

		$count = $model->count($criteria);
		//echo $count;
		//exit;
		$data=$model->findAll($criteria);
		$data_=Exammanage::model()->find("id='$exam_id'");
		$newarr=array();$i=0;
		foreach($data as $key=>$value)
		{	$student_id=$value['id'];
		
			$criteria2=new CDbCriteria(array(
				//'order'=>"$sort $order",
				//'select'=>array('id','title'),//'id,title',
				//'select'=>'knowledgepoint.title,t.id,t.title',
				'condition'=>"classroom_id=$classroom_id and exam_id=$exam_id and student_id=$student_id",
			));		
		
			$data2=Invigilator::model()->find($criteria2);
			$newarr[$i]['title']=$data_['title'];
			$newarr[$i]['student_id']=$value['id'];
			$newarr[$i]['fullname']=$value['fullname'];
			if(!empty($data))
			{
				$newarr[$i]['id']=$data2['id'];
				$newarr[$i]['starttime']=$data2['starttime'];
				$newarr[$i]['submittime']=$data2['submittime'];
				$newarr[$i]['remaintime']=$data2['remaintime'];
				if($data2['submitmark']<>null)
				{
					$newarr[$i]['submitmark']=($data2['submitmark'])?'Yes':'No';
					$newarr[$i]['cheatmark']=($data2['cheatmark'])?'Yes':'No';		
				}
			}else
			{
				$newarr[$i]['starttime']='';
				$newarr[$i]['submittime']='';
				$newarr[$i]['remaintime']='';
				$newarr[$i]['submitmark']='';
				$newarr[$i]['cheatmark']='';
			}
			$i++;
		}
		$data3=CJSON::encode($newarr);
		$data='{'.'"total":'.$count.','.'"rows":'.$data3.'}';
		echo $data;	
	}
	//---------------------->代交试卷
	public function actionReplaceSubmit()
	{
		$id=Yii::app()->request->getPost('id');
		$model=$this->loadModel($id);
		$model->attributes=array('submitmark'=>true,'submittime'=>date("Y-m-d H:i:s",time()+8*3600));
		if($model->update()){
			echo "yes";
		}			
	}
	//---------------------->设为作弊
	public function actionSetCheat()
	{
		$id=Yii::app()->request->getPost('id');
		$model=$this->loadModel($id);
		$model->attributes=array('cheatmark'=>true);
		if($model->update()){
			echo "yes";
		}		
	}	
	//>---------------------单行删除
	public function actionDeleterow(){
		$id=Yii::app()->request->getPost('id');
		$student_id=Yii::app()->request->getPost('student_id');
		$exam_id=Yii::app()->request->getPost('exam_id');
		$condition="student_id='$student_id' and exam_id='$exam_id'";
		$v1=Score::model()->deleteAllByAttributes(array('student_id'=>$student_id,'exam_id'=>$exam_id));
		$v2=Myexam::model()->deleteAllByAttributes(array('student_id'=>$student_id,'exam_id'=>$exam_id));
		$v3=$this->loadModel($id)->delete();
		if($v1 || $v2 || $v3){
			echo "yes";
		}
	}
	//>---------------多行删除
	public function actionDeleteall(){
		$arr=(array)(CJSON::decode(Yii::app()->request->getPost('qq')));
		$exam_id=Yii::app()->request->getPost('exam_id');
		foreach($arr as $value){
			$newarr[]=(array)$value;
		}
		$str='';
		//print_r($newarr);
		foreach($newarr as $value){
			$fullname=trim($value['fullname']);
			$student_id=$value['student_id'];
			$id=$value['id'];
			$v1=Score::model()->deleteAllByAttributes(array('student_id'=>$student_id,'exam_id'=>$exam_id));
			$v2=Myexam::model()->deleteAllByAttributes(array('student_id'=>$student_id,'exam_id'=>$exam_id));
			if(isset($id))
				$v3=$this->loadModel($id)->delete();
			else
				$v3=true;
			if($v1 || $v2 || $v3){
				$str.='删除考生《'.$fullname.'》成功！<br/>';
			}else
			{
				$str.='删除考生《'.$fullname.'》失败！<br/>';
			}            
		}
		echo $str;
	}
	//>---------------全部收卷
	public function actionSubmittest(){
		$classroom_id=Yii::app()->request->getPost('classroom_id');
		$data=Classroom::model()->find("id='$classroom_id'");
		$grade_id=$data->grade_id;
		$exam_id=Yii::app()->request->getPost('exam_id');
		$data=Student::model()->findAll("classroom_id='$classroom_id'");
		//取出所有这个班级的学生，一个一个循环
		foreach($data as $k=>$v)
		{	
			$student_id=$v['id'];
			//更新score
			$data=Score::model()->find("exam_id='$exam_id' and student_id='$student_id'");
			if(!isset($data))
			{
				$data=new Score;
				$data->attributes=array(
					'exam_id'=>$exam_id,
					'student_id'=>$student_id,
					'grade_id'=>$grade_id,
					'classroom_id'=>$classroom_id,
					'singlechoiceScore'=>0,
					'multichoiceScore'=>0,
					'judgeScore'=>0,
					'operateScore'=>0,
					'totalScore'=>0,
				);
				$data->save(false);
			}
			//更新invigilator
			$data=Invigilator::model()->find("exam_id='$exam_id' and student_id='$student_id'");
			if(!isset($data))
			{
				$data=new Invigilator;
				$data->attributes=array(
					'exam_id'=>$exam_id,
					'student_id'=>$student_id,
					'classroom_id'=>$classroom_id,
					'starttime'=>date("Y-m-d H:i:s",time()+8*3600),
					'submittime'=>date("Y-m-d H:i:s",time()+8*3600),
					'remaintime'=>0,
					'submitmark'=>true,
				);
				$data->save(false);
			}
			
		}
		echo "交卷成功";
	}
}
