package com.chenyang.nse.bussiness.jar.util;

import com.chenyang.nse.bussiness.jar.db.ServerClientSocketLogDao;
import com.chenyang.nse.bussiness.jar.db.TCoreClientInfo;
import com.chenyang.nse.bussiness.jar.db.TCoreClientInfoDao;
import com.chenyang.nse.bussiness.jar.db.TCoreClientIpControlledDao;
import com.chenyang.nse.bussiness.tools.spring.SpringUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.util.StringUtils;

public class JarClientUtil {
   private static final Logger log = LoggerFactory.getLogger(JarClientUtil.class);
   private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   private static final String PROJECTID_KEY = "projectId";
   public static final String REMOTE_PORT_KEY = "remotePort";
   private static final String DEFAULT_OPT_TIME = "";
   private static final char DEFAULT_IS_CONTROLLED = '1';
   private static final char DEFAULT_CLIENT_STATUS = '1';

   public static void registOrUpt(HttpServletRequest request) {
      Map<String, String> requestParamsMap = getRequestParamsMap(request);
      String projectId = (String)requestParamsMap.get("projectId");
      String remoteHost = request.getRemoteHost();
      int remotePort = Integer.parseInt((String)requestParamsMap.get("remotePort"));
      TCoreClientInfo clientInfo = getClientInfo(remoteHost, remotePort, projectId);
      if (clientInfo == null) {
         clientInfo = new TCoreClientInfo();
         clientInfo.setClient_ip(remoteHost);
         clientInfo.setClient_port(remotePort);
         clientInfo.setCreate_time(sdf.format(new Date()));
         clientInfo.setClient_status('1');
         clientInfo.setIs_controlled((char)(checkAuth(projectId, remoteHost) ? '0' : '1'));
         clientInfo.setLast_opt_time("");
         clientInfo.setProject_id(projectId);
      }

      clientInfo.setLast_req_time(sdf.format(new Date()));
      saveClientInfo(clientInfo);
   }

   public static boolean isUpdateLastOptTime(String clientIp, int clientPort, String projectId) {
      TCoreClientInfo clientInfo = getClientInfo(clientIp, clientPort, projectId);
      if (encryptionRulesHasChanged(clientInfo)) {
         log(clientInfo.getClient_ip(), clientInfo.getClient_port(), "检测到加密规则有变化，更新客户端主表的lastOptTime字段为最新时间：" + clientInfo.getLast_opt_time());
         saveClientInfo(clientInfo);
         return true;
      } else {
         return false;
      }
   }

   public static String getLastUptTimeInEncryptionField(String project) {
      return clientInfoDao().getLastedUptTimeInEncryptionTime(project);
   }

   public static boolean encryptionRulesHasChanged(TCoreClientInfo clientInfo) {
      String lastOptTime = getLastUptTimeInEncryptionField(clientInfo.getProject_id());

      try {
         if (clientInfo != null && (StringUtils.isEmpty(clientInfo.getLast_opt_time()) || sdf.parse(clientInfo.getLast_opt_time()).getTime() < sdf.parse(lastOptTime).getTime())) {
            clientInfo.setLast_opt_time(lastOptTime);
            return true;
         }
      } catch (ParseException var3) {
      }

      return false;
   }

   public static boolean checkAuth(HttpServletRequest request) {
      Map<String, String> requestParamsMap = getRequestParamsMap(request);
      String clientHost = request.getRemoteHost();
      String projectid = (String)requestParamsMap.get("projectId");
      boolean result = checkAuth(projectid, clientHost);
      return result;
   }

   public static int compareIpV4s(String source, String target) {
      int result = 0;
      long ipValue1 = getIp2long(source);
      long ipValue2 = getIp2long(target);
      if (ipValue1 > ipValue2) {
         result = 1;
      } else {
         if (ipValue1 >= ipValue2) {
            return 0;
         }

         result = -1;
      }

      return result;
   }

   public static long getIp2long(String ip) {
      ip = ip.trim();
      String[] ips = ip.split("\\.");
      long ip2long = 0L;

      for(int i = 0; i < 4; ++i) {
         ip2long = ip2long << 8 | (long)Integer.parseInt(ips[i]);
      }

      return ip2long;
   }

   public static int getIpV4Value(String ipOrMask) {
      byte[] addr = getIpV4Bytes(ipOrMask);
      int address1 = addr[3] & 255;
      address1 |= addr[2] << 8 & '\uff00';
      address1 |= addr[1] << 16 & 16711680;
      address1 |= addr[0] << 24 & -16777216;
      return address1;
   }

   public static byte[] getIpV4Bytes(String ipOrMask) {
      try {
         String[] addrs = ipOrMask.split("\\.");
         int length = addrs.length;
         byte[] addr = new byte[length];

         for(int index = 0; index < length; ++index) {
            addr[index] = (byte)(Integer.parseInt(addrs[index]) & 255);
         }

         return addr;
      } catch (Exception var5) {
         return new byte[4];
      }
   }

   public static boolean checkAuth(String projectId, String clientHost) {
      for(String ipRange : clientIpControlledDao().getIpRange(projectId)) {
         if (ipRange.contains("/")) {
            String startIp = ipRange.split("/")[0];
            String endIp = ipRange.split("/")[1];
            if (compareIpV4s(startIp, clientHost) <= 0 && compareIpV4s(endIp, clientHost) >= 0) {
               return true;
            }
         } else if (clientHost.equals(ipRange)) {
            return true;
         }
      }

      try {
         List<TCoreClientInfo> clients = getClientInfoByIp(clientHost, projectId);
         if (clients != null && clients.size() > 0) {
            for(TCoreClientInfo client : clients) {
               client.setLast_opt_time("");
               clientInfoDao().saveOrUpdate(client);
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      return false;
   }

   private static TCoreClientInfo getClientInfo(String clientIp, int clientPort, String projectId) {
      return (TCoreClientInfo)Optional.ofNullable(clientInfoDao().queryJarClients(clientIp, clientPort, projectId)).orElse(null);
   }

   private static List<TCoreClientInfo> getClientInfoByIp(String clientIp, String projectId) {
      return (List)Optional.ofNullable(clientInfoDao().queryJarClientsByIp(clientIp, projectId)).orElse(null);
   }

   public static void saveClientInfo(TCoreClientInfo clientInfo) {
      try {
         clientInfoDao().saveOrUpdate(clientInfo);
      } catch (Exception var2) {
         log.info("客户端信息保存失败，失败客户端信息为：" + clientInfo.toString());
      }

   }

   public static TCoreClientInfoDao clientInfoDao() {
      return (TCoreClientInfoDao)SpringUtil.getBean(TCoreClientInfoDao.class);
   }

   public static TCoreClientIpControlledDao clientIpControlledDao() {
      return (TCoreClientIpControlledDao)SpringUtil.getBean(TCoreClientIpControlledDao.class);
   }

   public static void log(String msg) {
      ((ServerClientSocketLogDao)SpringUtil.getBean(ServerClientSocketLogDao.class)).log(msg);
   }

   public static void log(String ip, int port, String msg) {
      ((ServerClientSocketLogDao)SpringUtil.getBean(ServerClientSocketLogDao.class)).log(ip, port, msg);
   }

   public static Map<String, String> getRequestParamsMap(HttpServletRequest request) {
      Map<String, String> result = new HashMap();
      String queryString = request.getQueryString();
      String[] params = queryString.split("&");

      for(String param : params) {
         result.put(param.split("=")[0], param.split("=")[1]);
      }

      result.put("remoteHost", request.getRemoteHost());
      return result;
   }
}
