<?php


namespace JinDouYun\Cache;

use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Factory;

/**
 * 规格缓存
 * Class SpecCache
 * @package JinDouYun\Cache
 */
class SpecCache
{
    /**
     * 企业ID
     * @var
     */
    private $onlineEnterpriseId;

    /**
     * redis
     * @var
     */
    private $cache;

    /**
     * SpecName=>id
     * @var
     */
    private $specNameRelIdKey = 'SpecNameRelId';

    /**
     * SpecCache constructor.
     * @param $enterpriseId
     * @throws \Exception
     */
    public function __construct($enterpriseId)
    {
        $this->onlineEnterpriseId = $enterpriseId;
        $this->cache = Factory::cache('mapping');
    }

    /**
     * SpecName => id
     * @param $specName
     * @param $id
     * @return ResultWrapper
     */
    public function cacheSpecNameRelId($specName, $id)
    { 
        return $this->cache->zadd($this->specNameRelIdKey.'::'.$this->onlineEnterpriseId, $id, $specName);
    }

    /**
     * del
     * @param $id
     * @return mixed
     */
    public function delSpecNameRelId($id)
    {
        return $this->cache->zremrangebyscore($this->specNameRelIdKey.'::'.$this->onlineEnterpriseId, $id,$id);
    }

    /**
     * get id => specName
     * @param $id
     * @return string
     */
    public function getSpecNameById($id)
    {
        $result = $this->cache->zrangebyscore($this->specNameRelIdKey.'::'.$this->onlineEnterpriseId, $id, $id);
        if (!$result) {
            return '';
        }
        return array_shift($result);
    }

    /**
     * get specName => id
     * @param $specName
     * @return int
     */
    public function getIdBySpecName($specName)
    {
        $result = $this->cache->zscore($this->specNameRelIdKey.'::'.$this->onlineEnterpriseId, $specName);
        if (!$result) return 0;
        return $result;
    }

}