<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace qcbase\models;

use Yii;
use yii\base\Model;
use common\models\User;

/**
 * 登录表单
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class LoginForm extends Model
{

    public $username;
    public $password;
    public $verifyCode;
    public $rememberMe = false;
    private $_user = false;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password', 'verifyCode'], 'required', 'message' => '请输入{attribute}'],
            ['password', 'validatePassword'],
            ['verifyCode', 'captcha' ,'captchaAction' =>'public/captcha'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'username' => '用户名',
            'password' => '密码',
            'verifyCode' => '验证码',
        ];
    }

    /**
     * 验证密码
     *
     * @param string $attribute 被验证的属性
     * @param array $params 自定义参数
     */
    public function validatePassword($attribute, $params)
    {
        if(!$this->hasErrors()){
            $user = $this->getUser();
            if(!$user || !$user->validatePassword($this->password)){
                $this->addError($attribute, '用户名或者密码错误');
            }
        }
    }

    /**
     * 登录用户
     *
     * @return boolean 用户是否登录成功
     */
    public function login()
    {
        if($this->validate()){
            Yii::$app->user->on('afterLogin', ['qcbase\models\Menu', 'updateMenuCache']); //获取用户菜单
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * 获取用户
     *
     * @return User|null
     */
    public function getUser()
    {
        if($this->_user === false){
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }

}
