<?php

namespace App\Http\Controllers;

use App\Role;
use App\Supplier;
use App\User;
use App\UserDetail;
use App\UserWorkgroup;
use Doctrine\DBAL\Configuration;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        if(!Gate::allows('用户-查询')){ return redirect(url('/'));  }
        $owners=app("OwnerService")->getIntersectPermitting();
        $userDetailQuery = UserDetail::query()->select('user_id')->where('type','临时工');
        $query = User::with(['roles','logistics','userWorkgroups','suppliers','userDetail'])->whereNotIn('id',$userDetailQuery);
        if($request->has('user')){
            $user=$request->input('user');
            $query->where('name','like',$user.'%');
        }
        if($request->has('role')){
            $role = $request->input('role');
            $query->whereHas('roles',function($query) use ($role){
                if (strpos($role, ',') || strpos($role, '，') || strpos($role, ' ')) {
                    $arr = array_filter(preg_split('/[,， ]+/is', $role));
                    $query->whereIn('name', $arr);
                    unset($role);
                } else {
                    $query->where('name','like',$role.'%');
                }
            });
        }
        if($request->input('owner_id')){
            $owner_id= $request->input('owner_id');
            $owner_ids = array_filter(preg_split('/[,， ]+/is',$owner_id));
            $ownerIds=[];
            foreach ($owner_ids as $id)$ownerIds[]='_'.$id;
            $query->whereHas('roles',function($query) use ($ownerIds){
                $query->whereHas('authorities',function ($query)use($ownerIds){
                    $query->whereIn('name',$ownerIds);
                });
            });
        }
        $users = $query->orderBy('id','desc')->paginate($request->paginate ?? 50);
        $users->each(function (User $user){
            $user['isSuperAdmin']=$user->isSuperAdmin();
        });
        return view('maintenance.user.index',compact('users','owners'));
    }

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



    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'],
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param User $user
     * @return Response
     */
    public function edit(User $user)
    {
        if(!Gate::allows('用户-编辑')){ return redirect(url('/'));  }
        $user=$user->loadMissing('userDetail');
        $rolesAll=Role::all();
        $roles=$user->roles()->get();
        $logistics=app('LogisticService')->getSelection(["id","name"],"物流");
        $logisticUser=$user->logistics()->get();
        $userWorkgroups=UserWorkgroup::query()->get();
        $userWorkgroup=$user->userWorkgroups()->first();
        $supplierUser=$user->suppliers()->get();
        $suppliers=Supplier::query()->get();
        return view('maintenance.user.edit',compact('user','rolesAll','roles','logistics','logisticUser','userWorkgroups','userWorkgroup','suppliers','supplierUser'));
    }

    /**
     * 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([]);
        }
        $supplierIds=$request->input('supplier')??'';
        if($supplierIds){
            $supplierIdArr=explode(',',$supplierIds);
            $user->suppliers()->sync($supplierIdArr);
        }else{
            $user->suppliers()->sync([]);
        }
        $carrierIds=$request->input('logistic')??'';
        if($carrierIds){
            $carrierIds=explode(',',$carrierIds);
            $user->logistics()->sync($carrierIds);
        }else{
            $user->logistics()->sync([]);
        }
        $userWorkgroupId=$request->input('userWorkgroupID');
        if($userWorkgroupId){
            $user->userWorkgroups()->sync([$userWorkgroupId]);
        }else{
            $user->userWorkgroups()->sync([]);
        }
        $phone=$request->input('phone');
        $user=$user->loadMissing('userDetail');
        if ($phone){
            if (!$user->userDetail) UserDetail::query()->create(['user_id'=>$user->id,'mobile_phone'=>$phone]);
            UserDetail::query()->where('user_id',$user->id) ->update(['mobile_phone'=>$phone]);
        }
        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];
    }
}
