package com.pcloud.book.book.cache;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.pcloud.book.book.constant.BookConstant;
import com.pcloud.book.book.dao.BookResourceDao;
import com.pcloud.book.book.dto.BookResourceDto;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;

/**
 * 描述 :图书应用关联缓存
 * 
 * @author 作者: lili
 * @date 创建时间：2017年6月15日 下午2:48:34
 * @version 1.0
 */
@Component("bookResourceCache")
public class BookResourceCache {
	/**
	 * 
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(BookResourceCache.class);

	@Autowired
	private BookResourceDao bookResourceDao;
	/**
	 *  从缓存中获取图书关联资源文件
	 * @param bookId 图书标识
	 * @param channelId 运营标识
	 * @param adviserId 编辑标识
	 * @return
	 */
	public List<BookResourceDto> listBookResource(Long bookId, Long channelId, Long adviserId) {
		if (!(bookId == null || channelId == null || null == adviserId)) {
			String key = BookConstant.BOOK_RESOURCE_CACHE+bookId+DateUtils.getReqDate();;
			return JSONArray.parseArray(JedisClusterUtils.hget(key, channelId+"_"+adviserId), BookResourceDto.class);
		}
		return null;
	}

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

	/**
	 * 清除图书缓存
	 * @param bookId
	 */
	public void clearBookCache(Long bookId){
		String key = BookConstant.BOOK_RESOURCE_CACHE+bookId+DateUtils.getReqDate();
		JedisClusterUtils.del(key);
	}
	
	/**
	 * 清除图书资源关联缓存
	 * @param bookId
	 * @param channelId
	 * @param adviserId
	 */
	public void clearBookResourceCache(Long bookId,Long channelId,Long adviserId){
		String key = BookConstant.BOOK_RESOURCE_CACHE+bookId+DateUtils.getReqDate();
		JedisClusterUtils.hdel(key, channelId+"_"+adviserId);
	}
	
	/**
	 * 清除图书资源关联
	 * @param bookResourceId
	 */
	public void clearByBookResourceId(Long bookResourceId){
		try{
			BookResourceDto bookResourceDto = bookResourceDao.getByBookResourceId(bookResourceId);
			if(bookResourceDto != null){
				clearBookResourceCache(bookResourceDto.getBookId(),bookResourceDto.getChannelId(),bookResourceDto.getCreatedUser())	;
			}
		}catch(Exception e){
			LOGGER.error("清除图书资源缓存失败bookResourceId"+bookResourceId);
		}
	}
	
}
