<?php

namespace App\Model;

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

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

    public function HDBrandName($BrandID = '', $Redis = '')
    {
        if (empty($BrandID)) {
            return false;
        }
        if (empty($Redis)) {
            $Redis = new RedisModel();
        }
        $BrandName = $Redis->hget('Self_Brand', $BrandID);
        if (!$BrandName) {
            $result = $this->ToRedis($BrandID, $Redis);
            if (!$result) {
                return false;
            }

            return $result['brand_name'];
        } else {
            $BrandName = json_decode($BrandName, true);

            return $BrandName['brand_name'];
        }
    }

    public function ToRedis($BrandID, $Redis = '')
    {
        if (empty($BrandID)) {
            return false;
        }
        if (empty($Redis)) {
            $Redis = new RedisModel;
        }
        if (empty($this->connection)) {
            $this->connection = 'self';
        }
        $Find = $this->where('brand_id', '=', $BrandID)->select('brand_logo', 'brand_id', 'brand_name', 'brand_area',
            'status')->first();
        if (!$Find) {
            return false;
        }
        $Find = $Find->toArray();
        $Redis->hset('Self_Brand', $BrandID, json_encode($Find));

        return $Find;
    }

    //ๅ“็‰Œๅˆ—่กจ
    public function getBrandList()
    {
        $expireMinutes = 5;

        return Cache::remember('brandListsss', $expireMinutes, function () {
            $field = [
                'brand_id',
                'brand_name',
                'brand_logo',
                'create_time',
                'brand_area',
                'brand_brief',
            ];

            return $this->select($field)->where('status', 1)->limit(10)
                ->get()->toArray();
        });
    }
}