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

use Yii;
use yii\web\Controller;
use app\models\Config;
use app\models\User;
use app\models\Doexam;
use app\models\Resour_leader;
use app\models\Specialty_leader;
use app\components\AccessControl;
use app\components\AuthcodeHelper;

class ProfileController 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(){
		$user = User::find()->where("id=". $this->userobj->id)->one();
		return $this->render("index", ["user"=>$user]);
	}

	//编辑资料，保存
	public function actionBasicok(){
		$realname = $this->request->post("realname");
		$realname = htmlspecialchars(strip_tags(trim($realname)));
		$logo = $this->request->post("logo");
		$logo = htmlspecialchars(strip_tags(trim($logo)));
		$male = $this->request->post("male");
		$male = htmlspecialchars(strip_tags(trim($male)));
		$cellphone = $this->request->post("cellphone");
		$cellphone = htmlspecialchars(strip_tags(trim($cellphone)));
		$email = $this->request->post("email");
		$email = htmlspecialchars(strip_tags(trim($email)));

		if(empty($logo)){
			$logo = "";
		}
		if($male==1 || $male==2){
			//do nothing
		}else{
			$male = 0;
		}
		if(!empty($cellphone)){
			$json = UserHelper::sameCellphone($cellphone, $this->userobj->id);
			$result = json_decode($json);
			if($result->code!="success"){
				echo json_encode(["code"=>"failed", "msg"=>$result->msg]);
				die();
			}
		}
		if(!empty($email)){
			$json = UserHelper::sameEmailbox($email, $this->userobj->id);
			$result = json_decode($json);
			if($result->code!="success"){
				echo json_encode(["code"=>"failed", "msg"=>$result->msg]);
				die();
			}
		}
		$user = User::find()->where("id=". $this->userobj->id)->one();
		if(empty($user)){
			echo json_encode(["code"=>"failed", "msg"=>"用户不存在"]);
			die();
		}
		$user->realname = $realname;
		$user->male = $male;
		$user->logo = $logo;
		$user->cellphone = $cellphone;
		$user->email = $email;
		$user->save();
		Doexam::updateAll(["realname"=>$user->realname],"userid=". $user->id);
		Resour_leader::updateAll(["realname"=>$user->realname,"logo"=>$user->logo],"userid=". $user->id);
		Specialty_leader::updateAll(["realname"=>$user->realname,"logo"=>$user->logo],"userid=". $user->id);
		AccessControl::RefreshCookie($user->id);
		echo json_encode(["code"=>"success","msg"=>"成功"]);
	}
	
}
?>