<?php

namespace App;

use App\Traits\ModelLogChanging;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;
use App\Traits\ModelTimeFormat;

class User extends Authenticatable
{
    use ModelLogChanging;
    use ModelTimeFormat;
    use Notifiable;
    use SoftDeletes;

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
//    function hasRole($roles){
//        return !!$roles->intersect($this->roles()->get())->count();
//    }
    function isSuperAdmin(){
        $superAdmins=config("users.superAdmin");
        foreach ($superAdmins as $superAdmin){
            if($this['name']==$superAdmin){
                return true;
            }
        }
        return false;
    }

    /**
     * @param null $expireTime 手动设置过期时间则覆盖其中默认时间，分钟为单位
     * @return mixed|string
     */
    public function token($expireTime=null){
        if(!$expireTime){
            $expireTime=config('users.token_expire_minutes');
        }
        $token=Cache::get('tokenUser_'.$this['id']);
        if($token){
            Cache::put('tokenUser_'.$this['id'],$token,$expireTime);
            Cache::put('tokenStr_'.$token,$this['id'],$expireTime);
            return $token;
        }
        $token=md5(rand(1,intval(microtime(true)*10000)).'baoshi');
        Cache::put('tokenUser_'.$this['id'],$token,$expireTime);
        Cache::put('tokenStr_'.$token,$this['id'],$expireTime);
        return $token;
    }
    public function touchToken(){
        return $this->token();
    }
    function roles(){
        return $this->belongsToMany('App\Role','user_role','id_user','id_role');
    }
    function userDetail(){
        return $this->hasOne('App\UserDetail','user_id','id');
    }

    function logistics(){
        return $this->belongsToMany('App\Logistic','logistic_user','user_id','logistic_id');
    }
    function userWorkgroups(){
        return $this->belongsToMany('App\UserWorkgroup','user_workgroup_user','user_id','user_workgroup_id');
    }
    function suppliers(){
        return $this->belongsToMany('App\Supplier','supplier_user','user_id','supplier_id');
    }

    function authorities(){
        $authorities = new Collection([]);
        $user=User::query()->where('id',$this['id'])->with('roles.authorities')->first();
        $user->roles->each(function ($role)use(&$authorities){
            if($role->authorities){
                if(!$authorities){
                    $authorities=$role->authorities;
                }else{
                    $authorities=$authorities->merge($role->authorities);
                }
            }
        });
        return $authorities;
    }
    function getPermittingOwnerIdsAttribute(){
        $ownerIds=[];
        if($this->isSuperAdmin()||Gate::allows('货主-可见全部')){
            $owners=Owner::query()->whereNull('deleted_at')->get();
            $owners->each(function(Owner $owner)use(&$ownerIds){
                array_push($ownerIds,$owner['id']);
            });
            return $ownerIds;
        }
        $this->authorities()->each(function(Authority $authority)use(&$ownerIds){
            $ownerId=$authority->getOwnerIdAttribute();
            if($ownerId){array_push($ownerIds,$ownerId);}
        });
        return array_unique($ownerIds);
    }
    function getPermittingWorkgroupIds($allowAll=false){
        $workgroupIds=[];
        if ($this->isSuperAdmin()||$allowAll){
            $workgroups=UserWorkgroup::all();
            $workgroups->each(function (UserWorkgroup $workgroup)use(&$workgroupIds){
                array_push($workgroupIds,$workgroup['id']);
            });
        }else{
            $this->authorities()->each(function(Authority $authority)use(&$workgroupIds){
                if($authority->type=="工作组"){array_push($workgroupIds,$authority->relevance);}
            });
        }
        return $workgroupIds;
    }
}
