<?php

namespace App\Http\Controllers;

use App\Events\UpdateOrderPackageExceptionListenerEvent;
use App\Filters\OrderPackageFilters;
use App\Logistic;
use App\OrderPackage;
use App\Owner;
use App\Services\UserService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class PackageLogisticController extends Controller
{
    /**
     * PackageLogisticsController constructor.
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(Request $request, OrderPackageFilters $filters)
    {
        /** @var UserService $userService */
        $userService = app('UserService');
        $owner_ids = $userService->getPermittingOwnerIds(auth()->user());
        $paginateParams = $request->input();
        $orderPackages = OrderPackage::query()
            ->filter($filters)
            ->whereIn('owner_id', $owner_ids)->with(['order.logistic', 'order.owner', 'order.issue' => function ($query) {
                $query->with(['issueType', 'logs'=>function($query) {
                    $query->with('user')->orderBy('created_at', 'DESC');
                }]);
            }])->orderByDesc('id')->paginate($request->paginate ?? 50);
        $logistics = Logistic::all();
        $owners = Owner::find($owner_ids);
        return view('package.logistic.index', compact('orderPackages', 'logistics', 'owners', 'paginateParams'));
    }

    public function update(Request $request)
    {
        $data = [];
        if ('无' == $request->input('exception_type')) {
            $data['exception_type'] = $request->input('exception_type');
            $data['exception'] = "否";
        } else {
            $data['exception_type'] = $request->input('exception_type');
        }
        OrderPackage::query()->where('id', $request['id'])->update($data);
        //更新统计数据
        event(new UpdateOrderPackageExceptionListenerEvent([$request['id']]));
    }

    public function batchUpdate(Request $request)
    {
        $data = [];
        if (array_key_exists('exception_type',$request->all())) {
            if ('无' == $request->input('exception_type')) {
                $data['exception_type'] = $request->input('exception_type');
                $data['exception'] = "否";
            } else {
                $data['exception_type'] = $request->input('exception_type');
            }
        }else if (array_key_exists('status',$request->all())) {
            $data['status'] = $request->input('status');
        }
        $logistic_numbers = $request->input('logistic_numbers');
        OrderPackage::query()->whereIn('logistic_number', $logistic_numbers)->update($data);
        //更新统计数据
        event(new UpdateOrderPackageExceptionListenerEvent($logistic_numbers));
    }
}
