<?php

namespace App\Services;

use App\OrderPackage;
use App\Services\common\QueryService;
use Illuminate\Http\Request;

const TABLE = "order_packages.";

Class PackageService
{
    private function conditionQuery($params){
        $packages = OrderPackage::query()->with(['order'=>function($query){
            $query->with('owner','logistic');
        },'paperBox','measuringMachine'])->orderBy(TABLE.'id','DESC');
        if ($params['owner_id'] ?? false){
            $owner_id = explode(',',$params['owner_id']);
            $packages->whereHas('order',function ($query)use($owner_id){
                $query->whereIn('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"]);
        }
        $columnQueryRules=[
            'batch_number' => ['like' => ''],
            'created_at_start' => ['alias' => 'created_at','startDate' => " 00:00:00"],
            'created_at_end' => ['alias' => 'created_at','endDate' => " 23:59:59"],
            'weighed_at_start' => ['alias' => 'weighed_at','startDate' => " 00:00:00"],
            'weighed_at_end' => ['alias' => 'weighed_at','endDate' => " 23:59: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();
    }

}
