<?php

namespace App\Services;

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


class OwnerBillReportService
{
    use ServiceAppAop;
    protected $modelClass=OwnerBillReport::class;

    /**
     * @param Builder $builder
     * @param array $params
     * @return Builder
     */
    private function query(Builder $builder, array $params)
    {
        $columnQueryRules = [
            'counting_month_start' => ['alias' => 'counting_month', 'startDate' => '-01'],
            'counting_month_end' => ['alias' => 'counting_month', 'endDate' => '-31'],
            'owner_id' => ['multi' => ','],
        ];
        if (($params["customer_id"] ?? false) || ($params["owner_group_id"] ?? false)){
            $builder->whereHas('owner',function ($query)use(&$params){
                /** @var Builder $query*/
                if ($params["customer_id"] ?? false){
                    $query->where("customer_id",$params["customer_id"]);
                    unset($params["customer_id"]);
                }
                if ($params["owner_group_id"] ?? false){
                    $query->where("user_owner_group_id",$params["owner_group_id"]);
                    unset($params["owner_group_id"]);
                }
            });
        }
        return app(QueryService::class)->query($params, $builder, $columnQueryRules);
    }

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

    public function update(array $params, array $values)
    {
        return $this->query(OwnerBillReport::query(),$params)->update($values);
    }

    public function get(array $params, array $withs = null)
    {
        $bills = OwnerBillReport::query()->orderByDesc('id');
        if ($withs)$bills->with($withs);
        return $this->query($bills,$params)->get();
    }

    public function first(array $params)
    {
        $query = OwnerBillReport::query();
        foreach ($params as $column=>$param){
            $query->where($column,$param);
        }
        return $query->first();
    }
}
