/**
 * Project Name:tuia-youtui-web<br>
 * File Name:ActivityEngineServiceImpl.java<br>
 * Package Name:com.duiba.tuia.youtui.web.service.impl<br>
 * Date:2017年4月14日上午11:56:39<br>
 * Copyright (c) 2017, duiba.com.cn All Rights Reserved.<br>
 */

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

import cn.com.duiba.tuia.ssp.center.api.dto.RspActivityCenterDto;
import cn.com.duiba.tuia.ssp.center.api.remote.RemoteActivityCenterService;
import cn.com.duiba.tuia.ssp.center.api.remote.RemoteActivitySortService;
import cn.com.duiba.tuia.ssp.center.api.remote.RemoteMediaActivitySlotStatisticsHourService;
import cn.com.duiba.tuia.ssp.center.api.remote.RemoteTuiaActivityService;
import cn.com.duiba.wolf.dubbo.DubboResult;
import cn.com.duiba.wolf.utils.DateUtils;
import com.duiba.tuia.youtui.web.constant.CacheKey;
import com.duiba.tuia.youtui.web.constant.ErrorCode;
import com.duiba.tuia.youtui.web.exception.ActivityException;
import com.duiba.tuia.youtui.web.service.ActivityEngineService;
import com.duiba.tuia.youtui.web.service.BaseCacheService;
import com.duiba.tuia.youtui.web.tool.CachedKeyUtils;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: ActivityEngineServiceImpl <br/>
 * date: 2017年4月14日 上午11:56:39 <br/>
 * .
 *
 * @author youhaijun
 * @since JDK 1.7
 */
@Service
public class ActivityEngineServiceImpl extends BaseCacheService implements ActivityEngineService {

    private LoadingCache<String, List<Long>> slotIdCanUseActIdListCache = CacheBuilder
            .newBuilder().maximumSize(10)
            .refreshAfterWrite(30, TimeUnit.SECONDS) // 缓存10s刷新一次(load不到新数据时仍返回就数据)
            .expireAfterWrite(5, TimeUnit.MINUTES) // 缓存10分钟强制刷新一次
            .build(new CacheLoader<String, List<Long>>() {
                @Override
                public List<Long> load(String key) {
                    return null;
                }
            });

    /**
     * The remote activity sort service.
     */
    @Autowired
    private RemoteActivitySortService remoteActivitySortService;

    @Autowired
    private RemoteActivityCenterService remoteActivityCenterService;

    @Autowired
    private RemoteMediaActivitySlotStatisticsHourService remoteMediaActivitySlotStatisticsHourService;

    @Autowired
    private RemoteTuiaActivityService remoteTuiaActivityService;

    /**
     * Gets the ids by spm.
     *
     * @return the ids by spm
     * @throws ActivityException the activity exception
     */
    @Override
    public List<Long> getIdsBySpm(Long slotId) throws ActivityException {

        // 1.从tuia-engine-activity活动推荐的活动id列表,<=20个
        DubboResult<List<Long>> idResult = remoteActivitySortService.getActivityIdForCenter(slotId);
        if (!idResult.isSuccess() || idResult.getResult().isEmpty()) {
            logger.warn("[Tuia-Activity]remoteActivitySortBackendService.getActivityIdForCenter happen error, because of reuqest param = {} and result =[{}]",
                    slotId, idResult.getMsg());
            throw new ActivityException(ErrorCode.E0900001);
        }
        return idResult.getResult();
    }

    /**
     * Gets the new ids.
     *
     * @return the new ids
     * @throws ActivityException the activity exception
     */
    @Override
    public List<Long> getNewIds(Integer source, Long slotId) throws ActivityException {
        // 1.从tuia-engine-activity活动推荐的活动id列表(按照推广计划id倒序)<=20个
        DubboResult<List<Long>> idResult = remoteActivitySortService.getActivityBySource(source, slotId);
        if (!idResult.isSuccess()) {
            logger.warn("[Tuia-Activity]remoteActivitySortBackendService.getActivityBySource happen error, because of reuqest param = {} and result =[{}]",
                    slotId, idResult.getMsg());
            throw new ActivityException(ErrorCode.E0900001);
        }
        return idResult.getResult();
    }

    @Override
    public List<Long> getCanUseActIds(List<Long> actIds, Long slotId) {
        return remoteActivityCenterService.getCanUseActIds(actIds, slotId);
    }


    @Override
    public List<RspActivityCenterDto> getActCenterList(Long slotId) throws ActivityException {
        DubboResult<List<RspActivityCenterDto>> listDubboResult = remoteActivityCenterService.selectAllLists(slotId);
        if (!listDubboResult.isSuccess() || listDubboResult.getResult().isEmpty()) {
            throw new ActivityException(ErrorCode.E0400014);
        }
        return listDubboResult.getResult();
    }

    @Override
    public int getAppEarn(Long appId) {
        return advancedCacheClient.getWithCacheLoader(CachedKeyUtils.getRedisKey(CacheKey.APP_EARN_KEY, appId),
                getRestSecondsToday(), TimeUnit.SECONDS, () -> {
                    DubboResult<Long> result = remoteMediaActivitySlotStatisticsHourService.selectAppEarnByDate(appId, DateUtils.getStartTime(new DateTime().dayOfMonth().addToCopy(-1).toDate()), DateUtils.getStartTime(new DateTime().toDate()));
                    if (result.isSuccess() && null != result.getResult()) {
                        return result.getResult().intValue();
                    }
                    return 0;
                });


    }

    @Override
    public List<Long> getActivityByUVLaunch(Long slotId) throws ActivityException {
        DubboResult<List<Long>> result = remoteTuiaActivityService.getActivityByUVLaunch(slotId);
        if (!result.isSuccess()) {
            logger.warn("[Tuia-Activity]remoteTuiaActivityService.getActivityByUVLaunch happen error, because of reuqest param = {} and result =[{}]",
                    slotId, result.getMsg());
            throw new ActivityException(ErrorCode.E0900001);
        }
        return result.getResult();
    }

    @Override
    public List<Long> getAvailMainMeet(Long slotId) throws ActivityException {
        DubboResult<List<Long>> result = remoteActivityCenterService.getAvilPlanListBySource(slotId, 2);
        if (!result.isSuccess() || result.getResult().isEmpty()) {
            logger.warn("[Tuia-Activity]remoteActivityCenterService.getAvilPlanListBySource happen error, because of reuqest param = {} and result =[{}]",
                    slotId, result.getMsg());
            throw new ActivityException(ErrorCode.E0900001);
        }
        return result.getResult();
    }

    @Override
    public List<Long> getDirectedAppByAct(Long activityId){
        DubboResult<List<Long>> result = remoteActivityCenterService.getDirectedAppByAct(activityId, 1);
        return result.getResult();
    }

    @Override
    public List<Long> getSpeApp(){
        DubboResult<List<Long>> result = remoteActivityCenterService.getSpeApp();
        return result.getResult();
    }

}
