package com.wechat.dao;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import com.wechat.common.Constants;
import com.wechat.common.utils.DateUtils;
import com.wechat.common.utils.StringsUtils;



/**
 * @author jadyn.wu
 * @date: 2020-04-21 18:08
 */
@Repository
public class JobPvRedisDao {
	//PV/UV记录失效时间(一周 7天 )
	@Value("#{configProperties['pvuv.expired.days']}")
	private Integer expiredDays;
	
	@Autowired
	protected RedisTemplate<String, Integer> redisTemplate;

    
    //职位详情pv统计
    public void insertJobDtlPv(String id) {
    	//按日期统计
        String pvKey = DateUtils.getLocalDateNowStr(DateUtils.PATTEN_YMD)+Constants.UNDER_LINE;
    	if(!StringsUtils.isEmpty(id))
    	{
    		String key = Constants.REDIS_JOB_PV + pvKey+id;
        	if(hasKey(key))
        	{
        		insert(key, select(key)+1);
        	} else {
        		insertDay(key, 1 ,expiredDays);
        	}
    	}
    }
    
    //根据职位id获取pv
    public int getJobPvById(Integer id) {
    	int pvNum = 0;
    	//按日期统计
        String pvKey = DateUtils.getLocalDateNowStr(DateUtils.PATTEN_YMD)+Constants.UNDER_LINE;
    	if(null != id &&  id != 0)
    	{
    		String key = Constants.REDIS_JOB_PV + pvKey+id.toString();
        	if(hasKey(key))
        	{
        		Integer pv = select(key);
        		pvNum = pv != null ? pv.intValue()+1 : 1;
        	} 
    	}
    	return pvNum;
    }

	public Integer select(String infoKey) {
		return redisTemplate.opsForValue().get(infoKey);
	}

	private void insert(String infoKey, Integer infoValue) {
		redisTemplate.opsForValue().set(infoKey, infoValue);
	}

	/**
	 * 保存并设置过期时间
	 * @param infoKey
	 * @param infoValue
	 * @param expiry    过期时长
	 * @param unit      单位
	 */
	private void insertAndExptime(String infoKey, Integer infoValue, int expiryNum, TimeUnit unit) {
		redisTemplate.opsForValue().set(infoKey, infoValue);
		// 设置失效时间
		redisTemplate.expire(infoKey, expiryNum, unit);
	}
	
	/**
	 * 
	 * @param infoKey
	 * @param infoValue
	 * @param expiry 过期时长 单位：天
	 */
	private void insertDay(String infoKey, Integer infoValue, int expired) {
		// 设置失效时间
		insertAndExptime(infoKey, infoValue, expired, TimeUnit.DAYS);
	}
	


	public void delete(String infoKey) {
		redisTemplate.delete(infoKey);
	}
	
   public Boolean hasKey(String infoKey) {
       return redisTemplate.hasKey(infoKey);
    }

}
