package com.cftech.activity.oil.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.activity.log.model.OilLog;
import com.cftech.activity.oil.model.Config;
import com.cftech.activity.oil.model.Oil;
import com.cftech.core.util.StringUtils;
import com.cftech.module.activity.core.service.ActivityBaseResultService;
import com.cftech.module.activity.core.utils.ActivityKeys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by liuling on 2017/4/18.
 */
@Slf4j
@Component
public class OilActivityRedisAPI {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ActivityBaseResultService resultService;

    private Random random;


    protected long timeGen() {
        return System.currentTimeMillis();
    }

    public RedisTemplate getRedis(){
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        //redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        return redisTemplate;
    }
    /**
     * 活动的redisKey前缀
     * ACTIVITY:账号Id:活动类名:活动的Id:
     *
     * @param t 活动对象
     * @return
     */
    public String redisKeyPrefix(Oil t,OilLog oilLog) {
        return "ACTIVITY:" + t.getAccountsId() + ":" + t.getClass().getSimpleName() + ":" + t.getId()+":"+oilLog.getType()+":"+ oilLog.getOpenId();
    }


    public JSONObject play(String openId, Oil t, OilLog oilLog, Config config) {

        String keys = redisKeyPrefix(t,oilLog);
        JSONObject retObj = new JSONObject();
        //机油大转盘不需要校验活动是否开启状态 默认全部为开启
       /* if (!t.getStatus().equals("1")) {
            log.info("活动:{}, 活动名称:{} 活动不在开启状态", t.getClass().getSimpleName(), t.getTitle());
            retObj.put("errorNo","1");
            retObj.put("errorMsg","活动不在开启状态");
            return retObj;
        }*/
        //与现有时间比较，是否在活动期间内
        Date now = new Date();
        if (now.compareTo(t.getStartTime()) == -1 || now.compareTo(t.getEndTime()) == 1) {
            //时间小于开始时间或者大于结束时间
            log.error("活动:{}, 活动名称:{} 不能play，因为不在活动期间内 {} - {}", new Object[]{t.getClass().getSimpleName(), t.getTitle(), t.getStartTime().toString(), t.getEndTime().toString()});
            retObj.put("errorNo","1");
            retObj.put("errorMsg","不在活动期间内");
            return retObj;
        }
        String prizeCode = config.getNumber();
        String prizeStr=t.getPrizes();
        String prizeName="";
        String prizeDetail="";
        if(StringUtils.isNotBlank(prizeStr)){
            JSONArray prizeArr=JSONArray.parseArray(prizeStr);
            for(int i=0,j=prizeArr.size();i<j;i++){
                JSONObject obj=prizeArr.getJSONObject(i);
                String prizeNumber=obj.getString("code");
                if(prizeCode.equals(prizeNumber)){
                    prizeName=obj.getString("name");
                    prizeDetail=obj.getString("amount");
                }
            }
        }

        String prizeInvKey = keys.concat(":").concat(prizeCode);
        //增加中奖标记(根据类型)
               long leftInventoryQty = getRedis().opsForValue().increment(prizeInvKey, 1);
        if (leftInventoryQty > 1) {
            log.info("活动:{}, 活动名称:{}，奖品:{} 库存为0", new Object[]{t.getClass().getSimpleName(), t.getTitle(), prizeName});
            retObj.put("errorNo","1");
            retObj.put("errorMsg","无抽奖机会");
            return retObj;
        }
        // 记录用户中奖记录
        resultService.prizeLog(t.getAccountsId(), t.getClass().getSimpleName(), t.getId(), t.getTitle(), openId, prizeName, 1, prizeDetail, prizeDetail, config.getCount(),null);
        retObj.put("errorNo","0");
        retObj.put("data",prizeCode);

        log.info("活动:{}, 活动名称:{}，用户:{} 中奖，奖品为{}", new Object[]{t.getClass().getSimpleName(), t.getTitle(), openId, prizeName});
        return retObj;
    }

}
