<?php
/**
 *------------------------------------------------------
 * AdminUserModel.php
 *------------------------------------------------------
 *
 * @author    m@9026.com
 * @date      2017/03/21 10:15
 * @version   V1.0
 *
 */

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class AdminUserModel extends Authenticatable
{
    /**
     * 数据表名
     */
    protected $table = "admin_users";

    /**
     * 主键
     */
    protected $primaryKey = "id";

    protected $guarded = [];

    public function getValidator(Request $request, $type)
    {
        if ($type == 'store') {
            $validator = Validator::make($request->input('data'), [
                'name' => 'required|unique:admin_users'
            ], [
                'name.required' => '用户名必填',
                'name.unique' => '用户名已存在'
            ]);
        } else if ($type == 'change-password') {
            $validator = Validator::make($request->input('data'), [
                'old_password' => 'required',
                'password' => 'required|min:6|confirmed'
            ], [
                'old_password.required' => '请填写原来密码',
                'password.required' => '密码必填，且不能少于6位',
                'password.min' => '密码必填，且不能少于6位',
                'password.confirmed' => '两次填写的密码不一致'
            ]);
        } else {
            $validator = Validator::make($request->input('data'), [
                'name' => 'required'
            ], [
                'name.required' => '账号必填'
            ]);
            $data = $request->input('data');
            $check = $this->where([
                ['id', '!=', $request->input('id')],
                ['name', '=', $data['name']]
            ])->first();
            $validator->after(function ($validator) use($check) {
                if ($check) {
                    $validator->errors()->add('name', '用户名已存在');
                }
            });
        }
        return $validator;
    }

    public function adminRole()
    {
        return $this->belongsTo('App\Models\AdminRoleModel', 'admin_role_id');
    }

    public function updateToken()
    {
        $token = Str::random(60);
        $token = hash('sha256', $token);
        $this->update(['token' => $token]);
    }
}