<?php
namespace backend\models\forms;

use backend\helpers\RandomHelper;
use common\helpers\MtKit;
use common\helpers\Utils;
use yii\base\Model;

class OpenDemoForm extends Model
{
    public $username;
    public $email;
    public $phone;

    private $_login;
    private $_password;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'required'],
            ['email', 'required'],
            ['email', 'email'],
            ['phone', 'required'],
            ['phone', 'checkPhone'],
        ];
    }

    public function checkPhone($attribute, $params = [])
    {
        if (!$this->hasErrors()) {
            if (Utils::checkPhoneNumber($this->phone) == false) {
                $this->addError($attribute, '手机号码格式错误');
            }
        }
    }

    /**
     * @return bool
     */
    public function openDemo()
    {
        if ($this->validate()) {
            $this->_password = RandomHelper::getRandomStringForMt4();
            $passwordInvestor = RandomHelper::getRandomStringForMt4();
            $passwordPhone = RandomHelper::getRandomStringForMt4();
            $login = MtKit::openUserDemo(null, $this->_password, $passwordInvestor, $passwordPhone, $this->username, null, $this->email, $this->phone);
            if ($login) {
                $this->_login = $login;
            } else {
                $this->addError('username', '模拟账户申请失败');
            }
        }
        return !$this->hasErrors();
    }

    /**
     * @return int
     */
    public function getLogin()
    {
        return $this->_login;
    }

    /**
     * @return string
     */
    public function getPassword()
    {
        return $this->_password;
    }
}