package com.duiba.tuia.youtui.web.service.impl;

import cn.com.duibaboot.ext.autoconfigure.accesslog.AccessLogFilter;
import com.duiba.tuia.youtui.web.constant.CacheKey;
import com.duiba.tuia.youtui.web.service.DirectPageSourceService;
import com.duiba.tuia.youtui.web.tool.CachedKeyUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 经过直投页时的链路数据获取
 * @see ://cf.dui88.com/pages/viewpage.action?pageId=7683525
 * @author lichao 2018/3/26
 */
@Service
public class DirectPageSourceServiceImpl implements DirectPageSourceService {

    /** redisClient */
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Long get(Long consumerId) {
        if(consumerId==null){
            return null;
        }
        String directPageSourceKey = CachedKeyUtils.getRedisKey(CacheKey.DIRECT_PAGE_SOURCE,consumerId);
        String directPage = stringRedisTemplate.opsForValue().get(directPageSourceKey);
        if(StringUtils.isNotBlank(directPage)){
            return Long.valueOf(directPage);
        }
        return null;
    }

    @Override
    public void put(Long consumerId, Long pageId) {
        String directPageSourceKey = CachedKeyUtils.getRedisKey(CacheKey.DIRECT_PAGE_SOURCE,consumerId);
        if(!stringRedisTemplate.hasKey(directPageSourceKey)){
            //有效时间为2个小时
            stringRedisTemplate.opsForValue().set(directPageSourceKey,
                    String.valueOf(pageId),2, TimeUnit.HOURS);
        }
    }

    @Override
    public void delete(Long consumerId) {
        String directPageSourceKey = CachedKeyUtils.getRedisKey(CacheKey.DIRECT_PAGE_SOURCE,consumerId);
        stringRedisTemplate.delete(directPageSourceKey);
    }

    /**
     * 记录统一访问日志
     *
     * @param consumerId 用户id
     */
    @Override
    public void log(Long consumerId) {
        Long directPage = this.get(consumerId);
        if(directPage!=null){
            AccessLogFilter.putExPair("directpage",directPage);
        }
    }
}
