/**
 * Project Name:tuia-youtui-web<br>
 * File Name:LuckBagServiceImpl.java<br>
 * Package Name:com.duiba.tuia.youtui.web.service.impl<br>
 * Date:2017年1月23日下午4:08:28<br>
 * Copyright (c) 2017, duiba.com.cn All Rights Reserved.<br>
 */

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

import cn.com.duiba.tuia.activity.center.api.dto.ActivityType;
import cn.com.duiba.wolf.utils.BeanUtils;
import cn.com.tuia.advert.model.ObtainAdvertReq;
import cn.com.tuia.advert.model.ObtainAdvertRsp;
import cn.com.tuia.advert.model.QueryAdvertReq;
import cn.com.tuia.advert.model.QueryAdvertRsp;
import cn.com.tuia.advert.service.IEngineService;
import com.alibaba.fastjson.JSONObject;
import com.duiba.tuia.youtui.web.constant.CacheKey;
import com.duiba.tuia.youtui.web.constant.Constants;
import com.duiba.tuia.youtui.web.model.req.DoJoinActivityReq;
import com.duiba.tuia.youtui.web.service.BaseCacheService;
import com.duiba.tuia.youtui.web.service.LuckBagService;
import com.duiba.tuia.youtui.web.tool.CachedKeyUtils;
import com.duiba.tuia.youtui.web.tool.RequestTool;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: LuckBagServiceImpl <br/>
 * Function: 福袋. <br/>
 * date: 2017年1月23日 下午4:08:28 <br/>
 *
 * @author leiliang
 * @version
 * @since JDK 1.6
 */
@Service
public class LuckBagServiceImpl extends BaseCacheService implements LuckBagService {

    @Autowired
    private IEngineService iEngineService;
    @Autowired
    private DirectPageSourceServiceImpl directPageSourceService;

    @Override
    public QueryAdvertRsp queryAdvert(Long consumerId, String orderId, Integer showType, Long slotId) {

        String orderId4Engine = Constants.THE_PREFIX_ORDERID + orderId;
        Object object = advancedCacheClient.get(CachedKeyUtils.getRedisKey(CacheKey.ADVERT_LUCKY_KEY, orderId4Engine));
        if (null != object) {
            return BeanUtils.copy(object, QueryAdvertRsp.class);
        }
        try {
            QueryAdvertReq req = new QueryAdvertReq();
            req.setConsumerId(consumerId);
            req.setOrderId(orderId4Engine);
            req.setShowType(showType);
            req.setSlotId(slotId);
            QueryAdvertRsp advertRsp = iEngineService.queryAdvert(req);
            if (null == advertRsp || !advertRsp.isResult()) {
                return null;
            }
            return advertRsp;
        } catch (Exception e) {
            logger.warn("获取福袋失败", e);
            return null;
        }
    }

    @Override
    public ObtainAdvertRsp obtainAdvert(DoJoinActivityReq doJoinReq, String activityTag, String orderId, Long advertId) {
        ObtainAdvertReq obtain = new ObtainAdvertReq();
        obtain.setConsumerId(doJoinReq.getConsumerId());
        obtain.setUa(RequestTool.getUA(doJoinReq.getUserAgent()));
        obtain.setOrderId(orderId);
        obtain.setIp(doJoinReq.getIp());
        obtain.setAppId(doJoinReq.getAppId());
        obtain.setActivityId(doJoinReq.getActivityId());
        obtain.setTimestamp(new Date().getTime());
        obtain.setTag(activityTag);
        obtain.setAdvertId(advertId);

        // 活动使用类型，0：普通活动，1：兑吧商业化活动 2：推啊商业活动
        obtain.setActivityUseType(2);

        obtain.setSlotId(doJoinReq.getSlotId());
        // 设备id
        obtain.setDeviceId(doJoinReq.getDeviceId());
        // os
        obtain.setOs(doJoinReq.getOs());
        // 点击：0，曝光：1，请求：2，发券：3，计费：4
        obtain.setType("2");
        // 用户ua
        obtain.setUserAgent(doJoinReq.getUserAgent());
        // 推啊活动id
        obtain.setDuibaActivityId(doJoinReq.getActivityId());
        // 推啊活动大类型
        obtain.setDuibaActivityType(ActivityType.isPlugin(doJoinReq.getActivityType()) ? Constants.PLUGIN_TOOLS_TYPE : doJoinReq.getActivityType());
        // 推啊活动大类型
        obtain.setActivityType(ActivityType.isPlugin(doJoinReq.getActivityType()) ? 1  : 0);

        Long directPage = directPageSourceService.get(doJoinReq.getConsumerId());
        Map<String, String> paramMap = doJoinReq.getParamMap();
        if(directPage!=null){
            if(paramMap==null){
                paramMap= Maps.newHashMap();
                doJoinReq.setParamMap(paramMap);
            }
            paramMap.put("directpage",String.valueOf(directPage));
        }
        //发券日志
        obtain.setLogExtMap(doJoinReq.getParamMap());

        try {
            ObtainAdvertRsp advert = iEngineService.obtainAdvert(obtain);
            if (null == advert || !advert.isResult()) {
                logger.info("the obtainAdvert is null");
                return null;
            } else {
                // 获取福袋后存3秒缓存
                advancedCacheClient.set(CachedKeyUtils.getRedisKey(CacheKey.ADVERT_LUCKY_KEY, orderId), advert,
                                        THREE_SECOND, TimeUnit.SECONDS);
            }
            return advert;
        } catch (Exception e) {
            logger.warn("es submit obtain advert error", e);
            return null;
        }
    }

}
