<?php

namespace App\Http\Controllers;

use App\Authority;
use App\Events\CustomerStored;
use App\Log;
use App\Logistic;
use App\Owner;
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;

class OwnerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        if (!Gate::allows('货主-查询')) {
            return redirect(url('/'));
        }
        $query = Owner::query()
            ->orderBy('id', 'desc')
            ->whereNull('deleted_at');
        if ($request->has('name')) {
            $query->where('name', 'like', $request->name . '%');
        }
        if ($request->has('code')) {
            $query->where('code', 'like', $request->code . '%');
        }
        $owners = $query->paginate($request->paginate);
        return view('maintenance.owner.index', ['owners' => $owners]);
    }

    public function create()
    {
        if (!Gate::allows('货主-录入')) {
            return redirect(url('/'));
        }
        return view('maintenance.owner.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return string
     */
    public function store(Request $request)
    {
        if (!Gate::allows('货主-录入')) {
            return redirect(url('/'));
        }
        $this->validatorCreate($request->all())->validate();
        $owner = new Owner($request->all());
        $owner->save();
//        event(new CustomerStoreEvent($owner));
        event(new CustomerStored($owner));
        $authority = new Authority([
            'name' => "_{$owner['id']}",
            'alias_name' => "(货主：{$owner['name']})",
            'remark' => "(key: _{$owner['id']})",
        ]);
        $authority->save();

        app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
        return redirect('maintenance/owner/create')->with('successTip', $request->input('name') ?? '');
    }

    protected function validatorCreate(array $data)
    {
        return Validator::make($data, [
            'code' => ['required', 'string', 'max:50', "unique:owners,code"],
            'name' => ['required', 'string', 'max:50'],
        ]);
    }

    protected function validatorUpdate(array $data, $id)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:50'],
            'code' => ['required', 'string', 'max:50', "unique:owners,code,$id"]
        ]);
    }

    public function getOwners()
    {
        $owners = app('OwnerService')->getSelection(['id', 'code', 'name']);
        return $owners;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Owner $owner
     * @return Response
     */
    public function edit(Owner $owner)
    {
        if (!Gate::allows('货主-编辑')) {
            return redirect(url('/'));
        }
        return view('maintenance.owner.edit', ['owner' => $owner]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param Owner $owner
     * @return Response
     */
    public function update(Request $request, Owner $owner)
    {
        if (!Gate::allows('货主-编辑')) {
            return redirect(url('/'));
        }
        $this->validatorUpdate($request->all(), $owner->id)->validate();
        $owner->fill($request->all());
        $owner->update();
        event(new CustomerStored($owner));
        app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
        return redirect('maintenance/owner/')->with('successTip', "成功修改货主{$owner['name']}！");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Owner $owner
     * @return array|Response
     * @throws Exception
     */
    public function destroy(Owner $owner)
    {
        if (!Gate::allows('货主-删除')) {
            return redirect(url('/'));
        }
        $re = $owner->update([
            "deleted_at" => date('Y-m-d H:i:s'),
        ]);
        app('LogService')->log(__METHOD__, __FUNCTION__, $owner->toJson(), Auth::user()['id']);
        return ['success' => $re];
    }

    public function recycle()
    {
        if (!Gate::allows('货主-删除')) {
            return redirect(url('/'));
        }
        $owners = Owner::query()->orderBy('id', 'desc')->whereNotNull('deleted_at')->paginate(25);
        return view('maintenance.owner.recycle', ['owners' => $owners]);
    }

    public function restoreSelected(Request $request)
    {
        if (!Gate::allows('货主-删除')) {
            return ['success' => 'false', 'fail_info' => "没有权限"];
        }
        $id = $request->input('id');
        $owner = Owner::query()->whereNotNull('deleted_at')->where('id', $id)->update([
            "deleted_at" => null,
        ]);
        app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
        return ['success' => 'true', 'owner' => $owner];
    }
}
