<?php
/**
 * 暂存cache
 * Created by PhpStorm.
 * User: 小威
 * Date: 2020/03/30
 * Time: 16:30
 */

namespace JinDouYun\Cache;

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

class PauseSave
{
    private $cache;

    private $enterpriseId;

    private $userCenterId;

    private $cacheBigKey;

    private $pauseSaveTime = '86400';//暂存保存时间

    private static $cacheKey = 'PauseSave';

    private $moneyCacheKey = 'MoneyPauseSave';

    public function __construct($enterpriseId, $userCenterId = false)
    {
        $userCenterId && $this->userCenterId = $userCenterId;
        $enterpriseId && $this->enterpriseId = $enterpriseId;
        $this->cacheBigKey = '';
        if($enterpriseId && $userCenterId){
            $this->cacheBigKey = self::$cacheKey.'::'.$this->enterpriseId . '_' . $this->userCenterId;
            $this->moneyCacheKey = $this->moneyCacheKey.'::'.$this->enterpriseId . '_' . $this->userCenterId;
        }
        $this->cache = Factory::cache('default');
    }

    /**---------------------------------------------哈希hash------------------------------------------------**/

    /**
     * 添加
     * @param $key
     * @param $value
     * @return bool
     */
    public function addCacheHash($key,$value)
    {
        $data = json_encode($value);
        $result = $this->cache->hset($this->cacheBigKey, $key, $data);
        if (!$result) {
            return false;
        }
        return true;
    }

    /**
     * 查询
     * @param $key
     * @return mixed|string
     */
    public function getCacheHash($key)
    {
        $result = $this->cache->hget($this->cacheBigKey, $key);
        if (!$result) return [];
        return json_decode($result, true);
    }

    /**
     * 删除
     * @param $key
     * @return array
     */
    public function delCacheHash($key)
    {
        return $this->cache->hdel($this->cacheBigKey, $key);
    }


    /***********************************价格暂存**************************************/
    /**
     * 添加
     * @param $key
     * @param $array
     * @return bool
     * @throws \Exception
     */
    public function addMoneyCache($array)
    {
        if(empty($array)){
            return false;
        }

        $pipe =  Factory::cache('default')->multi();
        foreach ($array as $key => $value){
            Factory::cache('default')->zadd($this->moneyCacheKey, $value, $key);
        }
        $pipe->exec();

        return true;
    }

    /**
     * 查询
     * @param $key
     * @return mixed|string
     */
    public function getMoneyCache($key)
    {
        $result = $this->cache->zscore($this->moneyCacheKey, $key);
        return $result;
    }
}