package com.chenyang.nse.bussiness.tools.licensekey;

import com.esotericsoftware.minlog.Log;
import com.chenyang.nse.bussiness.commmon.json.RespHelper;
import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseUser;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.tools.msg.MesUtil;
import com.chenyang.nse.bussiness.tools.string.AesTool;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.collections.map.HashedMap;

public class LicenseKeyTool {
   public static Map<String, String> map = new HashedMap();

   public static ResultVO verifyproperties(TBaseUser tBaseUser) throws ClassNotFoundException, IOException, SQLException, ParseException {
      ResultVO resultVO = new ResultVO();
      new HashMap();
      resultVO.setResult(true);
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      String isNeedLicenseKey = props.getProperty("isNeedLicenseKey");
      if ("1".equals(isNeedLicenseKey)) {
         String url = props.getProperty("licensedir");
         File file = new File(url + "/gtconfig.dat");
         if (file.exists()) {
            FileReader fileReader = new FileReader(file);
            BufferedReader bfReader = new BufferedReader(fileReader);
            StringBuffer stringBuffer = new StringBuffer();

            String line;
            while((line = bfReader.readLine()) != null) {
               stringBuffer.append(line);
            }

            fileReader.close();
            bfReader.close();
            resultVO = checkKey(stringBuffer.toString());
         } else {
            resultVO.setResult(false);
            resultVO.setMessage("缺少LICENCE KEY文件");
            resultVO.setResponse(RespHelper.createResp(false, "LGS_ERR_001", MesUtil.getMsg("LGS_ERR_001", new String[0])));
            map.put("flag", "0");
            map.put("msg", MesUtil.getMsg("LGS_ERR_001", new String[0]));
         }
      }

      return resultVO;
   }

   private static ResultVO checkKey(String licensekey) throws ParseException, SocketException {
      ResultVO resultVO = new ResultVO();
      if (licensekey != null && !licensekey.equals("")) {
         String password = "ghca";
         String licensekeyAfter = AesTool.decrypt(licensekey, password);
         if (licensekeyAfter == null) {
            resultVO.setMessage("密钥不正确");
            resultVO.setResult(false);
            resultVO.setResponse(RespHelper.createResp(false, "LGS_ERR_004", MesUtil.getMsg("LGS_ERR_004", new String[0])));
            map.put("flag", "0");
            map.put("msg", MesUtil.getMsg("LGS_ERR_004", new String[0]));
            return resultVO;
         } else {
            String[] licensekeyMessage = licensekeyAfter.split(",");
            String licname = licensekeyMessage[0];
            String licUUid = licensekeyMessage[1];
            String licInfoMac = licensekeyMessage[2];
            String startDatelicensekey = licensekeyMessage[3];
            String endDatelicensekey = licensekeyMessage[4];
            String projectNum = licensekeyMessage[5];
            map.put("licname", licname);
            map.put("licInfoIp", licUUid);
            map.put("licInfoMac", licInfoMac);
            map.put("startDatelicensekey", startDatelicensekey);
            map.put("endDatelicensekey", endDatelicensekey);
            map.put("projectNum", projectNum);
            Log.info("校验的证书是不是失效--UUID");
            List linuxLocalUUID = getLinuxLocalUUID();
            String mac = getLocalMacLiunx();
            boolean b = false;
            Log.info("校验的证书是不是失效--linuxLocalUUID" + linuxLocalUUID);

            for(int i = 0; i < linuxLocalUUID.size(); ++i) {
               String localUUid = (String)linuxLocalUUID.get(i);
               System.out.println(localUUid + "==" + licUUid);
               Log.info(localUUid + "==" + licUUid);
               if (licUUid.equalsIgnoreCase(localUUid) && licInfoMac.equalsIgnoreCase(mac)) {
                  Log.info("成功");
                  b = true;
                  break;
               }
            }

            if (!b) {
               resultVO.setMessage("uuid有误");
               resultVO.setResult(false);
               resultVO.setResponse(RespHelper.createResp(false, "LGS_ERR_002", MesUtil.getMsg("LGS_ERR_002", new String[0])));
               map.put("flag", "0");
               map.put("msg", MesUtil.getMsg("LGS_ERR_002", new String[0]));
               return resultVO;
            } else {
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
               Date date = new Date();
               Date startDate = sdf.parse(startDatelicensekey);
               Date endDate = sdf.parse(endDatelicensekey);
               int dayMis = 86400000;
               long startDateMis = startDate.getTime();
               long endDateMis = endDate.getTime() + (long)dayMis - 1L;
               long curDateMis = date.getTime();
               if (startDateMis <= curDateMis && curDateMis <= endDateMis) {
                  resultVO.setMessage("在有效期间");
                  resultVO.setResult(true);
                  map.put("flag", "1");
                  map.put("msg", MesUtil.getMsg("LGS_001", new String[0]));
                  return resultVO;
               } else {
                  resultVO.setMessage("您的用户秘钥已过期");
                  resultVO.setResult(false);
                  resultVO.setResponse(RespHelper.createResp(false, "LGS_ERR_003", MesUtil.getMsg("LGS_ERR_003", new String[0])));
                  map.put("flag", "0");
                  map.put("msg", MesUtil.getMsg("LGS_ERR_003", new String[0]));
                  return resultVO;
               }
            }
         }
      } else {
         resultVO.setMessage("密钥为空");
         resultVO.setResult(false);
         resultVO.setResponse(RespHelper.createResp(false, "LGS_ERR_004", MesUtil.getMsg("LGS_ERR_004", new String[0])));
         map.put("flag", "0");
         map.put("msg", MesUtil.getMsg("LGS_ERR_001", new String[0]));
         return resultVO;
      }
   }

   public static List getLinuxLocalUUID() {
      List<String> ipList = new ArrayList();
      String device = "";

      try {
         Process process = Runtime.getRuntime().exec("blkid " + device);
         BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

         String line;
         while((line = reader.readLine()) != null) {
            String[] ac = line.split(" ");
            String uuid = ac[1];
            String[] uuids = uuid.split("\"");
            String uuidr = uuids[1];
            ipList.add(uuidr);
         }

         reader.close();
      } catch (IOException e) {
         Log.info("校验的证书是不是失效--linuxLocalUUID" + e.getMessage());
      }

      return ipList;
   }

   public static List getLinuxLocalIp() throws SocketException {
      List<String> ipList = new ArrayList();
      String ip = "";

      try {
         Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();

         while(en.hasMoreElements()) {
            NetworkInterface intf = (NetworkInterface)en.nextElement();
            String name = intf.getName();
            if (!name.contains("docker") && !name.contains("lo")) {
               Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();

               while(enumIpAddr.hasMoreElements()) {
                  InetAddress inetAddress = (InetAddress)enumIpAddr.nextElement();
                  if (!inetAddress.isLoopbackAddress()) {
                     String ipaddress = inetAddress.getHostAddress().toString();
                     if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                        ipList.add(ipaddress);
                     }
                  }
               }
            }
         }
      } catch (SocketException ex) {
         ip = "127.0.0.1";
         ex.printStackTrace();
      }

      return ipList;
   }

   public static String getLocalMacLiunx() throws SocketException {
      String mac = "";

      try {
         Process p = (new ProcessBuilder(new String[]{"ifconfig"})).start();
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

         String line;
         while((line = br.readLine()) != null) {
            Pattern pat = Pattern.compile("\\b\\w+:\\w+:\\w+:\\w+:\\w+:\\w+\\b");
            Matcher mat = pat.matcher(line);
            if (mat.find()) {
               mac = mat.group(0);
            }
         }

         br.close();
      } catch (IOException var6) {
      }

      System.out.println("本机MAC地址为:\n" + mac);
      return mac;
   }

   public static void main(String[] args) {
      String content = "有效期1个月,10.10.200.24,fe:fc:fe:21:01:2d,2024-12-11,2025-01-11,5";
      String password = "ghca";
      System.out.println("加密之前：" + content);
      String encrypt = AesTool.encrypt(content, password);
      System.out.println("加密后的内容：" + encrypt);
      String decrypt = AesTool.decrypt(encrypt, password);
      System.out.println("解密后的内容：" + new String(decrypt));
   }
}
