<?php

namespace App\Services;

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


class OwnerReportService
{
    use ServiceAppAop;
    protected $modelClass=OwnerReport::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["owner_group_id"] ?? false){
            $builder->whereHas('owner',function ($query)use(&$params){
                /** @var Builder $query */
                $query->where("user_owner_group_id",$params["owner_group_id"]);
            });
            unset($params["owner_group_id"]);
        }
        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"]);
        }
        if ($params["status"] ?? false){
            $builder->whereHas('owner',function ($query)use(&$params){
                /** @var Builder $query */
                if ($params["status"] == "激活") $query->whereNull("deleted_at");
                else $query->whereNotNull("deleted_at");
            });
            unset($params["status"]);
        }
        return app(QueryService::class)->query($params, $builder, $columnQueryRules,"owner_reports");
    }

    public function get(array $params, array $withs = null)
    {
        $query = OwnerReport::query();
        if ($withs)$query->with($withs);
        return $this->query($query,$params)->get();
    }

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

}
