<?php
/**
 * 购物车缓存
 * Created by PhpStorm.
 * User: XiaoMing
 * Date: 2019/11/7
 * Time: 15:16
 */

namespace JinDouYun\Cache;

use Mall\Framework\Factory;

class CartCache
{
    private $cache;

    private $enterpriseId; //当前企业id

    private static $cartTable;//缓存购物车

    /**
     * CartCache constructor.
     * @param string $cacheDb
     * @param $enterpriseId
     * @throws \Exception
     */
    public function __construct($enterpriseId, $cacheDb = 'mapping')
    {
        $this->enterpriseId = $enterpriseId;
        self::$cartTable = 'cartTable' . '::' . $this->enterpriseId;
        $this->cache = Factory::cache($cacheDb);
    }

    /**
     * 购物车数据缓存
     * @param $params
     * @param $userId
     * @return mixed
     */
    public function cacheCartTable($params, $userId)
    {
        //$data = gzcompress(json_encode($params));
        $data = json_encode($params);//测试时用这个
        $result = $this->cache->hset(self::$cartTable, $userId, $data);
        return $result;
    }

    /**
     * 获取用户购物车数据
     * @param $userId
     * @return array|mixed
     */
    public function getCart($userId)
    {
        $result = $this->cache->hget(self::$cartTable,$userId);
        if (!$result) {
            return [];
        }
        if (!empty($result)){
            $result = json_decode($result, true);
        }
        return $result;
    }

    /**
     * 清空用户购物车
     * @param $userId
     * @return mixed
     */
    public function clearCart($userId)
    {
        $result = $this->cache->hdel(self::$cartTable,$userId);
        return $result;
    }
}