<?php

namespace App\Http\Controllers;

use App\Authority;
use App\Components\AsyncResponse;
use App\Owner;
use App\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Queue\RedisQueue;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;

class AuthorityController extends Controller
{
    use AsyncResponse;

    /**
     * Display a listing of the resource.
     *
     * @return string
     */
    public function index()
    {

        if(!Gate::allows('权限-查询')){ return redirect(url('/'));  }
        $authorities=Authority::orderBy('id','asc')->paginate(100);
        return view('maintenance.authority.index',['authorities'=>$authorities]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return string
     */
    public function create()
    {
        if(!Gate::allows('权限-录入')){ return redirect(url('/'));  }
        $owners=Owner::all();
        return view('maintenance.authority.create',compact('owners'));
    }

//    /**
//     * Store a newly created resource in storage.
//     *
//     * @param Request $request
//     * @return string
//     */
//    public function store(Request $request)
//    {
//        if(!Gate::allows('权限-录入')){ return redirect(url('/'));  }
//        $inputs=$request->all();
//        $inputs['combinedName']=$request->input('name').'_'.$request->input('id_owner');
//        $this->validatorCreate($inputs)->validate();
//        $successName= $request->input('name')??'';
//        $inputs['name']=$inputs['combinedName'];
//
//        if($request->input('id_owner')??''){
//            $owner=Owner::find($inputs['id_owner']);
//            if(isset($inputs['remark'])){
//                $inputs['remark'].="(key: {$inputs['combinedName']})";
//            }else{
//                $inputs['remark']="(key: {$inputs['combinedName']})";
//            }
//            $inputs['alias_name']=$request->input('name')."_(货主：$owner->name)";
//            $successName.="(货主：$owner->name)";
//        }else{
//            $inputs['alias_name']=$request->input('name');
//        }
//        $authority=new Authority($inputs);
//        $authority->save();
//
//        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
//        return redirect('maintenance/authority/create')->with('successTip',"成功录入权限“{$successName}”");
//    }

    public function store(Request $request)
    {
        if(!Gate::allows('权限-录入')){ return redirect(url('/'));  }
        $this->validatorCreate($request->all())->validate();
        $owner=Owner::find($request->input('id_owner'));

        $authority=new Authority(['alias_name'=>"(货主：{$owner['name']})",'name'=>"_{$owner['id']}",'remark'=>"(key: _{$owner['id']})"]);
        $authority->save();

        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('maintenance/authority/create')->with('successTip',"成功录入权限: (货主：{$owner['name']})");
    }

    protected function validatorCreate(array $data)
    {
        $data['name']="_{$data['id_owner']}";
        return Validator::make($data, [
            'id_owner' => ['required', 'exists:owners,id'],
            'name' => ['unique:authorities,name'],
        ],[
            'id_owner.required' => '必须选一个货主',
            'id_owner.exists' => '当前货主不存在',
            'name.unique' => '该货主对应权限已添加过',
        ]);
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param \App\Http\Controllers\Authority $authority
     * @return Response
     */
    public function edit(Authority $authority)
    {
        if(!Gate::allows('权限-编辑')){ return redirect(url('/'));  }
        $owners=Owner::all();
        return view('maintenance.authority.edit',compact('owners','authority'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param \App\Http\Controllers\Authority $authority
     * @return Response
     */
    public function update(Request $request, Authority $authority)
    {
        if(!Gate::allows('权限-编辑')){ return redirect(url('/'));  }
        $this->validatorUpdate($request->all())->validate();
        $authority->fill($request->all());
        $authority->update();
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('maintenance/authority/')->with('successTip',"成功修改权限“{$authority['name']}”！");
    }

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

    public function getAuthoritiesApi()
    {
        /** @var User $user */
        $user = Auth::user();
        if(!$user) $this->success(null);
        if($user && $user->isSuperAdmin()){
            $this->success( Authority::query()->orderBy('name')->get());
        }
        $authority = $user->authorities();
        $this->success($authority);
    }
}
