<?php

namespace App\Models;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Project extends BaseModel
{
    use SoftDeletes;

    public function getValidator(Request $request, $type)
    {
        $validator = Validator::make($request->input('data'), [
            'name' => 'required'
        ], [
            'name.required' => '名称必填'
        ]);
        $validator->after(function ($validator) use($request) {
            $data = $request->input('data');
            if (isset($data['name']) && mb_strlen($data['name']) > 16) {
                $validator->errors()->add('name', '名称长度不能超过16');
            }
        });
        return $validator;
    }

    public function getTwoLevelOptions()
    {
        $projects = Project::select('name as text', 'id as value')->where('id','!=',1)->get();
        $projects = $projects->prepend($this->transObject(['text' => '选择项目', 'value' => '']));
        foreach ($projects as $project) {
            $work_points = WorkPoint::where('project_id', $project->value)->select('name as text', 'id as value')->get();
            $project->work_points = $work_points->prepend($this->transObject(['text' => '选择工点', 'value' => '']));
        }
        return $projects;
    }

    public function transObject($items)
    {
        return json_decode(json_encode($items));
    }
    public function project_user(){
        return $this->hasMany(ProjectUser::class,'project_id','id');
    }
    public function getManager()
    {
        $role = ProjectRole::getByKey('manager');
        if(!$role) return null;
        $res = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['project_role_id', '=', $role->id]
        ])->first();
        if($res) return User::find($res['user_id']);
        return false;
    }

    public function user()
    {
        return $this->belongsTo('App\Models\User', 'user_id');
    }

    public function getUserProjectRole()
    {
        $user = Auth::guard('mini')->user();
        $project_user = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['user_id', '=', $user->id]
        ])->first();
        if($project_user) {
            return ProjectRole::find($project_user->project_role_id);
        }
        return null;
    }

    public function isTopLevel($user)
    {
        $current_role = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['user_id', '=', $user->id]
        ])->first();
        if(empty($current_role)) return false;
        $res = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['project_role_id', '>', $current_role['project_role_id']]
        ])->first();
        return $res ? false : true;
    }

    /**
     * @param User $user
     * @param $type: current/next
     * @return ProjectUser
     */
    public function getProjectUser(User $user, $type = 'current')
    {
        $current = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['user_id', '=', $user['id']]
        ])->first();
        if($type == 'current' || !$current) return $current;
        $next = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['project_role_id', '>', $current['project_role_id']]
        ])->first();
        return $next ? $next : $current;
    }

    public function getCreateProjectRoleId(User $user, $is_draft)
    {
        $project_user = $this->getProjectUser($user, $is_draft == 1 ? 'current' : 'next');
        return $project_user ? $project_user['project_role_id'] : '';
    }

    public static function getOptions()
    {
        return self::get()->toArray();
    }
    public static function getNotOneProjectOptions(){
        return self::where('id','!=',1)->get();
    }
    public function createDefaultUser()
    {
        $user_id = $this['user_id'];
        ProjectUser::where('project_id', $this['id'])->delete();
        ProjectUser::create([
            'project_id' => $this['id'],
            'user_id' => $user_id,
            'project_role_id' => ProjectRole::getByKey('manager', 'id')
        ]);
        $project_user = ProjectUser::where('project_role_id', ProjectRole::getByKey('admin', 'id'))->first();
        if($project_user) {
            ProjectUser::create([
                'project_id' => $this['id'],
                'user_id' => $project_user->user_id,
                'project_role_id' => $project_user->project_role_id
            ]);
        }
    }
}
