<?php


namespace App\Model;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class BrandModel extends Model
{
    protected $connection = 'self';
    public $timestamps = false;
    protected $table = 'brand';

    //获取缓存的二级分类
    public function getBrandList()
    {
        $brandList = Cache::get('cube_brands');
        if (!$brandList) {
            $result = $this->select(['brand_id', 'brand_name', 'brand_logo', 'brand_brief'])
                ->where('status', 1)
                ->get()->toArray();
            Cache::put('cube_brands', $result, 3600);

            return $result;
        }

        return $brandList;
    }

    //根据条件获取自营和联营分类
    public function getBrandListByType($type)
    {
        $redis = new RedisModel();
        $brandList = [];
        //1就是去取自营的品牌列表
        if ($type == 1) {
            $data = $redis->hgetall('Self_Brand');
            foreach ($data as $key => $item) {
                $item = json_decode($item, true);
                if (!$item['brand_id']) {
                    continue;
                }
                $brandList[] = [
                    'brand_id' => $item['brand_id'],
                    'brand_name' => $item['brand_name'],
                ];
            }
        } else {
            $data = DB::connection('spu')->table('brand')->where('status', 1)->orderBy('brand_id',
                'asc')->pluck('brand_name', 'brand_id');
            foreach ($data as $brandId => $brandName) {
                if (!$brandId) {
                    continue;
                }
                $brandList[] = [
                    'brand_id' => $brandId,
                    'brand_name' => trim($brandName),
                ];
            }
        }
        return $brandList;
    }

    public function getStandardBrandList()
    {
        $redis = new RedisModel();
        $standardBrands = json_decode($redis->get('standard_brands_for_supplier'),true);
        if (empty($standardBrands)) {
            $standardBrandModel = new StandardBrandModel();
            $standardBrands = $standardBrandModel->selectRaw('brand_name,standard_brand_id as brand_id')
                ->where('status', 1)->get()->toArray();
            $redis->set('standard_brands_for_supplier', json_encode($standardBrands));
            $redis->expire('standard_brands_for_supplier', 600);
        }

        return $standardBrands;
    }
}