package com.pcloud.book.book.cache;

import java.util.List;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.pcloud.book.book.constant.BookConstant;
import com.pcloud.book.book.dto.BookProductDto;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;

/**
 * 描述 :图书应用关联缓存
 * 
 * @author 作者: lili
 * @date 创建时间：2017年6月15日 下午2:48:34
 * @version 1.0
 */
@Component("bookProductCache")
public class BookProductCache {

	/**
	 * 清除某个编辑在某运营下图书商品关联关系
	 * 
	 * @param bookId
	 *            图书标识
	 * @param channelId
	 *            运营标识
	 * @param adviserId
	 *            编辑标识
	 */
	public void clearOneBookProduct(Long bookId, Long channelId, Long adviserId) {
		if (!(null == bookId || null == channelId || null == adviserId)) {
			String key = BookConstant.BOOK_PRODUCT_CACHE + bookId;
			JedisClusterUtils.hdel(key, channelId + "_" + adviserId);
		}
	}

	/**
	 * 清除图书与商品关联关系
	 * 
	 * @param bookId
	 *            图书标识
	 */
	public void clearBookProduct(Long bookId) {
		if (null == bookId) {
			String key = BookConstant.BOOK_PRODUCT_CACHE + bookId;
			JedisClusterUtils.del(key);
		}
	}

	/**
	 * 从缓存中获取图书商品关联数据
	 * 
	 * @param bookId
	 *            图书标识
	 * @return
	 */
	public List<BookProductDto> listBookProductAssoc(Long bookId, Long channelId, Long adviserId) {
		if (!(bookId == null || channelId == null || null == adviserId)) {
			String key = BookConstant.BOOK_PRODUCT_CACHE + bookId;
			return JSONArray.parseArray(JedisClusterUtils.hget(key, channelId + "_" + adviserId), BookProductDto.class);
		}
		return null;
	}

	/**
	 * 将图书商品关联放入缓存
	 * 
	 * @param bookId
	 *            图书标识
	 * @param channelId
	 *            运营标识
	 * @param adviserId
	 *            编辑标识
	 * @param bookProductDtos
	 */
	public void setBookProductAssoc(Long bookId, Long channelId, Long adviserId, List<BookProductDto> bookProductDtos) {
		if (bookId == null || channelId == null || null == adviserId || bookProductDtos.isEmpty()) {
			return;
		}
		String key = BookConstant.BOOK_PRODUCT_CACHE + bookId;
		JedisClusterUtils.hset(key, channelId + "_" + adviserId, JSONArray.toJSONString(bookProductDtos));
		JedisClusterUtils.expire(key, BookConstant.BOOK_CACHE_ONE_DAY);
	}

}
