<?php

class CategoryController 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='common';
	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 Category;
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

			if(Yii::app()->request->getPost('root')=='no'){
				$parent_id=Yii::app()->request->getPost('id');
				$Category['title']='未命名';
				$model->attributes=$Category;
				$parent=$this->loadModel($parent_id);
				$model->appendTo($parent,false);
				echo "yes";Yii::app()->end();
			}
			if(Yii::app()->request->getPost('root')=='yes'){
				$Category['title']='未命名';
				$model->attributes=$Category;
				$model->saveNode(false);
				echo "yes";Yii::app()->end();
			}
			if(Yii::app()->request->getPost('root')=='first'){
				$Category['title']=Yii::app()->request->getPost('title');
				$model->attributes=$Category;
				$model->saveNode(false);
				echo "yes";Yii::app()->end();
			}
				//$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,$title)
	{
		$model=$this->loadModel($id);
		$Category['title']=$title;
		$model->attributes=$Category;
		$model->saveNode(false);
		echo "yes";Yii::app()->end();
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Category']))
		{
			$model->attributes=$_POST['Category'];
			if($model->save())
				$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)
	{
		$model=$this->loadModel($id);
		if($model->deleteNode(false)){
				echo "yes";Yii::app()->end();
			}
		/*
		$isroot=$model->isRoot();
		$roots=Category::model()->roots()->findAll();
		if($isroot && $roots==1){
			if($model->delete()){
				echo "yes";Yii::app()->end();
			}			
		}else{
			if($model->deleteNode(false)){
				echo "yes";Yii::app()->end();
			}
		}
		*/
		// 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()
	{
		//$new_root=new Category;
		//$new_root->attributes=array('title'=>'第一章');
		//$new_root->saveNode(false);
		$roots=Category::model()->roots()->findAll();
		$count=count($roots);
		$this->render('index',array(
			'count'=>$count,
		));
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Category('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Category']))
			$model->attributes=$_GET['Category'];

		$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=Category::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']==='category-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionFetchtree()
    {
		 $categories=Category::model()->findAll(array('order'=>'root,lft'));
		 $level=0;
		 //$arr=[];
	   foreach($categories as $n=>$category)
	    {
		    if($category->level==$level)
				echo CHtml::closeTag('li')."\n";
		    else if($category->level>$level)
				{
					echo CHtml::openTag('ul')."\n";
				}			   
				else
				{
				    echo CHtml::closeTag('li')."\n";

				    for($i=$level-$category->level;$i;$i--)
					{
					   echo CHtml::closeTag('ul')."\n";
					   echo CHtml::closeTag('li')."\n";
					}
				}
			echo CHtml::openTag('li');
		    $arr[$category->id]=$category->title;
			echo CHtml::encode($category->title);
		    $level=$category->level;
	    }

	   for($i=$level;$i;$i--)
	   {
		   echo CHtml::closeTag('li')."\n";
		   echo CHtml::closeTag('ul')."\n";
	   }
    }
	public function actionTree()
    {$this->render('tree');exit;
		 $categories=Category::model()->findAll(array('order'=>'root,lft'));
		 $level=0;//$tree = create_tree($results);
		 
		 $data=CJSON::decode(CJSON::encode($categories));
		 //print_r($data);
		 //echo CJSON::encode($categories);
		 header('Content-Type: text/html; charset=utf-8');
		echo "<pre>";
		 print_r($this->create_tree($data));
    }
	public function actionMytree(){
		header('Content-Type: text/html; charset=utf-8');
		//$data=Category::model()->findAll(array('order'=>'lft'));
		//$data=Category::model()->findAll(array('condition'=>'root_id=?','order'=>'lft'),array($root_id));
		$roots=Category::model()->roots()->findAll();//获取所有根结点
		$data=array();
		foreach($roots as $k=>$v){
			$root=Category::model()->findByPk($v['id']);
			$descendants=$root->descendants()->findAll(array('order'=>'lft'));
			$data2=CJSON::decode(CJSON::encode($descendants));
			$data3=CJSON::decode(CJSON::encode($root));
			array_unshift($data2,$data3);
			$data[]=$this->create_tree($data2);
		}
		echo str_replace("title","text",CJSON::encode($data));
		//echo "<pre>";
		//print_r($data);
		exit;
		$category=Category::model()->findByPk(1);
		$descendants=$category->descendants()->findAll(array('order'=>'lft'));
		$children=$category->children()->findAll();
		
		$categories=Category::model()->findAll(array('order'=>'root,lft'));
		$data=CJSON::decode(CJSON::encode($categories));
		//print_r(CJSON::decode(CJSON::encode($categories)));
		echo "[".str_replace("title","text",CJSON::encode($this->create_tree($data)))."]";
		//print_r(CJSON::decode(CJSON::encode($children)));
		$data=array(
			"id"=>1,
			"text"=>'a',
			"children"=>array(
				array(
					"id"=>2,
					"text"=>'b',
					"children"=>array(
						array("id"=>5,"text"=>'e'),
						array("id"=>6,"text"=>'f'),
						array("id"=>7,"text"=>'g'),
					)			
				),
				array(
					"id"=>3,
					"text"=>'c',
					"children"=>array(
						array("id"=>8,"text"=>'h'),
						array("id"=>9,"text"=>'i'),
						array("id"=>10,"text"=>'j'),
					)			
				),
				array(
					"id"=>4,
					"text"=>'d',
					"children"=>array(
						array("id"=>11,"text"=>'k'),
						array("id"=>12,"text"=>'l'),
						array("id"=>13,"text"=>'m'),
					)			
				)
			)
		);
		//echo "<pre>";
		//echo "[".CJSON::encode($data)."]"."<br/>";
	}
function create_tree($results) {
	$return = $results[0];$rgt=-1;
	array_shift($results);

	if ($return['lft'] + 1 == $return['rgt'])
		$return['leaf'] = true;
	else {
		foreach ($results as $key => $result) {
			if ($result['lft'] > $return['rgt']) //not a child
				break;
			if ($rgt > $result['lft']) //not a top-level child
				continue;
			$return['children'][] = $this->create_tree(array_values($results));
			foreach ($results as $child_key => $child) {
				if ($child['rgt'] < $result['rgt'])
					unset($results[$child_key]);
			}
			$rgt = $result['rgt'];
			unset($results[$key]);
		}
	}

	unset($return['lft'],$return['rgt'],$return['root'],$return['level']);
	return $return;

}
	/**/
}
?>
<?php 



?>