<?php
class jsTreeAction extends action
{
	private $tree = null;
	private $level = -1;
    function __construct(){
        parent::__construct();
		$e = require(mvc::$cfg['ROOT'].'mod/element/'.$_REQUEST['element'].'.php');
		$this->level = $_REQUEST['level'];
		$this->noid = $_REQUEST['noid'];
		$this->parentId = $_REQUEST['parentId'];
		$this->mod = new mod($e);
		$this->tree = new LibTree($this->mod->e['title'],$this->mod->e['table'],$this->mod->e['tree']);
    }

    function __destruct(){
    }
	/**
	 * Method 取=父ID的树节点数据
	 */
    function getNode($id){
    	$root = 0;
    	if($id=='#' && $this->parentId>0) {
    		$id = $this->parentId;
    		$root = $this->parentId;
    	}
		$data = $this->tree->getDataByParent($id,$this->level,$this->noid,$root);
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}

	/**
	 * Method 取所有树节点数据
	 */
    function getAllNode(){
		$data = $this->tree->getDataAll($this->level);
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}
	/**
	 * Method 搜索节点
	 */
    function searchNode($str){
		$data = $this->tree->searchNode($str,$this->parentId);
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}
	/**
	 * Method 创建节点
	 */
    function createNode($parentId,$text='New node'){
		$parentLevel = $this->tree->getLevelById($parentId);
		if($parentLevel<1 || $parentLevel>=2) {
			$this->exitJson(1001,'限制层级为两级');
		}else{
			if($id = $this->tree->createNode($parentId,$text))
				$this->exitJson(0,$id);
			else
				$this->exitJson(2000);
		}
	}
	/**
	 * Method 修改节点名称
	 */
    function renameNode($id,$text){
		$done = $this->tree->renameNode($id,$text);
		if($done)
			$this->exitJson(0);
		else
			$this->exitJson(2000);
	}
	/**
	 * Method 修改节点名称
	 */
    function deleteNode($id){
		$done = $this->tree->deleteNode($id,function(){
			return true;
		});
		if($done)
			$this->exitJson(0);
		else
			$this->exitJson(2000);
	}
	/**
	 * Method 移动节点
	 */
    function moveNode($id,$parent,$old_parent,$position,$old_position){
		$parentLevel = $this->tree->getLevelById($parent);
		if(empty($parentLevel)) $parentLevel = 0;
		if($parentLevel<0 || $parentLevel>=2) {
			$this->exitJson(1001,'限制层级为两级'.$parentLevel);
		}else{
			$done = $this->tree->moveNode($id,$parent,$old_parent,$position,$old_position);
			if($done)
				$this->exitJson(0);
			else
				$this->exitJson(2000);
		}
	}
}