<?php
namespace App\Http\Controllers\Admin;

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

class UserController extends BaseController
{
    protected $model;

    protected $role;

    protected $project;

    protected $model_name = '用户';

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

    protected $view_path = 'admin.users.';

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

    public function __construct()
    {
        parent::__construct();
        $this->model = new User();
        $this->role = new ProjectRole();
        $this->project = new Project();
    }

    public function index()
    {
        $role_options = $this->role->getOptions();
        $project_options = $this->project->getOptions();
        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', 'role_options', 'project_options'));
    }

    public function get(Request $request)
    {
        $items = $this->model->where('id', '>', 0)->orderBy('id','desc');

        $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) . '%');
            }
        }
        $ids = [];
        if($request->input('project_id') || $request->input('project_role_id')) {
            $project_users = ProjectUser::where('id', '>', 0);
            if($request->input('project_id')) {
                $project_users = $project_users->where('project_id', $request->input('project_id'));
            }
            if($request->input('project_role_id')) {
                $project_users = $project_users->where('project_role_id', $request->input('project_role_id'));
            }
            $ids = $project_users->pluck('user_id')->unique();
        }
        if(count($ids) > 0) {
            $items = $items->whereIn('id', $ids);
        }

        $items = $items->orderBy('created_at', 'desc')->paginate();
//        foreach($items as $item) {
//            $item->role_name = $item->getProjectRoleName();
//            $item->project_name = $item->getProjectName();
//        }
        return response()->json(['code' => 0, 'message' => '', 'count' => $items->total(), 'data' => $items->items()]);
    }

    public function create()
    {
        $role_options = $this->role->getOptions();
        $project_options = $this->project->getOptions();
//        $role_options = array_merge([['id' => '', 'name' => '项目角色']], $role_options);
//        $project_options = array_merge([['id' => '', 'name' => '项目']], $project_options);
        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', 'role_options', 'project_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');
        if (strlen($data['phone'])!=11)
        {
            return back()->withErrors(['sg_error_info' => '请输入正确的手机号']);
        }
//        $project_id = $data['project_id'];
//        $project_role_id = $data['project_role_id'];
        unset($data['password_confirmation']);
//        unset($data['project_id']);
//        unset($data['project_role_id']);
        $data['password'] = bcrypt($data['password']);
        $res = $this->model->create($data);
//        if($project_id || $project_role_id) {
//            ProjectUser::create([
//                'project_id' => $project_id,
//                'project_role_id' => $project_role_id,
//                'user_id' => $res['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' => '找不到要编辑的数据']);
        $role_options = $this->role->getOptions();
        $project_options = $this->project->getOptions();
//        $role_options = array_merge([['id' => '', 'name' => '项目角色']], $role_options);
//        $project_options = array_merge([['id' => '', 'name' => '项目']], $project_options);
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
//        $project_user = ProjectUser::where('user_id', $item->id)->first();
//        $project_id = $project_user ? $project_user->project_id : '';
//        $project_role_id = $project_user ? $project_user->project_role_id : '';
        return view($this->view_path . 'edit', compact('model', 'model_name', 'pre_uri', 'item', 'role_options', 'project_options'));
    }

    public function update(Request $request)
    {
        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');
        if(isset($data['password']) && !empty($data['password'])) {
            $data['password'] = bcrypt($data['password']);
        } else {
            unset($data['password']);
        }
//        $project_id = $data['project_id'];
//        $project_role_id = $data['project_role_id'];
        unset($data['password_confirmation']);
//        unset($data['project_id']);
//        unset($data['project_role_id']);
        $res = $this->model->where('id', $request->input('id'))->update($data);
//        if($project_id || $project_role_id) {
//            ProjectUser::updateOrCreate([
//                'project_id' => $project_id,
//                'project_role_id' => $project_role_id,
//                'user_id' => $request->input('id')
//            ]);
//        }
        if(!$res) return back()->withErrors(['sg_error_info' => '数据库保存失败！']);
        return back()->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' => '找不到要删除的数据']);
        ProjectUser::where('user_id', $item->id)->delete();
        $res = $item->delete();
        if (!$res) return response()->json(['status' => 'fail', 'info' => '删除失败']);
        return response()->json(['status' => 'success', 'info' => '操作成功']);
    }

    public function changePassword()
    {
        $item = Auth::guard('mini')->user();
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'change-password', compact('model', 'model_name', 'pre_uri', 'item'));
    }

    public function updatePassword(Request $request)
    {
        $validator = $this->model->getValidator($request, 'change-password');
        $user = Auth::guard('mini')->user();
        $data = $request->input('data');
        $validator->after(function ($validator) use($request, $data, $user) {
            if(!isset($data['old_password'])) {
                $validator->errors()->add('old_password', '请填写原来密码');
            } else if(!Hash::check($data['old_password'], $user['password'])) {
                $validator->errors()->add('old_password', '原来密码错误');
            }
        });
        if($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $this->model->where('id', $user['id'])->update(['password' => $data['password']]);

        return back()->with(['sg_success_info' => '操作成功']);
    }
}