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.BookAppDto;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;

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

	/**
	 * 清除某个编辑在某运营下图书应用关联关系
	 * 
	 * @param BookDto
	 */
	public void clearOneBookApp(Long bookId, Long channelId, Long adviserId) {
		if (!(null == bookId || null == channelId || null == adviserId)) {
			String key = BookConstant.BOOK_APP_CACHE+bookId;
			JedisClusterUtils.hdel(key, channelId+"_"+adviserId);
		}
	}
	
	/**
	 * 清除图书与应用关联关系
	 * @param bookId
	 */
	public void clearBookApp(Long bookId) {
		if (null == bookId) {
			String key = BookConstant.BOOK_APP_CACHE+bookId;
			JedisClusterUtils.del(key);
		}
	}
	

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

	/**
	 * 将图书应用关联放入缓存
	 * 
	 * @param bookId
	 * @param bookAppDtos
	 */
	public void setBookAppAssoc(Long bookId, Long channelId, Long adviserId, List<BookAppDto> bookAppDtos) {
		if (bookId == null || channelId == null || null == adviserId || bookAppDtos.isEmpty()) {
			return;
		}
		String key = BookConstant.BOOK_APP_CACHE+bookId;
		JedisClusterUtils.hset(key, channelId+"_"+adviserId, JSONArray.toJSONString(bookAppDtos)) ;
		JedisClusterUtils.expire(key, BookConstant.BOOK_CACHE_ONE_DAY);
	}

}
