<?php
namespace backend\models\forms;

use backend\models\OpenApi;
use yii\base\Model;

class OpenDemoForm extends Model
{
    public $name;
    public $email;
    public $mobile;
    public $level;
    public $agree;

    private $_login;
    private $_password;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['name', 'required', 'message' => '请填写姓名'],
            ['email', 'required', 'message' => '请填写电子邮箱'],
            ['email', 'email'],
            ['mobile', 'required', 'message' => '请填写手机号码'],
            ['mobile', 'match', 'pattern' => '/^1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\d{8}$/'],
            ['level', 'required'],
            ['level', 'in', 'range' => [100, 200]],
            ['agree', 'boolean', 'trueValue' => 'on'],
        ];
    }

    /**
     * @return bool
     */
    public function openDemo()
    {
        if ($this->validate()) {
            $api = new OpenApi();
            $data = [];
            $data['username'] = $this->name;
            $data['email'] = $this->email;
            $data['phone'] = $this->mobile;
            $result = $api->openDemo($data);
            if ($result['code'] == 1) {
                $this->_login = isset($result['data']['login']) ? $result['data']['login'] : 0;
                $this->_password = isset($result['data']['password']) ? $result['data']['password'] : '';
                return true;
            } else {
                if (is_array($result['message'])) {
                    $this->addErrors($result['message']);
                } else {
                    $this->addError('name', $result['message']);
                }
            }
        }
        return !$this->hasErrors();
    }

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

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