<?php

/**
 * Pj品牌服务类[我还有点没明白为啥不把车品、商品品牌、pj品牌放一起，然后对品牌分个类]
 *
 * @author lixiaolin
 * @Date: 2021/7/23
 * @Time: 18:56
 * @Email: lixiaolin@bluearp.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Inc\CacheInc;
use App\Models\ServiceTypes;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class ServiceTypesService extends Service
{
    public static $instance;
    public $modelMain = null;

    public function __construct()
    {
        if (!$this->modelMain) $this->modelMain = new ServiceTypes();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 获取pj品牌数据
     *
     * @param array $typeIDs
     *
     * @return mixed $data
     */
    public static function getAll(array $typeIDs = []) {
        $data = [];
        $cacheExist = Cache::has('service_types');
        if ($cacheExist) { //防止缓存穿透
            $itemList = Cache::get('service_types');
            foreach ($itemList as $key=>$val) {
                if ($typeIDs && in_array($val['id'], $typeIDs)) {
                    $data[$val['id']] = $val;
                }
            }
        } else {
            $itemList = [];
            $itemData = (new ServiceTypes())
                ->select('id','type_name','com_id')
                ->get()
                ->toArray();
            foreach ($itemData as $key=>$val) {
                if ($typeIDs && in_array($val['id'], $typeIDs)) {
                    $data[$val['id']] = $val;
                }
                $itemList[$val['id']] = $val;
            }
            Cache::set('service_types', $itemList, CacheInc::CACHE_TIME+rand(0, 10)); //防止缓存雪崩
        }

        return !empty($typeIDs) ? $data: $itemList;
    }

    /**
     * 获取某个brand
     *
     * @param int $ID
     *
     * @return mixed
     */
    public static function getByID(int $ID) {
        $cacheExist = Cache::has('service_types');
        $data = [];
        if ($cacheExist) { //防止缓存穿透
            $itemList = Cache::get('service_types');
            foreach ($itemList as $key=>$val) {
                if ($val['id'] = $ID) {
                    return $val;
                }
            }
        } else {
            $itemList = [];
            $itemData = (new ServiceTypes())
                ->select('id','type_name','com_id')
                ->get()
                ->toArray();
            foreach ($itemData as $key=>$val) {
                if ($val['id'] = $ID) {
                    $data = $val;
                }
                $itemList[$val['id']] = $val;
            }
            Cache::set('service_types', $itemList, CacheInc::CACHE_TIME+rand(0, 10)); //防止缓存雪崩
        }

        return $data;
    }

}
