<?php

namespace App\Http\Controllers;

use App\Authority;
use App\Components\AsyncResponse;
use App\Events\CustomerStored;
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
{
    use AsyncResponse;

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     *
     * @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')) {
            $name=$request->input('name');
            if (strpos($name, ',') || strpos($name, '，') || strpos($name, ' ')) {
                $arr = array_filter(preg_split('/[,， ]+/is', $name));
                $query->whereIn('name', $arr);
                unset($name);
            } else {
                $query->where('name','like',$name.'%');
            }
        }
        if ($request->has('code')) {
            $code=$request->input('code');
            if (strpos($code, ',') || strpos($code, '，') || strpos($code, ' ')) {
                $arr = array_filter(preg_split('/[,， ]+/is', $code));
                $query->whereIn('code', $arr);
                unset($code);
            } else {
                $query->where('code','like',$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');
    }

    public function store(Request $request)
    {
        if (!Gate::allows('货主-录入')) {
            return redirect(url('/'));
        }
        $this->validatorCreate($request->all())->validate();
        $owner = new Owner($request->all());
        $owner->save();
        $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') ?? '');
    }

    public function apiStore()
    {
        $this->gate("货主-录入");

        if (request("id"))$errors = $this->validatorUpdate(request()->input(),request("id"))->errors();
        else $errors = $this->validatorCreate(request()->input())->errors();
        if (count($errors)>0)$this->success(["errors"=>$errors]);

        if (request("id")){
            $owner = app("OwnerService")->find(request("id"));
            if (!$owner)$this->error("项目已被删除");
            if ($owner->name == request("name") && $owner->code == request("code"))
                $this->success($owner);
            $owner = app("OwnerService")->update($owner,[
                "name" => request("name"),
                "code" => request("code"),
            ]);
        }else $owner = app("OwnerService")->create([
            "name" => request("name"),
            "code" => request("code"),
        ]);

        $this->success($owner);
    }

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

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

    public function getOwners()
    {
        $owners = app('OwnerService')->getIntersectPermitting(['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
     *
     * @throws Exception
     */
    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("OwnerService")->deleteAuthority($owner);
        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)->first();
        $owner->update(["deleted_at" => null]);
        app("OwnerService")->createAuthority($owner);
        app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
        return ['success' => 'true', 'owner' => $owner];
    }

    public function get(Request $request)
    {
        $params = [];
        if ($request->has("customer_id"))$params["customer_id"] = $request->input("customer_id");
        return ["success"=>true,"data"=>app("OwnerService")->get($params,null,false)];
    }
}
