<?php
namespace backend\models\forms;

use backend\models\LoginApi;
use backend\models\MemberIdentity;
use Yii;
use yii\base\Model;

class LoginForm extends Model
{
    public $username;
    public $password;
    public $type;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            [['type'], 'integer'],
            [['type'], 'default', 'value' => 1],
        ];
    }

    /**
     * @return bool
     */
    public function login()
    {
        if ($this->validate()) {
            $data = [];
            $data['username'] = $this->username;
            $data['password'] = $this->password;
            $data['type'] = $this->type;
            $api = new LoginApi();
            $result = $api->loginPost($data);
            if ($result['code'] == 1) {
                $identity = MemberIdentity::findIdentity($result['data']['id']);
                if ($this->type == MemberIdentity::MEMBER_TYPE_USER) {
                    return Yii::$app->getUser()->login($identity);
                } elseif ($this->type == MemberIdentity::MEMBER_TYPE_IB) {
                    return Yii::$app->get('userIb')->login($identity);
                } else {
                    return false;
                }
            } else {
                if (is_array($result['message'])) {
                    $this->addErrors($result['message']);
                } else {
                    $this->addError('username', $result['message']);
                }
            }
        }
        return !$this->hasErrors();
    }
}