package com.gic.haoban.manage.service.util;

import com.gic.commons.util.IPUtil;
import com.gic.dubbo.util.DubboInvokeUtil;
import com.gic.haoban.manage.api.service.MemberUnionidRelatedApiService;
import com.gic.haoban.manage.service.pojo.HBQwMonitorBO;
import com.gic.redis.data.util.RedisUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.redisson.api.RAtomicLong;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
/**
 * 好办统计
 */
@Component
public class HBQwMonitorUtils {

    private static Logger logger = LogManager.getLogger(HBQwMonitorUtils.class);

    private static final List<String> keyList = Arrays.asList("hbmonitor:friendNotice","hbmonitor:friendFail") ;

    /**
     * @param index 0加好友企微通知数量 1加好友查询企微接口限制数量
     */
    public static void addForFriend(int index) {
        String ip = IPUtil.getLocalIP();
        logger.info("addForFriend={}",ip);
        String key = keyList.get(index)+ip ;
        RAtomicLong cache = RedisUtil.getRedisClient().getAtomicLong(key);
        cache.addAndGet(1);
    }


    public static Object query(String sql) {
        return InfluxDbMonitorUtils.getInstance().query(sql);
    }

    public static void addByTimer() {
        List<String> ipList = DubboInvokeUtil.getServiceHostList(MemberUnionidRelatedApiService.class) ;
        logger.info("add timer");
        for(String ip : ipList) {
            int totalNum = getNum(keyList.get(0),ip) ;
            int failNum =  getNum(keyList.get(1),ip);
            HBQwMonitorBO bo = new HBQwMonitorBO() ;
            bo.setHost(ip);
            bo.setNum(totalNum);
            bo.setFailNum(failNum);
            InfluxDbMonitorUtils.getInstance().friendAdd(bo);
        }
    }


    private static  int getNum(String key , String ip) {
        key = key+ip ;
        int count = 0 ;
        Object countObj = RedisUtil.getCache(key) ;
        if(null != countObj) {
            count = Integer.valueOf(countObj.toString()) ;
        }
        RAtomicLong cache = RedisUtil.getRedisClient().getAtomicLong(key);
        cache.addAndGet(-count) ;
        return count ;
    }


}
