<?php

namespace App\Domains\Virtual\Repositories;

use Carbon\Carbon;
use App\Core\Repository;
use App\Models\Virtual\FlowPool as Model;

class FlowPoolRepository extends Repository
{
    /**
     * 是否关闭缓存
     *
     * @var boolean
     */
    protected $cacheSkip = false;

    /**
     * 是否开启数据转化
     *
     * @var bool
     */
    protected $needTransform = false;

    /**
     * @var array
     */
    protected $fieldSearchable = [
        'id'         => '=',
        'created_at' => 'like',
    ];

    public function model()
    {
        return Model::class;
    }

    /**
     * 数据格式化
     *
     * @param mixed $result
     *
     * @return mixed
     */
    public function transform($model)
    {
        return $model->toArray();
    }

    /**
     * 查询条件
     *
     * @return void
     */
    public function withConditions(array $conditions = [])
    {
        if (isset($conditions['id'])) {
            $conditions['id'] = array_wrap($conditions['id']);
            $this->model = $this->model->whereIn('id', $conditions['id']);
        }

        if (isset($conditions['carrier_operator'])) {
            $this->model = $this->model->where('carrier_operator', $conditions['carrier_operator']);
        }

        if (!empty($conditions['name'])) {
            $this->model = $this->model->where('name', 'like', "%{$conditions['name']}%");
        }

        if (!empty($conditions['company_name'])) {
            $this->model = $this->model->whereHas('company', function ($relation) use ($conditions) {
                $relation->withTrashed()->where('name', $conditions['company_name']);
            });
        }

        if (isset($conditions['month'])) {
            $time = Carbon::parse($conditions['month'])->format('Y-m-d H:i:s');
            $this->model = $this->model->where(function ($subQuery) use ($time) {
                $subQuery->where('start_at', '<=', $time)->where(function ($endAtQuery) use ($time) {
                    $endAtQuery->where('end_at', '>=', $time)->orWhereNull('end_at');
                });
            });
        }

        return $this;
    }
}
