<?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='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
		);
	}
	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'),
				'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 Student;

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

		if(isset($_POST['Student']))
		{
			$model->attributes=$_POST['Student'];
			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)
	{
		$model2=$this->loadModel($id);
		$model=new StudentForm;
		$model->username=$model2->username;
		$model->fullname=$model2->fullname;
		$model->sex=$model2->sex;
		$model->classroom_id=$model2->classroom_id;
		$model->grade_id=$model2->grade_id;
		$model->remark=$model2->remark;
		$model->photo=$model2->photo;	
		$this->layout='common1';
		Yii::app()->clientScript->registerCoreScript('jquery');
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['StudentForm']))
		{
			$model2->attributes=$_POST['StudentForm'];
			$model->attributes=$_POST['StudentForm'];
			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);//上传操作
					$model2->photo="/myfiles/students_photo/".$filename.".$fileExtensionName"; 	
					//$model2->photo=$model->photo; 	
				}else
				{
					unset($model2->photo);
				}
				
				
				
				if($model2->save(false))
					Yii::app()->user->setFlash('updated','更新成功！');
					$this->refresh();
			}
			
		}

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

	/**
	 * 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 actionList($grade_id,$classroom_id){
		$this->render('admin',array(
			'grade_id'=>$grade_id,
			'classroom_id'=>$classroom_id,
		));
	}
	//取所有数据
	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');//查询标题
		$condition_1="classroom_id='$classroom_id'";
		$condition_2="classroom_id='$classroom_id' and fullname like '%$fullname%'";
		$condition=(isset($fullname))?$condition_2:$condition_1;
		
		$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,
			//'with'=>'singletest',
		));

		$count = $model->count($criteria);
		$data3=$model->findAll($criteria);
		foreach($data3 as $k=>$v){
			($v['sex'])?$data3[$k]['sex']='女':$data3[$k]['sex']='男';
			//(empty($v['photo']))?$data3[$k]['image']='无':$data3[$k]['image']='有';
			//$data3[$k]['created']='<img src="'.$data3[$k]['photo'].'"'.' style="width:100px" />';
			//if($v['examState']){$data3[$k]['examState']='是';}else {$data3[$k]['examState']='否';}
		}
			$data2=CJSON::encode($data3);
			$data='{'.'"total":'.$count.','.'"rows":'.$data2.'}';
			echo $data;	
	}
	//>---------------------单行删除
	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 actionResetPwd()
	{
		$id=Yii::app()->request->getPost('id');
		$model=$this->loadModel($id);
		$data=$model->find(array(
			'condition'=>'id='.$id,
			'select'=>'salt',
		));
		$model->backend=1;

		$num="123456";
		$arr['Student']['password']=md5($data['salt'].$num);
		$model->attributes=$arr['Student'];
		if($model->save(false))
		{echo "yes";
		Yii::app()->end();
		}
	
	}
	public function actionImport($grade_id,$classroom_id)
	{	//echo Yii::app()->layoutPath;
		//echo getcwd();
		//如果是yii就用 Yii::app()->baseUrl;
		//如果使用了多套模版就是用
		//Yii::app()->theme->baseUrl;
		//echo dirname(__FILE__);
		//$_SERVER['DOCUMENT_ROOT']
		//exit;Yii::getPathOfAlias('webroot'); 网站根目录
		$model=new ImportForm;
		if(isset($_POST['ImportForm']))
		{
				$model->attributes=$_POST['ImportForm'];
				if($model->validate()){
					$csvfile=$model->csvfile=CUploadedFile::getInstance($model,'csvfile');
					if(isset($model->csvfile)){
						$filename=uniqid(); 
						$fileExtensionName=$csvfile->getExtensionName(); 				
						//$filename1=iconv("utf-8", "gb2312", $model->csvfile);
						//这里是处理中文的问题，非中文不需要   
						$uploadfile=Yii::app()->basePath."/../myfiles/import/".$filename.".$fileExtensionName";  
						$model->csvfile->saveAs($uploadfile,true);//上传操作
						$model->csvfile="/myfiles/import/".$filename.".$fileExtensionName";
						$tmp=$filename.".$fileExtensionName";
						$file = fopen(Yii::app()->request->hostInfo.$model->csvfile,"r");
						$path=getcwd()."\myfiles\import\\".$tmp;//echo $path;exit;
						//$file = fopen($path,"r");
						while(! feof($file))
						{
							$model2=new Student;
							//header("Content-type: text/html; charset=utf-8");
							$arr=fgetcsv($file);
								if(iconv('gb2312', 'utf-8', $arr[3])=='男')
									$arr[3]=0;
								else
									$arr[3]=1;
								$arr2['username']=iconv('gb2312', 'utf-8', $arr[0]);
								$arr2['password']=iconv('gb2312', 'utf-8', $arr[1]);
								//$arr2['fullname']=$arr[2];
								$arr2['fullname']=iconv('gb2312', 'utf-8', $arr[2]);
								$arr2['sex']=iconv('gb2312', 'utf-8', $arr[3]);
								$arr2['classroom_id']=$classroom_id;
								$arr2['grade_id']=$classroom_id;
								$model2->attributes=$arr2;
								$model2->save(false);							
						}
						fclose($file);
						unlink($path);
						Yii::app()->user->setFlash('imported','导入成功！');
						$this->refresh();
					}
				}
		}
		$this->render('import',array(
			'model'=>$model,
		));
	}
}
