package com.sys.util;

import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.util.DateUtils;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * ip每日限额工具类
 *
 * @author fanhuibin
 */
@Component
public class IPLimitUtil {
    private static final String CACHE_NAME = "IPCache";
    private static final Logger logger = Logger.getLogger(IPLimitUtil.class);
    
    @Autowired
    private CacheUtils cacheUtils;

    /**
     * 查询是否满足ip限额
     *
     * @param key
     * @param request
     * @param count   允许的次数
     * @return
     */
    public void CheckLimit(String key, HttpServletRequest request, int count) throws ZAException {
        String ip = getIpAddr(request);
        CheckLimit(key, ip, count);
    }

    public void CheckLimit(String key, String ip, int count) throws ZAException {
    	logger.info("key="+key+" ip="+ip+" count="+count);
        key = ip + key;
        logger.info("key="+key);
        Integer currentCount = (Integer) cacheUtils.get(CACHE_NAME, key);
        logger.info("currentCount="+currentCount);
        String date = (String) cacheUtils.get(CACHE_NAME, key + "-date");
        logger.info("date="+date);
        String cDate = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        logger.info("cDate="+cDate);
        logger.info(date != null && date.equals(cDate));
        if (date != null && date.equals(cDate)) {
            if (currentCount <= count) {
                currentCount += 1;
                cacheUtils.put(CACHE_NAME, key, currentCount);
            } else {
                throw new ZAException(ZAErrorCode.ZA_ERC_UNKNOWN,"该接口的访问已经达到了ip限制，请明天再访问");
            }
        } else {
        	cacheUtils.put(CACHE_NAME, key, 1);
        	cacheUtils.put(CACHE_NAME, key + "-date", cDate);
        }
    }

    public  String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        // ipAddress = request.getRemoteAddr();
        ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0
                || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0
                || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0
                || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }

        }

        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
            // = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
}