<?php
namespace app\modules\glspecial\controllers;

use Yii;
use yii\web\Controller;
use app\models\Config;
use app\models\Specialty;
use app\components\WarningHelper;
use app\components\AccessControl;

class DefaultController extends Controller
{
	
	private $userobj; //用户登录信息
	private $request; //Yii::$app->request对象
	
    public function init(){
		$this->userobj = AccessControl::isLogin();
		$this->request = Yii::$app->request;
	}
	
	public function beforeAction($action) {
		$this->view->params["navicode"] = "glspecial";
		$this->view->params["navicode_two"] = "glspecial_manage";
		$this->view->params["meta_title"] = "专业管理";
		return true;
	}
		
	//行政结构树
	public function actionIndex(){
		$chapters = Specialty::find()->where("parentid=0")->orderby("spelling asc")->all();
		foreach ($chapters as $onechapter) {
			$onechapter->children = Specialty::find()->where("parentid=". $onechapter->id)->orderby("spelling asc")->all();
			foreach ($onechapter->children as $onesection) {
				$onesection->children = Specialty::find()->where("parentid=". $onesection->id)->orderby("spelling asc")->all();
			}
		}
		$treepath = $this->request->post("treepath");
		$treepath = htmlspecialchars(strip_tags(trim($treepath)));
		return $this->render("index", ["chapters"=>$chapters, "treepath"=>$treepath]);
	}

	//上下移动院系专业
	public function actionMoveupdown(){
		$treeid = $this->request->post("treeid");
		$treeid = htmlspecialchars(strip_tags(trim($treeid)));
		$direction = $this->request->post("direction");
		$direction = htmlspecialchars(strip_tags(trim($direction)));
		if(empty($treeid) || is_numeric($treeid)==false){
			echo json_encode(["code"=>"failed","msg"=>"参数错误"]);
			die();
		}
		$tree = Specialty::find()->where("id=". $treeid)->one();
		if(empty($tree)){
			echo json_encode(["code"=>"failed","msg"=>"节点不存在"]);
			die();
		}
		$brothers = Specialty::find()->where("parentid=". $tree->parentid ." and nodetype=". $tree->nodetype)->orderby("sortid asc,id asc")->all();
		foreach($brothers as $onekey => $onebrother){
			$onebrother->sortid = ($onekey+1)*10;
			if($direction=="up"){ //上移
				if($onebrother->id==$tree->id){
					if($onebrother->sortid<15){
						$onebrother->sortid = 1;
					}else{
						$onebrother->sortid -= 15;
					}
				}
			}else{ //下移
				if($onebrother->id==$tree->id){
					$onebrother->sortid += 15;
				}
			}
			$onebrother->save();
		}
		echo json_encode(["code"=>"success","msg"=>"成功"]);
	}
		
}
?>