<?php

namespace App\Services;

use App\OwnerFeeDetail;
use App\Services\common\QueryService;
use Illuminate\Database\Eloquent\Builder;
use App\Traits\ServiceAppAop;


class OwnerFeeDetailService
{
    use ServiceAppAop;
    protected $modelClass=OwnerFeeDetail::class;
    /**
     * @param Builder $builder
     * @param array $params
     * @return Builder
     */
    private function query(Builder $builder, array $params)
    {
        $columnQueryRules = [
            'worked_at_start' => ['alias' => 'worked_at', 'startDate' => ''],
            'worked_at_end' => ['alias' => 'worked_at', 'endDate' => ''],
            'owner_id' => ['multi' => ','],
            'id' => ['multi' => ','],
            'operation_bill' => ['batch' => ''],
            'logistic_bill' => ['batch' => ''],
        ];
        if ($params["customer_id"] ?? false){
            $builder->whereHas('owner',function ($query)use(&$params){
                /** @var Builder $query*/
                $query->where("customer_id",$params["customer_id"]);
                unset($params["customer_id"]);
            });
        }
        return app(QueryService::class)->query($params, $builder, $columnQueryRules, 'owner_fee_details');
    }

    public function paginate(array $params, array $withs = null)
    {
        $areas = OwnerFeeDetail::query()->orderByDesc('id');
        if ($withs)$areas->with($withs);
        return $this->query($areas,$params)->paginate($params["paginate"] ?? 50);
    }

    public function getSql($params)
    {
        $query = $this->query(OwnerFeeDetail::query()->orderByDesc('id'),$params);
        $query->selectRaw("owner_fee_details.*,(work_fee+logistic_fee) total");
        $query->leftJoin("owners","owner_fee_details.owner_id","owners.id")
            ->selectRaw("owners.name owner_name")
        ->leftJoin("customers","owners.customer_id","customers.id")
            ->selectRaw("customers.name customer_name")
        ->leftJoin("shops","owner_fee_details.shop_id","shops.id")
            ->selectRaw("shops.name shop_name")
        ->leftJoin("logistics","owner_fee_details.logistic_id","logistics.id")
            ->selectRaw("logistics.name logistic_name");
        return $query->sql();
    }

    public function create(array $params)
    {
        return OwnerFeeDetail::query()->create($params);
    }

    public function first(array $params)
    {
        $query = OwnerFeeDetail::query();
        foreach ($params as $column=>$param){
            if (is_array($param))$query->whereIn($column,$param);
            else $query->where($column,$param);
        }
        return $query->first();
    }

    public function updateFind(OwnerFeeDetail $detail, array $values)
    {
        return $detail->update($values);
    }

}
