<?php

namespace App\Models;

//use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\ProjectRole as ProjectRoleModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
//use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Cache;
use Laravel\Sanctum\HasApiTokens;

class User extends Base
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $table = 'gl_project_user';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
    ];

    /***
     * @name :登录
     * @return void
     * @author :liyuhang
     * @method
     */
    public function login($param){
        if(!isset($param['login_method'])){
            //密码加密
            $param['password'] = base64_encode(md5($param['password']));
            $info = $this->read(['mobile'=>$param['mobile'],'password'=>$param['password'],'status'=>0], ['*']);
        }else{
            //TODO::验证验证码是否正确
            $info = $this->read(['mobile'=>$param['mobile']],['*']);
        }
        if(empty($info)){
            return false;
        }
        //当前用户角色是否被禁用
        $projectRoleModel = new ProjectRoleModel();
        $role_info = $projectRoleModel->read(['id'=>$info['role_id'],'status'=>0]);
        if(empty($role_info)){
            return false;
        }
        //验证码登录
        if(isset($info['token']) && !empty($info['token'])){
            //清除上一次用户缓存
            Cache::pull($info['token']);
        }
        //生成新token
        $token = md5(uniqid().$info['id']);
        //存储缓存
        Cache::add($token,$info);
        $rs = $this->edit(['token'=>$token],['id'=>$info['id']]);
        if($rs === false){
            return false;
        }
        return $info;
    }
}