package com.liquidnet.service.chime.utils;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.chime.constant.ChimeConstant;
import com.liquidnet.service.chime.dto.ChimeUserDoTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;

import java.time.LocalDateTime;
import java.util.Calendar;

@Slf4j
@Component
public class DoTaskUtils {
    @Autowired
    private RedisUtil redisUtil;
    @Value("${liquidnet.service.stone.url}")
    private String stoneUrl;

    /**
     * 划卡调任务
     *
     * @param currentUserId
     */
    public void userAddNum(String currentUserId) {
        long timeout = ((24 * 60 * 60) - LocalDateTime.now().getSecond());
        Object obj = redisUtil.get(ChimeConstant.REDIS_USER_OPEN_NUM + currentUserId);
        int slidCount ;
        //判断当天是否有划卡
        if (obj==null) {
            slidCount = 1;
        } else {
            slidCount = (int)obj;
            slidCount = slidCount + 1;
        }
        redisUtil.set(ChimeConstant.REDIS_USER_OPEN_NUM + currentUserId, slidCount, timeout);

        //获取用户是否调用过任务接口
        Object taskObj = redisUtil.get(ChimeConstant.REDIS_USER_TO_DOTASK + currentUserId);
        if (taskObj == null){
            //满足10次调用接口，每天最多调用一次
            if (slidCount >= 10) {
                try {
                    MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                    params.add("uid", currentUserId);
                    params.add("taskId", 3 + "");
                    String resultData = HttpUtil.post(stoneUrl + "/user/inner/doTask", params);
                    redisUtil.set(ChimeConstant.REDIS_USER_TO_DOTASK + currentUserId, 1, timeout);
                }catch (Exception e){
                    log.error("任务接口调用失败currentUserId:"+currentUserId,e);
                }
            }
        }
    }
}
