package com.engine.kq.biz;

import com.engine.kq.entity.KQGroupEntity;
import com.engine.kq.log.KQLog;
import com.google.common.collect.Lists;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.IpUtils;
import weaver.general.Util;
import weaver.hrm.common.database.dialect.DbDialectFactory;
import weaver.hrm.common.database.dialect.IDbDialectSql;

import java.util.*;

public class KQGroupBiz extends BaseBean {

  private static final double EARTH_RADIUS = 6378137;// 地球半径

  public String getGroupMemberSql() {
    return getGroupMemberSql("");
  }

  public String getGroupMemberSql(String groupId) {
    Map<String,Object> params = new HashMap<>();
    params.put("groupId",groupId);
    return this.getGroupMemberSql(params);
  }

  public String getGroupMemberSql(Map<String,Object> params) {
    String sql = "";
    try {
      String groupId = Util.null2String(params.get("groupId"));
      String isNoAccount = Util.null2String(params.get("isNoAccount"));
      sql = " SELECT distinct resourceid, groupid FROM ( " +
              " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " +
              " WHERE a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') " +
              " UNION ALL " +
              " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " +
              " WHERE a.subcompanyid1 = b.typevalue AND b.type=2 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') " +
              " UNION ALL " +
              " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " +
              " WHERE a.departmentid = b.typevalue AND b.type=3 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') " +
              " UNION ALL " +
              " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " +
              " WHERE a.jobtitle = b.typevalue AND b.type=5 " +
              " AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " +
              " and (b.isdelete is null or b.isdelete <> '1') " +
              " UNION ALL " +
              " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " +
              " WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') ) t" +
              " where 1=1 ";
      if(!Util.null2String(isNoAccount).equals("1")){
        sql += " and t.status in (0,1,2,3) ";
      }

      if(Util.null2String(groupId).length()>0){
        sql += "  and t.groupid =  "+groupId;
      }
    } catch (Exception e) {
      writeLog(e);
    }

    return sql;
  }

  public List<String> getGroupMembers(String groupId) {
    Map<String,Object> params = new HashMap<>();
    params.put("groupId",groupId);
    return this.getGroupMembers(params);
  }

  public List<String> getGroupMembers(Map<String,Object> params) {
    RecordSet rs = new RecordSet();
    List<String> members = new ArrayList<>();
    try {
      String sql = this.getGroupMemberSql(params);
      rs.executeQuery(sql);
      while (rs.next()) {
        members.add(rs.getString("resourceid"));
      }
    } catch (Exception e) {
      writeLog(e);
    }

    return members;
  }

  //根据传入的班次id，然后判断是否有考勤组引用这个班次
  public boolean serialIdIsUesed(String serialid) {
    boolean serialIdUesed = false;
    RecordSet rs = new RecordSet();
    String sql = "";
    IDbDialectSql dialectSql = DbDialectFactory.get(rs.getDBType()) ;
    String isDeleteField = dialectSql.isNull("isdelete",0) ;
    try {
      sql = " select count(1) " +
              " from (select distinct serialid from kq_fixedschedulce where serialid in ( ? ) and ("+isDeleteField+" !=1 ) "+
              " union " +
              " select distinct serialid from kq_shiftschedule where serialid in ( ? ) and ("+isDeleteField+" !=1 ) ) t";
      rs.executeQuery(sql,serialid,serialid);
      if (rs.next()){
        if(rs.getInt(1)>0){
          serialIdUesed = true;
        }
      }

      if(!serialIdUesed){


        if(rs.getDBType().equals("oracle")||rs.getDBType().equals("postgresql")) {
          sql = " select count(1) from kq_group where ((','||serialids||',') like '%," + serialid + ",%' or  (','||shiftcycleserialids||',') like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')";
        }else if(rs.getDBType().equals("mysql")){
          String serialidsConcatContion = dialectSql.concatStr("','","serialids","','") ;
          String shiftcycleSerialidsConcatConditon = dialectSql.concatStr("','","shiftcycleserialids","','") ;
          String groupIsDeleteCondition = dialectSql.isNull("isdelete",0) ;
          String likeValue = "%,"+serialid+",%" ;

          sql = String.format(" select count(1) from kq_group where ((%s) like '%s' or  (%s) like '%s') and (%s!=1)",
                  serialidsConcatContion,likeValue,
                  shiftcycleSerialidsConcatConditon,likeValue,
                  groupIsDeleteCondition) ;
        }else{
          sql = " select count(1) from kq_group where (','+serialids+',' like '%," + serialid + ",%' or  ','+shiftcycleserialids+',' like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')";
        }



        rs.executeQuery(sql);
        if (rs.next()){
          if(rs.getInt(1)>0){
            serialIdUesed = true;
          }
        }
      }
    } catch (Exception e) {
      writeLog(e);
    }
    return serialIdUesed;
  }

  /**
   * 根据传入的班次id，引用此班次的考勤组
   * @param serialid
   * @return
   */
  public List<String> getGroupIdByUesedSerialId(String serialid) {
    RecordSet rs = new RecordSet();
    List<String> groupList = Lists.newArrayList();
    String sql = "";
    IDbDialectSql dialectSql = DbDialectFactory.get(rs.getDBType()) ;
    String isDeleteField = dialectSql.isNull("isdelete",0) ;
    try {
      sql = " select serialid,groupid " +
          " from (select distinct serialid,groupid from kq_fixedschedulce where serialid in ( ? ) and ("+isDeleteField+" !=1 ) "+
          " union " +
          " select distinct serialid,groupid from kq_shiftschedule where serialid in ( ? ) and ("+isDeleteField+" !=1 ) ) t";
      rs.executeQuery(sql,serialid,serialid);
      while (rs.next()){
        String tmp_groupId = rs.getString("groupid");
        if(!groupList.contains(tmp_groupId)){
          groupList.add(tmp_groupId);
        }
      }

      if(rs.getDBType().equals("oracle")||rs.getDBType().equals("postgresql")) {
        sql = " select id from kq_group where ((','||serialids||',') like '%," + serialid + ",%' or  (','||shiftcycleserialids||',') like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')";
      }else if(rs.getDBType().equals("mysql")){
        String serialidsConcatContion = dialectSql.concatStr("','","serialids","','") ;
        String shiftcycleSerialidsConcatConditon = dialectSql.concatStr("','","shiftcycleserialids","','") ;
        String groupIsDeleteCondition = dialectSql.isNull("isdelete",0) ;
        String likeValue = "%,"+serialid+",%" ;

        sql = String.format(" select id from kq_group where ((%s) like '%s' or  (%s) like '%s') and (%s!=1)",
            serialidsConcatContion,likeValue,
            shiftcycleSerialidsConcatConditon,likeValue,
            groupIsDeleteCondition) ;
      }else{
        sql = " select id from kq_group where (','+serialids+',' like '%," + serialid + ",%' or  ','+shiftcycleserialids+',' like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')";
      }

      rs.executeQuery(sql);
      while (rs.next()){
        String tmp_groupId = rs.getString("id");
        if(!groupList.contains(tmp_groupId)){
          groupList.add(tmp_groupId);
        }
      }
    } catch (Exception e) {
      writeLog(e);
    }
    return groupList;
  }

  public Map<String,Object> getLocationWifiInfo(String userid,String showWifiList) {
    Map<String,Object> result = new HashMap<>();
    Map<String,Object> locationInfo = new HashMap<>();
    Map<String,Object> wifiInfo = new HashMap<>();
    KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
    KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
    KQLoactionComInfo kqLoactionComInfo = new KQLoactionComInfo();
    String groupid = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userid));
    List<Object> datas = null;
    Map<String, Object> data = null;

    if(groupid.length()>0){
      datas = new ArrayList();
      while(kqLoactionComInfo.next()){
        if(!kqLoactionComInfo.getGroupid().equals(groupid))continue;
        data = new HashMap<>();
        data.put("id",kqLoactionComInfo.getId());
        data.put("locationname",Util.null2String(kqLoactionComInfo.getLocationname()));
        data.put("longitude",Util.null2String(kqLoactionComInfo.getLongitude()));
        data.put("latitude",Util.null2String(kqLoactionComInfo.getLatitude()));
        data.put("address",Util.null2String(kqLoactionComInfo.getAddress()));
        data.put("checkscope",Util.null2String(kqLoactionComInfo.getCheckscope()));
        data.put("groupid",Util.null2String(kqLoactionComInfo.getGroupid()));
        datas.add(data);
      }
      locationInfo.put("locationcheck",Util.null2String(kqGroupComInfo.getLocationcheck(groupid)).equals("1"));
      locationInfo.put("locationcheckscope",Util.null2String(kqGroupComInfo.getLocationcheckscope(groupid)));
      locationInfo.put("locations",datas);

      datas = new ArrayList();
      if("1".equalsIgnoreCase(showWifiList)){
        KQWifiComInfo kqWifiComInfo = new KQWifiComInfo();
        while(kqWifiComInfo.next()){
          if(!kqWifiComInfo.getGroupid().equals(groupid))continue;
          data = new HashMap<>();
          data.put("id",kqWifiComInfo.getId());
          data.put("wifiname",Util.null2String(kqWifiComInfo.getWifiname()));
          data.put("mac",Util.null2String(kqWifiComInfo.getMac()));
          data.put("groupid",Util.null2String(kqWifiComInfo.getGroupid()));
          datas.add(data);
        }
      }
      wifiInfo.put("wificheck",Util.null2String(kqGroupComInfo.getWificheck(groupid)).equals("1"));
      wifiInfo.put("wifis",datas);

      result.put("locationInfo",locationInfo);
      result.put("wifiInfo",wifiInfo);
      result.put("status","1");
    }
    return result;
  }
  /**
   * 用户考勤地点 WIFI限制信息
   * @param userid
   * @return
   */
  public Map<String,Object> getLocationWifiInfo(String userid) {
    return getLocationWifiInfo(userid,"1");
  }

  /**
   *判断办公地点范围
   * @return
   */
  public Map<String,Object> checkLocationScope(String userId, String longitude, String latitude){
    Map<String,Object> retmap = new HashMap<>();
    Map<String,Object> loactionInfo = null;
    boolean inScope = false;
    KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
    KQGroupEntity kqGroupEntity = kqGroupMemberComInfo.getUserKQGroupInfo(userId);
    KQLoactionComInfo kqLoactionComInfo = new KQLoactionComInfo();
    if(kqGroupEntity != null && kqGroupEntity.getLocationcheck().equals("1")){
      while(kqLoactionComInfo.next()){
        if(Util.null2String(kqLoactionComInfo.getGroupid()).equals(kqGroupEntity.getId())){
          double lng1 = Util.getDoubleValue(longitude);//经度
          double lat1 = Util.getDoubleValue(latitude);//纬度
          double lng2 = Util.getDoubleValue(kqLoactionComInfo.getLongitude());//经度
          double lat2 = Util.getDoubleValue(kqLoactionComInfo.getLatitude());//纬度
          int checkscope = Util.getIntValue(kqLoactionComInfo.getCheckscope());//有效范围
          if(geo_distance(lng1, lat1, lng2, lat2)<checkscope){
            inScope = true;
            loactionInfo = new HashMap<>();
            loactionInfo.put("locationname",kqLoactionComInfo.getLocationname());
            loactionInfo.put("longitude",kqLoactionComInfo.getLongitude());
            loactionInfo.put("latitude",kqLoactionComInfo.getLatitude());
            loactionInfo.put("address",kqLoactionComInfo.getAddress());
            loactionInfo.put("id",kqLoactionComInfo.getId());
            break;
          }
        }
      }
    }else{//未开启开关
      inScope = true;
    }
    retmap.put("needCheck",kqGroupEntity != null ? Util.null2String(kqGroupEntity.getLocationcheck()) : "0");//是否开启办公地点验证
    retmap.put("inScope",inScope);//是否在考勤范围内
    retmap.put("locationshowaddress",kqGroupEntity != null ? Util.null2String(kqGroupEntity.getLocationshowaddress()) : "0");//有效识别半径内显示同一地址
    retmap.put("loactionInfo",loactionInfo);//考勤范围相关信息
    return retmap;
  }

  /**
   * 计算两个经度纬度(WGS-84)之间的距离
   * @param lng1 坐标1经度
   * @param lat1 坐标1纬度EARTH_RADIUS
   * @param lng2 坐标2经度
   * @param lat2 坐标2纬度
   * @return 2个坐标之间距离,单位:米
   */
  private double geo_distance(double lng1, double lat1, double lng2, double lat2) {
    double radLat1 = Math.toRadians(lat1);
    double radLat2 = Math.toRadians(lat2);
    double a = Math.abs(radLat1 - radLat2);
    double b = Math.abs(Math.toRadians(lng1) - Math.toRadians(lng2));
    double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    distance = distance * EARTH_RADIUS;
    distance = Math.round(distance * 10000) / 10000;
    return distance;
  }

  /**
   *判断Wifi范围
   * @return
   */
  public Map<String,Object> checkWifiScope(String userId, String wifiName, String mac){
    Map<String,Object> retmap = new HashMap<>();
    Map<String,Object> wifiInfo = null;
    boolean inScope = false;
    KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
    KQGroupEntity kqGroupEntity = kqGroupMemberComInfo.getUserKQGroupInfo(userId);
    KQWifiComInfo kqWifiComInfo = new KQWifiComInfo();

    if(kqGroupEntity.getWificheck().equals("1")){
      try{
        List<String> lst = new ArrayList<>(Arrays.asList(mac.split(":")));
        for(int i = 0; i < lst.size(); i++){
          String s = lst.get(i);
          if(s.length() == 1)
            lst.set(i, "0" + s);
        }
        mac = String.join(":", lst);
      }catch (Exception ex){
        ex.printStackTrace();
      }
      while(kqWifiComInfo.next()){
        if(Util.null2String(kqWifiComInfo.getGroupid()).equals(kqGroupEntity.getId())){
          if(Util.null2String(kqWifiComInfo.getWifiname().toLowerCase()).equals(wifiName.toLowerCase())){
            String wifi_cominfo_mac = Util.null2String(kqWifiComInfo.getMac().toLowerCase());
            String param_mac = mac.toLowerCase();
            int last_wifi_mac_index = wifi_cominfo_mac.lastIndexOf(":");
            int param_mac_index = param_mac.lastIndexOf(":");
            if(last_wifi_mac_index > 0 && param_mac_index > 0){
              wifi_cominfo_mac = wifi_cominfo_mac.substring(0,last_wifi_mac_index);
              param_mac = param_mac.substring(0,param_mac_index);
            }
            if(wifi_cominfo_mac.equals(param_mac)){
              inScope = true;
              wifiInfo = new HashMap<>();
              wifiInfo.put("wifiname",kqWifiComInfo.getWifiname());
              wifiInfo.put("mac",kqWifiComInfo.getMac());
              break;
            }
          }
        }
      }
    }else{//未开启开关
      inScope = true;
    }
    retmap.put("needCheck",Util.null2String(kqGroupEntity.getWificheck()));//是否开启wifi验证
    retmap.put("inScope",inScope);//是否在考勤范围内
    retmap.put("wifiInfo",wifiInfo);//考勤范围相关信息
    return retmap;
  }

  /**
   * 校验ipv4和v6范围
   * @param userId
   * @param clientAddress
   * @param ismobile
   * @return
   */
  public boolean getIsInScopeV4V6(String userId, String clientAddress,String ismobile) {
    boolean isInScope = false;
    clientAddress = Util.null2String(clientAddress).trim();
    if (clientAddress.length() == 0) {
      return isInScope;
    }

    RecordSet rs = new RecordSet();
    KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
    KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
    String groupid = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userId));
    String signIpScope = Util.null2String(kqGroupComInfo.getIpscope(groupid)).trim();//格式：10.*.*.*;10.16.0.12;10.16.0.13-10.16.0.18
    String signIpscope_v4_em = Util.null2String(kqGroupComInfo.getIpscope_v4_em(groupid)).trim();
    String signIpscope_v4_pc = Util.null2String(kqGroupComInfo.getIpscope_v4_pc(groupid)).trim();
    String signIpscope_v6_em = Util.null2String(kqGroupComInfo.getIpscope_v6_em(groupid)).trim();
    String signIpscope_v6_pc = Util.null2String(kqGroupComInfo.getIpscope_v6_pc(groupid)).trim();
    if (signIpscope_v4_em.length() == 0 && signIpscope_v4_pc.length() == 0
        && signIpscope_v6_em.length() == 0 && signIpscope_v6_pc.length() == 0) {
      return true;
    }

    new KQLog().info("getIsInScopeV4V6:ismobile:"+ismobile+":signIpscope_v4_em:"+signIpscope_v4_em+":signIpscope_v6_em:"+signIpscope_v6_em
        +":signIpscope_v4_pc:"+signIpscope_v4_pc+":signIpscope_v6_pc:"+signIpscope_v6_pc);
    if("1".equalsIgnoreCase(ismobile)){
      if(signIpscope_v4_em.length() > 0){
        return checkIps(signIpscope_v4_em,clientAddress,"IPv4");
      }else if(signIpscope_v6_em.length() > 0){
        return checkIps(signIpscope_v6_em,clientAddress,"IPv6");
      }else{
        return true;
      }
    }else{
      if(signIpscope_v4_pc.length() > 0){
        return checkIps(signIpscope_v4_pc,clientAddress,"IPv4");
      }else if(signIpscope_v6_pc.length() > 0){
        return checkIps(signIpscope_v6_pc,clientAddress,"IPv6");
      }else{
        return true;
      }
    }
  }


  private boolean checkIps(String signIpScope, String clientAddress,String ipType) {
    boolean isInScope = false;
    List signIpScopeList = Util.TokenizerString(signIpScope, ";");
    String signIpScopeSingle = "";
    for (int i = 0; i < signIpScopeList.size(); i++) {
      signIpScopeSingle = Util.null2String((String) signIpScopeList.get(i));
      signIpScopeSingle = signIpScopeSingle.trim();
      if("IPv4".equalsIgnoreCase(ipType)){
        isInScope = checkIpV4(signIpScopeSingle,clientAddress);
        if(isInScope){
          break;
        }
      }else if("IPv6".equalsIgnoreCase(ipType)){
        isInScope = checkIpV6(signIpScopeSingle,clientAddress);
        if(isInScope){
          break;
        }
      }
    }
    return isInScope;
  }

  private boolean checkIpV6(String signIpScopeSingle, String clientAddress) {

    boolean isInScope = false;
    if (signIpScopeSingle.indexOf("-") > -1) {
      String signIpFrom = signIpScopeSingle.substring(0, signIpScopeSingle.indexOf("-"));
      signIpFrom = Util.null2String(signIpFrom).trim();
      String signIpTo = "";
      if (!signIpScopeSingle.endsWith("-")) {
        signIpTo = signIpScopeSingle.substring(signIpScopeSingle.indexOf("-") + 1);
      }
      signIpTo = Util.null2String(signIpTo).trim();
      String tempClientAddress = IpUtils.parseAbbreviationToFullIPv6(clientAddress);
      signIpFrom = addToThreeFigure(signIpFrom, "signIpFrom");
      signIpTo = addToThreeFigure(signIpTo, "signIpTo");

      signIpFrom = IpUtils.parseAbbreviationToFullIPv6(signIpFrom);
      signIpTo = IpUtils.parseAbbreviationToFullIPv6(signIpTo);

      if (signIpFrom.equals("") && signIpTo.equals("")) {
        isInScope = true;
      }
      if (signIpFrom.equals("") && !signIpTo.equals("")) {
        if (tempClientAddress.compareTo(signIpTo) <= 0) {
          isInScope = true;
        }
      }

      if (!signIpFrom.equals("") && signIpTo.equals("")) {
        if (tempClientAddress.compareTo(signIpFrom) >= 0) {
          isInScope = true;
        }
      }
      if (!signIpFrom.equals("") && !signIpTo.equals("")) {
        if (tempClientAddress.compareTo(signIpFrom) >= 0 && tempClientAddress.compareTo(signIpTo) <= 0) {
          isInScope = true;
        }
      }
    } else {
      String tempClientAddress = IpUtils.parseAbbreviationToFullIPv6(clientAddress);
      if (tempClientAddress.equals(signIpScopeSingle)) {
        isInScope = true;
      }
    }
    return isInScope;
  }

  public boolean checkIpV4(String signIpScopeSingle,String clientAddress) {

    boolean isInScope = false;
    if (signIpScopeSingle.indexOf("*") > -1) {//如果单个ip范围的格式为10.*.*.*
      List signIpScopeSingleList = Util.TokenizerString(signIpScopeSingle, ".");
      List clientAddressList = Util.TokenizerString(clientAddress, ".");
      if (signIpScopeSingleList.size() == 4
          && clientAddressList.size() == 4
          && ("*".equals((String) signIpScopeSingleList.get(0))
          || Util.null2String((String) clientAddressList.get(0)).equals((String) signIpScopeSingleList.get(0)))
          && ("*".equals((String) signIpScopeSingleList.get(1))
          || Util.null2String((String) clientAddressList.get(1)).equals((String) signIpScopeSingleList.get(1)))
          && ("*".equals((String) signIpScopeSingleList.get(2))
          || Util.null2String((String) clientAddressList.get(2)).equals((String) signIpScopeSingleList.get(2)))
          && ("*".equals((String) signIpScopeSingleList.get(3))
          || Util.null2String((String) clientAddressList.get(3)).equals((String) signIpScopeSingleList.get(2)))
      ) {
        isInScope = true;
      }
    } else if (signIpScopeSingle.indexOf("-") > -1) {//如果单个ip范围的格式为10.16.0.13-10.16.0.18
      String signIpFrom = signIpScopeSingle.substring(0, signIpScopeSingle.indexOf("-"));
      signIpFrom = Util.null2String(signIpFrom).trim();
      String signIpTo = "";
      if (!signIpScopeSingle.endsWith("-")) {
        signIpTo = signIpScopeSingle.substring(signIpScopeSingle.indexOf("-") + 1);
      }
      signIpTo = Util.null2String(signIpTo).trim();
      String tempClientAddress = addToThreeFigure(clientAddress, "clientAddress");
      signIpFrom = addToThreeFigure(signIpFrom, "signIpFrom");
      signIpTo = addToThreeFigure(signIpTo, "signIpTo");

      if (signIpFrom.equals("") && signIpTo.equals("")) {
        isInScope = true;
      }
      if (signIpFrom.equals("") && !signIpTo.equals("")) {
        if (tempClientAddress.compareTo(signIpTo) <= 0) {
          isInScope = true;
        }
      }

      if (!signIpFrom.equals("") && signIpTo.equals("")) {
        if (tempClientAddress.compareTo(signIpFrom) >= 0) {
          isInScope = true;
        }
      }
      if (!signIpFrom.equals("") && !signIpTo.equals("")) {
        if (tempClientAddress.compareTo(signIpFrom) >= 0 && tempClientAddress.compareTo(signIpTo) <= 0) {
          isInScope = true;
        }
      }
    } else {//否则单个ip范围的格式为10.16.0.12
      if (clientAddress.equals(signIpScopeSingle)) {
        isInScope = true;
      }
    }
    return isInScope;
  }


  /**
   * 校验ip范围
   * @param clientAddress
   * @return
   */
  public boolean getIsInScope(String userId, String clientAddress) {
    boolean isInScope = false;
    clientAddress = Util.null2String(clientAddress).trim();
    if (clientAddress.length() == 0) {
      return isInScope;
    }

    RecordSet rs = new RecordSet();
    KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
    KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
    String groupid = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userId));
    String signIpScope = Util.null2String(kqGroupComInfo.getIpscope(groupid)).trim();//格式：10.*.*.*;10.16.0.12;10.16.0.13-10.16.0.18
    if (signIpScope.length() == 0) {
      return true;
    }

    List signIpScopeList = Util.TokenizerString(signIpScope, ";");
    String signIpScopeSingle = "";
    for (int i = 0; i < signIpScopeList.size(); i++) {
      signIpScopeSingle = Util.null2String((String) signIpScopeList.get(i));
      signIpScopeSingle = signIpScopeSingle.trim();
      if (signIpScopeSingle.indexOf("*") > -1) {//如果单个ip范围的格式为10.*.*.*
        List signIpScopeSingleList = Util.TokenizerString(signIpScopeSingle, ".");
        List clientAddressList = Util.TokenizerString(clientAddress, ".");
        if (signIpScopeSingleList.size() == 4
            && clientAddressList.size() == 4
            && ("*".equals((String) signIpScopeSingleList.get(0))
            || Util.null2String((String) clientAddressList.get(0)).equals((String) signIpScopeSingleList.get(0)))
            && ("*".equals((String) signIpScopeSingleList.get(1))
            || Util.null2String((String) clientAddressList.get(1)).equals((String) signIpScopeSingleList.get(1)))
            && ("*".equals((String) signIpScopeSingleList.get(2))
            || Util.null2String((String) clientAddressList.get(2)).equals((String) signIpScopeSingleList.get(2)))
            && ("*".equals((String) signIpScopeSingleList.get(3))
            || Util.null2String((String) clientAddressList.get(3)).equals((String) signIpScopeSingleList.get(2)))
        ) {
          isInScope = true;
          break;
        }

      } else if (signIpScopeSingle.indexOf("-") > -1) {//如果单个ip范围的格式为10.16.0.13-10.16.0.18
        String signIpFrom = signIpScopeSingle.substring(0, signIpScopeSingle.indexOf("-"));
        signIpFrom = Util.null2String(signIpFrom).trim();
        String signIpTo = "";
        if (!signIpScopeSingle.endsWith("-")) {
          signIpTo = signIpScopeSingle.substring(signIpScopeSingle.indexOf("-") + 1);
        }
        signIpTo = Util.null2String(signIpTo).trim();
        String tempClientAddress = addToThreeFigure(clientAddress, "clientAddress");
        signIpFrom = addToThreeFigure(signIpFrom, "signIpFrom");
        signIpTo = addToThreeFigure(signIpTo, "signIpTo");

        if (signIpFrom.equals("") && signIpTo.equals("")) {
          isInScope = true;
          break;
        }
        if (signIpFrom.equals("") && !signIpTo.equals("")) {
          if (tempClientAddress.compareTo(signIpTo) <= 0) {
            isInScope = true;
            break;
          }
        }

        if (!signIpFrom.equals("") && signIpTo.equals("")) {
          if (tempClientAddress.compareTo(signIpFrom) >= 0) {
            isInScope = true;
            break;
          }
        }
        if (!signIpFrom.equals("") && !signIpTo.equals("")) {
          if (tempClientAddress.compareTo(signIpFrom) >= 0 && tempClientAddress.compareTo(signIpTo) <= 0) {
            isInScope = true;
            break;
          }
        }
      } else {//否则单个ip范围的格式为10.16.0.12
        if (clientAddress.equals(signIpScopeSingle)) {
          isInScope = true;
          break;
        }
      }
    }
    return isInScope;
  }
  /**
   * 将IP地址填充为3位数
   * 如  "192.168.0.25"填充为3位数后为"192.168.000.025"
   * @return String   填充为3位数后的IP地址
   */
  private String addToThreeFigure(String IPAddress, String IPType) {
    if (IPAddress == null || IPAddress.trim().equals("") || IPType == null || IPType.trim().equals("")) {
      return "";
    }
    String returnString = "";
    List IPAddressList = Util.TokenizerString(IPAddress, ".");
    String IPAddressPart = "";
    for (int i = 0; i < IPAddressList.size(); i++) {
      IPAddressPart = Util.null2String(IPAddressList.get(i));
      if (IPType.equals("signIpTo")) {
        returnString += "." + Util.add0(Util.getIntValue(IPAddressPart, 255), 3);
      } else {
        returnString += "." + Util.add0(Util.getIntValue(IPAddressPart, 0), 3);
      }
    }
    if (!returnString.equals("")) {
      returnString = returnString.substring(1);
    }
    return returnString;
  }
}