<?php
/**
 * Created by PhpStorm.
 * User: chenkuan
 * Date: 2017/11/13
 * Time: 下午3:01
 */

namespace backend\models\forms;


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

class RePwdForm extends Model
{
    public $username;
    public $type;
    public $code;
    public $password;
    public $rePassword;

    public function rules()
    {
        return [
            [['username', 'password', 'rePassword', 'code'], 'required'],
            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'email'],
            [['password', 'rePassword'], 'string', 'min' => 6, 'max' => 16, 'message' => '{attribute}是6-16位数字或字母'],
            ['rePassword', 'compare', 'compareAttribute' => 'password', 'message' => '两次密码不一致'],
            [['type', 'code'], 'integer'],
            [['type'], 'default', 'value' => 1],
        ];
    }

    public function modifyPwd1()
    {
        if ($this->validate()) {
            $data = [];
            $data['username'] = $this->username;
            $data['code'] = $this->code;
            $data['password'] = $this->password;
            $data['rePassword'] = $this->rePassword;
            $data['type'] = $this->type;

            $api = new LoginApi();
            $result = $api->modifyPwd1($data);
            if ($result['code'] == 1) {
                return true;
            } else {
                if (is_array($result['message'])) {
                    $this->addErrors($result['message']);
                } else {
                    $this->addError('username', $result['message']);
                }
            }
        }
        return !$this->hasErrors();
    }
}
