<?php

namespace App\Http\Controllers\Admin;

use App\Models\Project;
use App\Models\ProjectRole;
use App\Models\ProjectUser;
use App\Models\User;
use function Couchbase\defaultDecoder;
use Illuminate\Http\Request;

class ProjectUserController extends BaseController
{
    protected $model;

    protected $department;

    protected $model_name = '项目角色';

    protected $pre_uri = '/admin/ProjectUser/';

    protected $view_path = 'admin.project-users.';

    protected $redirect_index = '/admin/ProjectUser/index';

    public function __construct()
    {
        parent::__construct();
        $this->model = new ProjectUser();
    }

    public function index(Request $request)
    {
        $project = Project::find($request->input('project_id'));
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'index', compact('model', 'model_name','pre_uri', 'project'));
    }

    public function get(Request $request)
    {
        $items = $this->model->with('user', 'projectRole');

        if($request->input('name')) {
            $user_ids = User::where('name', 'like', '%' . $request->input('name') . '')->pluck('id')->unique();
            if(count($user_ids) > 0) {
                $items = $items->whereIn('user_id', $user_ids);
            }
        }

        $select_items = collect(['project_id', 'user_id']);
        foreach($select_items as $select_item) {
            if($request->has($select_item) && !empty($request->input($select_item))) {
                $items = $items->where($select_item, '=', $request->input($select_item));
            }
        }

        $items = $items->paginate();

        foreach($items as $item) {
            $item->user_name = $item->user ? $item->user->name : '';
            $item->role_name = $item->projectRole ? $item->projectRole->name : '';
            $item->project_name = $item->project ? $item->project->name : '';
        }

        return response()->json(['code' => 0, 'message' => '', 'count' => $items->total(), 'data' => $items->items()]);
    }

    public function create()
    {
        $user_options = (new User())->getOptions();
        $role_options = (new ProjectRole())->getNotLeaderOptions();
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'create', compact('model', 'model_name','pre_uri', 'user_options', 'role_options'));
    }

    public function store(Request $request)
    {
        if(empty($request->input('data')) || !is_array($request->input('data'))) return back()->withErrors(['sg_error_info' => '数据错误']);
        $validator = $this->model->getValidator($request, 'store');
        if($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        $data = $request->input('data');
        $project_id = $data['project_id'];
        $user_id = $data['user_id'];
        $project_role_id = $data['project_role_id'];
        //查找该用户
        $project_users = ProjectUser::where('project_id',$project_id)->where('user_id',$user_id)->get()->toArray();
        //用户在项目中
        if (count($project_users)!=0)
        {
            if ($project_role_id == 4)
            {
                //原本的项目经理变成项目副经理
                $s_user_id = ProjectUser::where('project_id',$project_id)->where('project_role_id',4)->value('user_id');
                ProjectUser::where('project_id',$project_id)->where('user_id',$s_user_id)->update(['project_role_id'=>3]);
            }else if ($project_role_id == 2)
            {
                $m_user_id = ProjectUser::where('project_id',$project_id)->where('project_role_id',2)->value('user_id');
                ProjectUser::where('project_id',$project_id)->where('user_id',$m_user_id)->update(['project_role_id'=>1]);
            }
            //自己的角色变成项目经理
                $res = ProjectUser::where('project_id',$project_id)->where('user_id',$user_id)->update(['project_role_id'=>$project_role_id]);
                Project::where('id',$project_id)->update(['user_id'=>$user_id]);
                if(empty($res)) return back()->withErrors(['sg_error_info' => '更新失败']);
                return redirect($this->pre_uri . 'create')->with(['sg_success_info' => '更新成功']);
        }else{
            // 用户不在项目中
            if ($project_role_id == 4)
            {
                //原本的项目经理变成项目副经理
                $s_user_id = ProjectUser::where('project_id',$project_id)->where('project_role_id',4)->value('user_id');
                ProjectUser::where('project_id',$project_id)->where('user_id',$s_user_id)->update(['project_role_id'=>3]);
            }else if ($project_role_id == 2)
            {
                $m_user_id = ProjectUser::where('project_id',$project_id)->where('project_role_id',2)->value('user_id');
                ProjectUser::where('project_id',$project_id)->where('user_id',$m_user_id)->update(['project_role_id'=>1]);
            }
            $res = $this->model->create($data);
            Project::where('id',$project_id)->update(['user_id'=>$user_id]);
            if(empty($res)) return back()->withErrors(['sg_error_info' => '保存失败']);
            return redirect($this->pre_uri . 'create')->with(['sg_success_info' => '创建成功']);
        }
    }

    public function edit(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
        $user_options = (new User())->getOptions();
        $role_options = (new ProjectRole())->getNotLeaderOptions();
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'edit', compact('model', 'model_name', 'pre_uri', 'item', 'user_options', 'role_options'));
    }

    public function update(Request $request)
    {
        $user_id = intval(request('user_id'));
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
        if(empty($request->input('data')) || !is_array($request->input('data'))) return back()->withErrors(['sg_error_info' => '数据错误']);
        $validator = $this->model->getValidator($request, 'update');
        if($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        $data = $request->input('data');
        $project_id = $request->input('project_id');
        $project_users = ProjectUser::where('project_id',$project_id)->where('user_id',$user_id)->get()->toArray();

        if (count($project_users)!=0)
        {
            if ($data['project_role_id'] == 4)
            {
                //原本的项目经理变成项目副经理
                $s_user_id = ProjectUser::where('project_id',$project_id)->where('project_role_id',4)->value('user_id');
                ProjectUser::where('project_id',$project_id)->where('user_id',$s_user_id)->update(['project_role_id'=>3]);
            }else if ($data['project_role_id'] == 2)
            {
                $m_user_id = ProjectUser::where('project_id',$project_id)->where('project_role_id',2)->value('user_id');
                ProjectUser::where('project_id',$project_id)->where('user_id',$m_user_id)->update(['project_role_id'=>1]);
            }
            //自己的角色变成项目经理
            $res = ProjectUser::where('project_id',$project_id)->where('user_id',$user_id)->update(['project_role_id'=>$data['project_role_id']]);
            if(empty($res)) return back()->withErrors(['sg_error_info' => '更新失败']);
            return redirect($this->pre_uri . 'create')->with(['sg_success_info' => '更新成功']);
        }
        else
        {
            if ($data['project_role_id'] == 4)
            {
                //原本的项目经理变成项目副经理
                $s_user_id = ProjectUser::where('project_id',$project_id)->where('project_role_id',4)->value('user_id');
                ProjectUser::where('project_id',$project_id)->where('user_id',$s_user_id)->update(['project_role_id'=>3]);
            }else if ($data['project_role_id'] == 2)
            {
                $m_user_id = ProjectUser::where('project_id',$data['project_id'])->where('project_role_id',2)->value('user_id');
                ProjectUser::where('project_id',$project_id)->where('user_id',$m_user_id)->update(['project_role_id'=>1]);
            }
            $res = $this->model->create($data);
            if(empty($res)) return back()->withErrors(['sg_error_info' => '保存失败']);
            return redirect($this->pre_uri . 'create')->with(['sg_success_info' => '创建成功']);
        }

    }

    public function delete(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return response()->json(['status' => 'fail', 'info' => '找不到要删除的数据']);
        $res = $item->delete();
        if (!$res) return response()->json(['status' => 'fail', 'info' => '删除失败']);
        return response()->json(['status' => 'success', 'info' => '操作成功']);
    }

}
