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

import cn.com.duiba.tuia.activity.center.api.dto.ContactPlateDto;
import cn.com.duiba.tuia.activity.center.api.remoteservice.RemoteContactPlateService;
import com.duiba.tuia.youtui.web.exception.ActivityException;
import com.duiba.tuia.youtui.web.log.InnerLogService;
import com.duiba.tuia.youtui.web.service.BaseService;
import com.duiba.tuia.youtui.web.service.ContactPlateService;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 客服信息模版
 * <p>
 * Created by xuefeng on 2017/11/29.
 */
@Service
public class ContactPlateServiceImpl extends BaseService implements ContactPlateService, InitializingBean {

    @Autowired
    private RemoteContactPlateService remoteContactPlateService;

    private LoadingCache<String, ContactPlateDto> contactPlateCache;

    @Override
    public void afterPropertiesSet() throws Exception {
        contactPlateCache = CacheBuilder
                .newBuilder()
                .maximumSize(100)
                .refreshAfterWrite(1, TimeUnit.MINUTES)//缓存1分钟刷新一次(load不到新数据时仍返回就数据)
                .expireAfterWrite(10, TimeUnit.MINUTES)//缓存10分钟强制刷新一次
                .build(new CacheLoader<String, ContactPlateDto>() {
                    @Override
                    public ContactPlateDto load(String key) throws Exception {
                        return remoteContactPlateService.getDtoByHost(key);
                    }
                });
    }

    /**
     * 根据域名查询客服模版信息
     *
     * @param host
     * @return
     */
    @Override
    public ContactPlateDto getDtoByHost(String host) throws ActivityException {
        try {
            ContactPlateDto dto =  contactPlateCache.get(host);
            InnerLogService.contactPlateLog(host, dto == null ? 0 : dto.getId());
            return dto;
        } catch (Exception e) {
            throw new ActivityException(e);
        }
    }
}
