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

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

class QutypechildController 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(){
		$sectionid = $this->request->get("id");
		$sectionid = htmlspecialchars(strip_tags(trim($sectionid)));
		$parentid = $this->request->get("parentid");
		$parentid = htmlspecialchars(strip_tags(trim($parentid)));
		if(empty($parentid) || is_numeric($parentid)==false){
			echo "参数错误"; die();
		}
		if(empty($sectionid) || is_numeric($sectionid)==false){
			$section = new Questi_type();
			$section->parentid = $parentid;
			$chapter = Questi_type::find()->where("id=". $parentid)->one();
		}else{
			$section = Questi_type::find()->where("id=". $sectionid)->one();
			if(empty($section)){
				echo "子题型不存在"; die();
			}
		}
		return $this->renderPartial("index", ["section"=>$section]);
	}
	
	//编辑子题型，保存
	public function actionBasicok(){
		$sectionid = $this->request->post("sectionid");
		$sectionid = htmlspecialchars(strip_tags(trim($sectionid)));
		$title = $this->request->post("title");
		$title = htmlspecialchars(strip_tags(trim($title)));
		$parentid = $this->request->post("parentid");
		$parentid = htmlspecialchars(strip_tags(trim($parentid)));
		if(empty($parentid) || is_numeric($parentid)==false){
			echo json_encode(["code"=>"failed","msg"=>"参数错误"]);
			die();
		}
		$chapter = Questi_type::find()->where("id=". $parentid)->one();
		if(empty($chapter)){
			echo json_encode(["code"=>"failed","msg"=>"题型不存在"]);
			die();
		}
		if(empty($sectionid) || is_numeric($sectionid)==false){
			$section = new Questi_type();
		    $section->parentid = $chapter->id;
			$isnewnode = 1;
			$sameone = Questi_type::find()->where("parentid=". $chapter->id ." and name='". $title ."'")->one();
		}else{
			$section = Questi_type::find()->where("id=". $sectionid)->one();
			$isnewnode = 0;
			$sameone = Questi_type::find()->where("parentid=". $chapter->id ." and name='". $title ."' and id<>". $sectionid)->one();
		}
		if(!empty($sameone)){
			echo json_encode(["code"=>"failed","msg"=>"名称已被占用"]);
			die();
		}
		$section->name = $title;
		$section->save();
		if($isnewnode==1){
			$section->sortid = $section->id*10;
			$section->save();
		}
		echo json_encode(["code"=>"success","msg"=>"成功"]);
	}
	
}
?>