<?php
/**
 * 库存cache添加
 * Created by PhpStorm.
 * User: 小威
 * Date: 2020/01/11
 * Time: 16:00
 */

namespace JinDouYun\Cache;

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

class InventoryCache
{
    private $cache;

    private $enterpriseId;

    private $userCenterId;

    private $cacheKey = 'Inventory';

    private $cacheKeyShopLock = 'InventoryLock';


    public function __construct($enterpriseId, $userCenterId = false)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        $this->cache = Factory::cache('mapping');
    }

    /**---------------------------------------------仓库库存------------------------------------------------**/

    /**
     * 添加
     * @param $key
     * @param $value
     * @return ResultWrapper
     */
    public function addCacheHash($key,$value)
    {
        $data = json_encode($value);
        $result = $this->cache->hset($this->cacheKey . '::' . $this->enterpriseId.'::'.$value['warehouseId'], $key, $data);
        if (!$result) {
            return ResultWrapper::fail('error', ErrorCode::$redisWriteError);
        }
        return ResultWrapper::success('success');
    }

    /**
     * 查询
     * @param $skuId
     * @param $warehouseId
     * @param bool $type
     * @return mixed|string
     */
    public function getCacheHash($skuId, $warehouseId, $type = false)
    {
        $result = $this->cache->hget($this->cacheKey.'::'.$this->enterpriseId.'::'.$warehouseId, $skuId);
        if (!$result) return '';
        $returnData = json_decode($result, true);
        if($type){
            return $returnData[$type];
        }
        return $returnData;
    }

    /**
     * 删除
     * @param $skuId
     * @param $warehouseId
     */
    public function delCacheHash($skuId, $warehouseId)
    {
        $this->cache->hdel($this->cacheKey.'::'.$this->enterpriseId.'::'.$warehouseId, $skuId);
    }

    /**---------------------------------------------商铺锁定--有序集合------------------------------------------------**/

    /**
     * 添加
     */
    public function addShopLock($shopId, $skuId, $shopLock)
    {
        $result = $this->cache->zadd($this->cacheKeyShopLock . '::' . $this->enterpriseId.'::'.$shopId, $shopLock, $skuId);
        if($result){
            return true;
        }
        return false;
    }

    /**
     * 查询
     * @param $skuId
     * @param $shopId
     * @param bool $type
     * @return mixed|string
     */
    public function getShopLock($shopId, $skuId)
    {
        return $this->cache->zscore($this->cacheKeyShopLock.'::'.$this->enterpriseId.'::'.$shopId, $skuId);
    }

    /**
     * 删除
     * @param $skuId
     * @param $shopId
     */
    public function delShopLock($skuId, $shopId)
    {
        return $this->cache->zrem($this->cacheKeyShopLock.'::'.$this->enterpriseId.'::'.$shopId, $skuId);
    }

}