<?php

namespace App\Services;

use App\OrderPackage;
use App\Services\common\QueryService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Traits\ServiceAppAop;


class PackageStatisticsService
{
    use ServiceAppAop;
    /**
     * @param array $params
     * @return Builder
     */
    private function conditionQuery(array $params){
        $ownerIds = app('UserService')->getPermittingOwnerIds(auth()->user());
        $query = DB::table('order_packages')->select(DB::raw('COUNT(*) AS count'))
            ->whereIn('order_packages.owner_id',$ownerIds)
            ->whereNotNull('logistic_id')
            ->leftJoin('orders','order_packages.order_id','orders.id')
                ->selectRaw('orders.owner_id,logistic_id');

        $columnQueryRules=[
            'created_at_start' => ['alias' => 'weighed_at','startDate' => ":00"],
            'created_at_end' => ['alias' => 'weighed_at','endDate' => ":59"],
            'logistic_id' => ['multi' => ','],
            'owner_id' => ['multi' => ','],
        ];
        $query = $query->groupBy('order_packages.owner_id','logistic_id');
        return app(QueryService::class)->query($params,$query,$columnQueryRules,'order_packages');
    }

    public function get(array $params){
        return $this->conditionQuery($params)->get();
    }

    public function getPackageStatistic(array $params)
    {
        $query = $this->conditionQuery($params);
        return DB::table(DB::raw("({$query->sql()}) AS p"))->selectRaw('p.*')
            ->leftJoin('owners','p.owner_id','owners.id')
            ->selectRaw('owners.name owner_name')
            ->leftJoin('logistics','p.logistic_id','logistics.id')
            ->selectRaw('logistics.name logistic_name')
            ->get();
    }

}
