<?php

namespace App\Http\Controllers;

use App\Carrier;
use App\Exports\UserExport;
use App\Role;
use App\User;
use App\UserWorkgroup;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        if(!Gate::allows('用户-查询')){ return redirect(url('/'));  }
        $query = User::with(['roles','carriers','userWorkgroups']);
        if($request->has('user')){
           $query->where('name','like',$request->input('user'));
        }
        if($request->has('role')){
            $role = $request->input('role');
            $query->whereHas('roles',function($query) use ($role){
                 $query->where('name','like',$role);
            });
        }
        $users = $query->orderBy('id','desc')->paginate($request->paginate ?? 50);
        $users->each(function (User $user){
            $user['isSuperAdmin']=$user->isSuperAdmin();
        });
        return view('maintenance.user.index',['users'=>$users]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        if(!Gate::allows('用户-录入')){ return redirect(url('/'));  }
        $roles=Role::all();
        $carriers=Carrier::select('id','name')->get();
        $userWorkgroups=UserWorkgroup::get();
        return view('maintenance.user.create',['rolesAll'=>$roles,'carriers'=>$carriers,'userWorkgroups'=>$userWorkgroups]);
    }



    protected function validatorCreate(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:50', 'unique:users'],
        ]);
    }
    protected function validatorUpdate(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:50'],
        ]);
    }
    /**
     * Display the specified resource.
     *
     * @param User $user
     * @return Response
     */
    public function show(User $user)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param User $user
     * @return Response
     */
    public function edit(User $user)
    {
        if(!Gate::allows('用户-编辑')){ return redirect(url('/'));  }
        $rolesAll=Role::all();
        $roles=$user->roles()->get();
        $carriers=Carrier::select('id','name')->get();
        $carrierUser=$user->carriers()->get();
        $userWorkgroups=UserWorkgroup::get();
        $userWorkgroup=$user->userWorkgroups()->first();
        return view('maintenance.user.edit',compact('user','rolesAll','roles','carriers','carrierUser','userWorkgroups','userWorkgroup'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param User $user
     * @return Response
     */
    public function update(Request $request, User $user)
    {
        if(!Gate::allows('用户-编辑')){ return redirect(url('/'));  }
        $this->validatorUpdate($request->all())->validate();
        $user->fill($request->all());
        $user->update();
        $rolesIds=$request->input('role')??'';
        if($rolesIds){
            $roleIdArr=explode(',',$rolesIds);
            $user->roles()->sync($roleIdArr);
        }else{
            $user->roles()->sync([]);
        }
        $carrierIds=$request->input('carrier')??'';
        if($carrierIds){
            $carrierIds=explode(',',$carrierIds);
            $user->carriers()->sync($carrierIds);
        }else{
            $user->carriers()->sync([]);
        }
        $userWorkgroupId=$request->input('userWorkgroupID');
        if($userWorkgroupId){
            $user->userWorkgroups()->sync([$userWorkgroupId]);
        }else{
            $user->userWorkgroups()->sync([]);
        }
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('maintenance/user/')->with('successTip',"成功修改用户“{$user['name']}”！");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param User $user
     * @return array|Response
     * @throws Exception
     */
    public function destroy(User $user)
    {
        if(!Gate::allows('用户-删除')){ return redirect(url('/'));  }
        app('LogService')->log(__METHOD__,__FUNCTION__,$user->toJson(),Auth::user()['id']);
        $re=$user->delete();
        return ['success'=>$re];
    }
}
