<?php

namespace common\modules\user\models;

use Yii;
use yii\base\Model;

/**
 * Login form.
 */
class QrcodeLoginForm extends Model
{
    public $access_token;
    public $qrcode_hash;
    public $rememberMe = false; // 自动登录
    private $_user;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['access_token', 'qrcode_hash'], 'required'],
            ['rememberMe', 'boolean'],
            ['qrcode_hash', 'validateQrcodeHash'],
        ];
    }
    public function attributeLabels()
    {
        return [
            'access_token' => '访问令牌',
            'qrcode_hash' => '二维码哈希',
            'rememberMe' => '记住我',
        ];
    }
    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array  $params    the additional name-value pairs given in the rule
     */
    public function validateQrcodeHash($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validateQrcodeHash($this->qrcode_hash)) {
                $this->addError($attribute, '等待微信扫码登录');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * 管理员登录
     * @return bool
     * @author nodelog
     */
    public function loginAdmin()
    {
        if ($this->validate()) {
            if ($this->getUser()->getIsAdmin()) {
                return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
            } else {
                $this->addError('username', '无权登录');
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]].
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findIdentityByAccessToken($this->access_token);
        }

        return $this->_user;
    }
}
