<?php

class AssignController 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';

	/**
	 * @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($classroom_id=null,$exam_id=null)
	{
		$model=new Assign;

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

		if(isset($_POST['Assign']))
		{
			$_POST['Assign']['score_list']=Yii::app()->session['operatelist'];
			$model->attributes=$_POST['Assign'];
			if($model->save())
				{
				unset(Yii::app()->session['operatelist']);
				header('Content-Type: text/html; charset=utf-8');
				echo "<script>alert('添加成功！请继续添加！');history.back(-1)</script>";
				Yii::app()->end();
				}
		}
		
		$data2=Assign::model()->findAll("classroom_id='$classroom_id' and exam_id='$exam_id'");
		$str='';
		foreach($data2 as $k=>$v)
		{
			empty($str)? $str=$v['assistant_id'] : $str.=','.$v['assistant_id'];
		}
		$arr_not_in=explode(',',$str);		
		
		$criteria=new CDbCriteria(array(
		'select'=>array('id','fullname'),
		'condition'=>"classroom_id=$classroom_id",
		));
		
		$criteria->addNotInCondition('id',$arr_not_in);
		$assistant=Assistant::model()->findAll($criteria);
		
		
		
		$model->classroom_id=$classroom_id;
		$model->exam_id=$exam_id;
		$this->render('create',array(
			'model'=>$model,
			'assistant'=>$assistant,
		));
	}

	/**
	 * 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($classroom_id=null,$exam_id=null,$id)
	{
		$model=$this->loadModel($id);
		Yii::app()->session['operatelist2']=$model->score_list;
		//$model=Assign::model()->find("classroom_id='$classroom_id' and exam_id='$exam_id' and id='$id'");
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Assign']))
		{
			$_POST['Assign']['score_list']=Yii::app()->session['operatelist'];
			$model->attributes=$_POST['Assign'];
			if($model->save())
				{
				unset(Yii::app()->session['operatelist']);
				header('Content-Type: text/html; charset=utf-8');
				echo "<script>alert('修改成功！请关闭此窗口！');window.location.reload();</script>";
				Yii::app()->end();
				}
		}
		/*取得已经用去的助手，并把他们删除掉，现在是更新，所以要留下当前的助手*/
		
		$data2=Assign::model()->findAll("classroom_id='$classroom_id' and exam_id='$exam_id'");
		$str='';
		foreach($data2 as $k=>$v)
		{
			if($v['assistant_id']<>$model->assistant_id)
			empty($str)? $str=$v['assistant_id'] : $str.=','.$v['assistant_id'];
		}
		$arr_not_in=explode(',',$str);		
		
		$criteria=new CDbCriteria(array(
		'select'=>array('id','fullname'),
		'condition'=>"classroom_id=$classroom_id",
		));
		
		$criteria->addNotInCondition('id',$arr_not_in);
		$assistant=Assistant::model()->findAll($criteria);


		//$model->classroom_id=$classroom_id;
		//$model->exam_id=$exam_id;
		//$model->assistant_id=10;
		$this->render('update',array(
			'model'=>$model,
			'assistant'=>$assistant,			
		));
	}

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

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

		$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 $id the ID of the model to be loaded
	 * @return Assign the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Assign::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Assign $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='assign-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	public function actionList($classroom_id){
		$data=Exammanage::model()->findAll();
		$this->render('admin',array(
			'classroom_id'=>$classroom_id,
			'data'=>$data,
		));
	}
	public function actionQq($classroom_id=null){
		$order=Yii::app()->request->getPost('order');
		$sort=Yii::app()->request->getPost('sort');
		$page=Yii::app()->request->getPost('page');
		$rows=Yii::app()->request->getPost('rows');
		
		$exam_id=Yii::app()->request->getPost('exam_id');//查询标题
		//$condition_1="t.classroom_id='$classroom_id'";
		$condition="t.classroom_id='$classroom_id' and t.exam_id='$exam_id'";
		//$condition=(isset($exam_id))?$condition_2:$condition_1;
		
		$model=new Assign;
		$criteria=new CDbCriteria(array(
			'order'=>"t.$sort $order",
			//'select'=>array('id','title'),//'id,title',
			//'select'=>'knowledgepoint.title,t.id,t.title',
			'condition'=>$condition,
			'limit'=>$rows,
			'offset'=>($page-1)*$rows,
			'with'=>array('assign_fullname'),
		));

		$count = $model->count($criteria);
		//exit;
		$data3=$model->findAll($criteria);
		$json = new CArJSON();
		// Define which relations do you want to load
		$relations = array('assign_fullname');
		// Define which attributes, foreach relations do you want to load
		// root denote attributes for the main model
		$attributes = array(
			'root' => array('id','score_list'),//表示主表中的字段
			'assign_fullname' => array( 'fullname' ),//表示从表中的字段
			//'votes' => null, // This will load all attributes
		);
		$data=$json->toJSON($data3, $relations, $attributes);
		//print_r(CJSON::decode($data));
		$i=0;$newarr=array();
		foreach(CJSON::decode($data) as $key=>$value)
		{
			//echo $key;echo $value['attributes']['id'];
			$newarr[$i]['id']=$value['attributes']['id'];
			//$newarr[$i]['title']=$value['attributes']['title'];
			$newarr[$i]['score_list']=$value['attributes']['score_list'];
			$newarr[$i]['fullname']=$value['relations']['assign_fullname']['fullname'];$i++;
		}

			$data2=CJSON::encode($newarr);
			$data='{'.'"total":'.$count.','.'"rows":'.$data2.'}';
			echo $data;	
	}
	//此动作用于创建
	public function actionQq2(){
		$order=Yii::app()->request->getPost('order');
		$sort=Yii::app()->request->getPost('sort');
		$page=Yii::app()->request->getPost('page');
		$rows=Yii::app()->request->getPost('rows');
		
		$classroom_id=Yii::app()->request->getPost('classroom_id');//查询标题
		$exam_id=Yii::app()->request->getPost('exam_id');//查询标题
		//$condition_1="t.classroom_id='$classroom_id'";
		$condition="t.classroom_id='$classroom_id' and t.exam_id='$exam_id'";
		//$condition=(isset($exam_id))?$condition_2:$condition_1;
		
		$session=new CHttpSession;
		$session->open();
		
		$data=$session['operatelist'];
		$arr2=explode(",",$data);
		$data2=Assign::model()->findAll("classroom_id='$classroom_id' and exam_id='$exam_id'");
		$str='';
		foreach($data2 as $k=>$v)
		{
			empty($str)? $str=$v['score_list'] : $str.=','.$v['score_list'];
		}
		$arr3=explode(',',$str);
		$arr4=array_merge($arr2,$arr3);
		$arr_not_in=array_unique($arr4);
		
		$model=new Score;
		$criteria=new CDbCriteria(array(
			'order'=>"t.$sort $order",
			//'select'=>array('id','title'),//'id,title',
			//'select'=>'knowledgepoint.title,t.id,t.title',
			'condition'=>$condition,
			'limit'=>$rows,
			'offset'=>($page-1)*$rows,
			'with'=>array('student_fullname'),
		));
		$criteria->addNotInCondition('t.id',$arr_not_in);
		$count = $model->count($criteria);
		//exit;
		$data3=$model->findAll($criteria);
		$json = new CArJSON();
		// Define which relations do you want to load
		$relations = array('student_fullname');
		// Define which attributes, foreach relations do you want to load
		// root denote attributes for the main model
		$attributes = array(
			'root' => array('id','singlechoiceScore','multichoiceScore','judgeScore','operateScore','totalScore','reexam'),//表示主表中的字段
			'student_fullname' => array( 'fullname' ),//表示从表中的字段
			//'votes' => null, // This will load all attributes
		);
		$data=$json->toJSON($data3, $relations, $attributes);
		//print_r(CJSON::decode($data));
		$newarr=array();
		foreach(CJSON::decode($data) as $key=>$value)
		{
			$newarr[]=array(
				'id'=>$value['attributes']['id'],
				'operateScore'=>$value['attributes']['operateScore'],
				'fullname'=>$value['relations']['student_fullname']['fullname'],
			);
			//echo $key;echo $value['attributes']['id'];
			//$newarr[$i]['title']=$value['attributes']['title'];
			//$newarr[$i]['singlechoiceScore']=$value['attributes']['singlechoiceScore'];
			//$newarr[$i]['multichoiceScore']=$value['attributes']['multichoiceScore'];
			//$newarr[$i]['judgeScore']=$value['attributes']['judgeScore'];
			//$newarr[$i]['totalScore']=$value['attributes']['totalScore'];
			//$newarr[$i]['reexam']=($value['attributes']['reexam'])?'Yes':'No';
		}

			$data2=CJSON::encode($newarr);
			$data='{'.'"total":'.$count.','.'"rows":'.$data2.'}';
			echo $data;	
	}
	//此动作用于更新
	public function actionQq3(){
		$order=Yii::app()->request->getPost('order');
		$sort=Yii::app()->request->getPost('sort');
		$page=Yii::app()->request->getPost('page');
		$rows=Yii::app()->request->getPost('rows');
		
		$classroom_id=Yii::app()->request->getPost('classroom_id');//查询标题
		$exam_id=Yii::app()->request->getPost('exam_id');//查询标题
		//$condition_1="t.classroom_id='$classroom_id'";
		$condition="t.classroom_id='$classroom_id' and t.exam_id='$exam_id'";
		//$condition=(isset($exam_id))?$condition_2:$condition_1;
		$session=new CHttpSession;
		$session->open();
		//所有已使用的减去当前的+session为Notin。下面是所有已使用的
		$data2=Assign::model()->findAll("classroom_id='$classroom_id' and exam_id='$exam_id'");
		$str='';
		foreach($data2 as $k=>$v)
		{
			empty($str)? $str=$v['score_list'] : $str.=','.$v['score_list'];
		}
		$arr2=explode(',',$str);
		//这是当前的
		$data3=Yii::app()->session['operatelist2'];
		$arr=explode(",",$data3);
		//这是session当中的
		$data=$session['operatelist'];
		$arr3=explode(",",$data);
		$arr_not_in=array_merge(array_diff($arr2,$arr),$arr3);
		
		$model=new Score;
		$criteria=new CDbCriteria(array(
			'order'=>"t.$sort $order",
			//'select'=>array('id','title'),//'id,title',
			//'select'=>'knowledgepoint.title,t.id,t.title',
			'condition'=>$condition,
			'limit'=>$rows,
			'offset'=>($page-1)*$rows,
			'with'=>array('student_fullname'),
		));
		$criteria->addNotInCondition('t.id',$arr_not_in);
		$count = $model->count($criteria);
		//exit;
		$data3=$model->findAll($criteria);
		$json = new CArJSON();
		// Define which relations do you want to load
		$relations = array('student_fullname');
		// Define which attributes, foreach relations do you want to load
		// root denote attributes for the main model
		$attributes = array(
			'root' => array('id','singlechoiceScore','multichoiceScore','judgeScore','operateScore','totalScore','reexam'),//表示主表中的字段
			'student_fullname' => array( 'fullname' ),//表示从表中的字段
			//'votes' => null, // This will load all attributes
		);
		$data=$json->toJSON($data3, $relations, $attributes);
		//print_r(CJSON::decode($data));
		$newarr=array();
		foreach(CJSON::decode($data) as $key=>$value)
		{
			$newarr[]=array(
				'id'=>$value['attributes']['id'],
				'operateScore'=>$value['attributes']['operateScore'],
				'fullname'=>$value['relations']['student_fullname']['fullname'],
			);
			//echo $key;echo $value['attributes']['id'];
			//$newarr[$i]['title']=$value['attributes']['title'];
			//$newarr[$i]['singlechoiceScore']=$value['attributes']['singlechoiceScore'];
			//$newarr[$i]['multichoiceScore']=$value['attributes']['multichoiceScore'];
			//$newarr[$i]['judgeScore']=$value['attributes']['judgeScore'];
			//$newarr[$i]['totalScore']=$value['attributes']['totalScore'];
			//$newarr[$i]['reexam']=($value['attributes']['reexam'])?'Yes':'No';
		}

			$data2=CJSON::encode($newarr);
			$data='{'.'"total":'.$count.','.'"rows":'.$data2.'}';
			echo $data;	
	}
	

	//>---------------选择试题
	public function actionSelectall(){
		$session=new CHttpSession;
		$session->open();
		$arr=(array)(CJSON::decode(Yii::app()->request->getPost('qq')));
		//print_r($arr);exit;

		if(!isset($session['operatelist'])){$str=implode(',',$arr);}else{$str=$session['operatelist'].','.implode(',',$arr);}
		$session['operatelist']=$str;
			echo "选择成功！请继续选择！";
	}
	//>--------------------重新选择
	public function actionResetall(){
		if(isset(Yii::app()->session['operatelist']))
		{
			unset(Yii::app()->session['operatelist']);
			echo "已清空，请重新选择！";
			Yii::app()->end();
		}else
		{
			echo "本来就是空的！";
			Yii::app()->end();
		}
	}
	//>---------------------单行删除
	public function actionDeleterow(){
		$id=Yii::app()->request->getPost('id');
		if($this->loadModel($id)->delete()){
			echo "yes";
		}
	}
	//>---------------多行删除
	public function actionDeleteall(){
		$arr=(array)(CJSON::decode(Yii::app()->request->getPost('qq')));
		foreach($arr as $value){
			$newarr[]=(array)$value;
		}
		$str='';
		//print_r($newarr);
		foreach($newarr as $value){
			$fullname=trim($value['fullname']);
			$id=trim($value['id']);
				if($this->loadModel($id)->delete()){
					$str.='删除《'.$fullname.'》成功！<br/>';
				}else
				{
					$str.='删除《'.$fullname.'》失败！<br/>';
				}            
		}
		echo $str;
	}
	public function actionAaaa()
	{
		$arr=array('a','b','c');
		$arr2=array();
		$arr3=array_diff($arr,$arr2);
		print_r($arr3);
	}
}
