<?php

namespace App\Http\Controllers\Api\mini;

use App\Models\ProjectRole;
use App\Models\ProjectUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ProjectRoleController extends BaseController
{
    protected $model;

    public function __construct()
    {
        $this->model = new ProjectRole();
    }

    public function create(Request $request)
    {
        if(empty($request->input('name'))) return $this->error(['msg' => '项目名称不能为空']);
        if($item = $this->model->where('name', $request->input('name'))->first()) return $this->error(['msg' => '项目名称已存在']);
        $res = $this->model->create([
            'name' => $request->input('name')
        ]);
        if(!$res) return $this->error(['msg' => '创建失败']);
        return $this->success(['msg' => '创建成功']);
    }

    public function get(Request $request)
    {
        $items = $this->model;
        $tmp_items = collect(['name']);
        foreach($tmp_items as $tmp_item) {
            if($request->has($tmp_item) && !empty($request->input($tmp_item))) {
                $items = $items->where($tmp_item, 'like', '%' . $request->input($tmp_item) . '%');
            }
        }

        $items = $items->paginate();

        foreach($items as $item) {
            $item->date = substr($item->created_at, 0, 10);
        }

        return $this->success(['msg' => '创建成功', 'data' => $items->items()]);
    }

    public function getAll()
    {
        $items = $this->model->get();
        return $this->success(['msg' => '创建成功', 'data' => $items]);
    }

    public function getByExclude()
    {
        $top_role = Auth::guard('mini')->user()->getTopRole();
        if($top_role && in_array($top_role->key, ['sub', 'admin'])) {
            $items = $this->model->whereIn('key', ['work', 'machine', 'assist', 'manager'])->get();
        } else {
            $items = $this->model->whereIn('key', ['work', 'machine', 'assist'])->get();
        }

        return $this->success(['msg' => '创建成功', 'data' => $items]);
    }

    public function getRoleAndRights(Request $request)
    {
        $user = Auth::guard('mini')->user();
        if (!$user || !$request->input('id')) return $this->success(['data' => null]);
        $project_user = ProjectUser::where([
            ['user_id', $user->id],
            ['project_id', $request->input('id')]
        ])->first();
        if ($project_user) {
            $project_role = ProjectRole::find($project_user->project_role_id);
            if ($project_role) {
                $project_role->rights = $project_role->getRights();
                return $this->success(['msg' => '创建成功', 'data' => $project_role]);
            }
        }
        return $this->success(['data' => null]);
    }
}
