<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable
{
    use SoftDeletes;
    protected $guarded = [];

    public function getValidator(Request $request, $type)
    {
        if ($type == 'store') {
            $validator = Validator::make($request->input('data'), [
                'name' => 'required|unique: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, $request) {
                if ($check) {
                    $validator->errors()->add('name', '用户名已存在');
                }
            });
        }
        return $validator;
    }

    public function getAvatar()
    {
        return '<img style="width: 40px; height: 40px" src="' . $this['avatar'] . '"  />';
    }

    public function role()
    {
        return $this->belongsTo('App\Models\Role', 'role_id');
    }

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

    public function projects()
    {
        return $this->belongsToMany('App\Models\Project', 'project_users', 'user_id', 'project_id');
    }

    public function project_users()
    {
        return $this->hasMany('App\Models\ProjectUser', 'user_id');
    }

    public function project_roles()
    {
        return $this->belongsToMany('App\Models\ProjectRole', 'project_users', 'project_role_id', 'user_id');
    }

    public function getProjectRoleName()
    {
        $ids = ProjectUser::where('user_id', $this['id'])->pluck('project_role_id');
        return ProjectRole::whereIn('id', $ids)->pluck('name')->implode(',');
    }

    public function getProjectName()
    {
        return $this->projects()->pluck('name')->implode(',');
    }

    public static function getOptions()
    {
        return self::where('id', '>', 0)->get()->toArray();
    }

    public function getTopRole()
    {
        $project_role_ids = ProjectUser::where('user_id', $this['id'])->pluck('project_role_id');
        $project_role = ProjectRole::whereIn('id', $project_role_ids)->orderBy('level', 'desc')->first();
        $is_manager = ProjectUser::where('user_id',$this['id'])->where(['project_role_id'=>4])->count();
        if($is_manager){
            $project_role->key = 'machine';
        }
        if($project_role) {
            $project_role->rights = $project_role->getRights();
        }
        return $project_role;
    }

    public function getLevel($project_id)
    {
        $project_user = ProjectUser::where([
            ['user_id', $this['id']],
            ['project_id', $project_id]
        ])->first();
        if($project_user) {
            $project_role = ProjectRole::find($project_user->project_role_id);
            return $project_role ? $project_role['level'] : 0;
        }
        return 0;
    }

    public function getUserInfo($session_key = null)
    {
        $user = User::find($this['id']);
        $user->topRole = $user->getTopRole();
        if($session_key) $user->session_key = $session_key;
        return $user;
    }
}
