<?php
/**
 * Created by PhpStorm.
 * Author: NODELOG
 * DateTime: 2017/3/8 17:46
 * Description:
 */

namespace api\modules\v1\models;

use api\common\models\User;
use common\helpers\Regexp;
use Yii;
use yii\base\Model;


class UserEditForm extends Model
{
    //user
    public $nickname;
    public $tel;

    //profile
    public $gender;
    public $avatar;
    public $signature;

    private $_user;


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['nickname', 'avatar', 'gender'], 'required'],
            [['tel'], 'match', 'pattern' => Regexp::$mobile],
            [['tel'], 'validateTel'],//
            [['signature'], 'safe'],
        ];
    }

    public function validateTel($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $exists = User::find()->where(['tel' => $this->tel])->andWhere(['not', ['id' => Yii::$app->user->id]])->exists();
            if ($exists) {
                $this->addError($attribute, '手机号已被绑定');
            }
        }
    }

    public function attributeLabels()
    {
        return [
            'nickname' => '昵称',
            'gender' => '性别',
            'avatar' => '头像',
            'signature' => '签名',
            'tel' => '手机号',
        ];
    }


    /**
     * @return bool
     * @author nodelog
     */
    public function edit()
    {
        if ($this->validate()) {
            $user = Yii::$app->user->identity;
            $user->nickname = $this->nickname;
            $user->tel = $this->tel;
            $user->save();

            $user->profile->updateAttributes([
                'avatar' => $this->avatar,
                'gender' => $this->gender,
                'signature' => $this->signature,
            ]);

            return true;
        } else {
            return false;
        }
    }

}
