<?php

namespace App\Services;

use App\OrderPackage;
use App\Package;
use App\Services\common\QueryService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;

const TABLE = "order_packages.";
use App\Traits\ServiceAppAop;


class PackageService
{
    use ServiceAppAop;
    protected $modelClass=Package::class;
    private function conditionQuery($params){
        $ownerIds=app('UserService')->getPermittingOwnerIds(Auth::user());
        $packages = OrderPackage::query()->with(['order'=>function($query){
            return  $query->with(['owner','logistic','batch']);
        },'paperBox','measuringMachine'])
        ->whereIn('order_packages.owner_id',$ownerIds)->orderBy(TABLE.'id','DESC');
        if ($params['owner_id'] ?? false){
            $owner_id = explode(',',$params['owner_id']);
            $packages->whereIn('order_packages.owner_id',$owner_id);
            unset($params['owner_id']);
        }
        if ($params['logistic_number'] ?? false){
            $packages->whereIn('logistic_number',array_values(array_filter(preg_split('/[,， ]+/is', $params['logistic_number']))));
            unset($params["logistic_number"]);
        }
        if ($params['is_weighed']?? false) {
            $packages->whereNotNull('weighed_at');
            Arr::forget($params, 'is_weighed');
        }
        if ($params["batch_number"] ?? false){
            $codes = preg_split('/[,， ]+/is', $params["batch_number"]);
            $packages->whereHas("order",function ($query)use($codes){
                /** @var Builder $query */
                $query->whereHas("batch",function ($query)use($codes){
                    /** @var Builder $query */
                    $query->whereIn("code",$codes);
                });
            });
            unset($params["batch_number"]);
        }
        $columnQueryRules=[
            'batch_number' => ['batch' => ''],
            'weighed_at_start' => ['alias' => 'weighed_at', 'startDate' => ':00'],
            'weighed_at_end' => ['alias' => 'weighed_at','endDate' => ":59"],
            'id' => ['multi' => ','],
        ];
        $packages = app(QueryService::class)->query($params,$packages,$columnQueryRules,"order_packages");
        return $packages;
    }

    public function paginate(Request $request){
        $packages = $this->conditionQuery($request->input());
        return $packages->paginate($request->paginate ?? 50);
    }

    public function get(Request $request){
        $packages = $this->conditionQuery($request->input());
        return $packages->get();
    }

    public function getSql($params){
        return $this->conditionQuery($params)->selectRaw(TABLE.'*')
        ->leftJoin('orders',TABLE.'order_id','orders.id')
            ->selectRaw('orders.code order_code,orders.consignee_name order_consignee_name,orders.consignee_phone order_consignee_phone')
        ->LeftJoin('owners','orders.owner_id','owners.id')
            ->selectRaw('owners.name owner_name')
        ->LeftJoin('logistics','orders.logistic_id','logistics.id')
            ->selectRaw('logistics.name logistic_name')
        ->LeftJoin('paper_boxes',TABLE.'paper_box_id','paper_boxes.id')
            ->selectRaw('paper_boxes.model paper_box_name')
        ->LeftJoin('measuring_machines',TABLE.'measuring_machine_id','measuring_machines.id')
            ->selectRaw('measuring_machines.name measuring_machine_name')
        ->sql();
    }

}
