<?php

namespace App\Domains\Real\Repositories;

use App\Core\Repository;
use App\Models\Real\OrderCardPartition as Model;
use App\Domains\Real\Repositories\Concerns\OrderCardConcern;

class OrderCardPartitionRepository extends Repository
{
    use OrderCardConcern;

    /**
     * 是否关闭缓存
     *
     * @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();
    }

    public function withVirtual($conditions)
    {
        $select = 'distinct on (real_order_cards_partition.id)
            real_order_cards_partition.sim,
            real_order_cards_partition.order_id,
            real_order_cards_partition.virtual_order_id,
            real_order_cards_partition.counts,
            virtual_order_cards_partition.company_id,
            virtual_order_cards_partition.package_id,
            real_order_cards_partition.refunded_at
        ';

        $this->model = $this->model->selectRaw($select);

        $this->model = $this->model->leftJoin('virtual_order_cards_partition', function($join){
            $join->on('virtual_order_cards_partition.sim', '=', 'real_order_cards_partition.sim')
                ->whereNull('virtual_order_cards_partition.deleted_at');
        });

        $this->model= $this->model
            ->orderBy('real_order_cards_partition.id')
            ->orderBy('virtual_order_cards_partition.created_at');

        if (isset($conditions['type'])) {
            $conditions['type'] = array_wrap($conditions['type']);
            $this->model= $this->model->whereIn('real_order_cards_partition.type', $conditions['type']);
        }

        if (isset($conditions['sim'])) {
            $conditions['sim'] = array_wrap($conditions['sim']);
            $this->model= $this->model->whereIn('real_order_cards_partition.sim', $conditions['sim']);
        }

        if (isset($conditions['order_id'])) {
            $conditions['order_id'] = array_wrap($conditions['order_id']);
            $this->model= $this->model->whereIn('real_order_cards_partition.order_id', $conditions['order_id']);
        }

        return $this;
    }
}
