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

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

class ChapterController 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) {
		return true;
	}
		
	//编辑院
	public function actionIndex(){
		$chapterid = $this->request->get("id");
		$chapterid = htmlspecialchars(strip_tags(trim($chapterid)));
		if(empty($chapterid) || is_numeric($chapterid)==false){
			$chapter = new Specialty();
			$treepath = "";
		}else{
			$chapter = Specialty::find()->where("id=". $chapterid)->one();
			if(empty($chapter)){
				echo "院不存在"; die();
			}
			$treepath = $chapter->nodepath;
		}
		return $this->renderPartial("index", ["chapter"=>$chapter, "treepath"=>$treepath]);
	}
	
	//编辑院，保存
	public function actionBasicok(){
		$chapterid = $this->request->post("chapterid");
		$chapterid = htmlspecialchars(strip_tags(trim($chapterid)));
		$title = $this->request->post("title");
		$title = htmlspecialchars(strip_tags(trim($title)));
		if(empty($chapterid) || is_numeric($chapterid)==false){
			$chapter = new Specialty();
		    $chapter->parentid = 0;
		    $chapter->nodetype = 1;
			$chapter->cometime = date("Y-m-d H:i:s");
			$isnewnode = 1;
			$sameone = Specialty::find()->where("name='". $title ."'")->one();
		}else{
			$chapter = Specialty::find()->where("id=". $chapterid)->one();
			$isnewnode = 0;
			$sameone = Specialty::find()->where("name='". $title ."' and id<>". $chapterid)->one();
		}
		if(!empty($sameone)){
			echo json_encode(["code"=>"failed","msg"=>"名称已被占用"]);
			die();
		}
		$pinyin = new PinyinHelper();
		$chapter->name = $title;
		$chapter->spelling = $pinyin->getAllPY($chapter->name);
		if(stripos($chapter->name,"会计")!==false){
			$chapter->spelling = str_ireplace("huiji", "kuaiji", $chapter->spelling);
		}
		$chapter->firstletter = substr($chapter->spelling,0,1);
		$chapter->firstletter = strtoupper($chapter->firstletter);
		$chapter->save();
		if($isnewnode==1){
			$chapter->nodepath = ",". $chapter->id .",";
			$chapter->sortid = $chapter->id*10;
			$chapter->save();
		}
		echo json_encode(["code"=>"success","msg"=>"成功"]);
	}
	
	//删除院
	public function actionDelete(){
		$chapterid = $this->request->post("chapterid");
		$chapterid = htmlspecialchars(strip_tags(trim($chapterid)));
		if(empty($chapterid) || is_numeric($chapterid)==false){
			echo json_encode(["code"=>"failed","msg"=>"参数错误"]);
			die();
		}
		Specialty_leader::deleteAll("specialid=". $chapterid);
		Specialty::deleteAll("find_in_set('". $chapterid ."',nodepath) or id=". $chapterid);
		echo json_encode(["code"=>"success","msg"=>"成功"]);
	}
	
}
?>