init.js 8.63 KB
$(function() {

  // Client funcs
  getScript('interface/funs.js')

  // init i18n
  initLocale(function () {
    initDetectTable()
  })
  
})

function operateFormatter(value, row, index) {
  return [
      '<a class="detect btn active" href="#" data-i18n="btn_detect">'+ i18n.t('btn_detect') +'</a>'
  ].join('');
} 

function initDetectTable () {
  var $table = $('#table')
  var $detectall = $('#btn-detect-all')
  var $selelang = $('#btn-sele-lang')
  $table.bootstrapTable({
    url: 'interface/items-'+ {'7': 'zh-CN', '8': 'en-US', '9': 'zh-TW'}[detectLanguage] +'.json',
    columns: [
      {
        field: 'state',
        checkbox: true,
        align: 'center',
        valign: 'middle'
      },
      {
        field: 'keywords',
        title: i18n.t('col0'),
        width: '33%'
      }, {
        field: 'result',
        title: i18n.t('col1'),
        cellStyle: function (value, row, index, field) {
	    	var strClass = "";
	    	if (value === i18n.t("detect_pass")) {
    			strClass = 'pass'
    		} else {
    			strClass = 'fail'
    		}
	    	return { classes: strClass }
	    }
      }, {
        field: 'resolution',
        title: i18n.t('col2'),
        width: '33%'
      },
      {
        field: 'operate',
        title: i18n.t('col3'),
        formatter: operateFormatter,
        events: operateEvents,
        width: 150
      }
    ],
    method: 'get',
    toolbar: '#toolbar', 
    striped: true,
    cache: false,
    pagination: true,
    sortable: false,
    sortOrder: "asc",
    sidePagination: "client",
    pageNumber: 1,
    pageSize: 10,
    pageList: [10, 25, 50, 100, 'All'],
    search: true,
    contentType: "application/json",
    strictSearch: false,
    // searchOnEnterKey: true,
    showColumns: true,
    showRefresh: true,
    minimumCountColumns: 1,
    clickToSelect: true,
    uniqueId: "id", 
    // showToggle: true,
    cardView: false,
    detailView: false
  });
  // 适应窗口高度变化
  $(window).resize(function () {
    $table.bootstrapTable('resetView');
  });
  
  $table.on('pre-body.bs.table', function(e, data) {
    // 避免重复渲染导致数据错乱
    if (typeof window.diables !== 'undefined') return
    window.diables = []
  	for (var id in data) {
  	  if (data[id].disable) {
  	  	window.diables.push(id)
  	  }
  	  // 判断当前环境是公有云还是私有云
  	  else if (data[id].rongcloud && sysinfo.isUseOpenfire) {
  	  	window.diables.push(id)
  	  }
  	  else if (data[id].openfire && !sysinfo.isUseOpenfire) {
  	  	window.diables.push(id)
  	  }
  	  // 没有开启emessage功能,需要屏蔽掉若干功能
      else if ($.inArray(id, ['1', '6', '7', '9']) >= 0 && !sysinfo.isUseEm) {
        window.diables.push(id)
      }
  	}
  })
  
  $table.on('post-body.bs.table', function(e, data) {
  	if (window.diables) {
  	  for (var i = 0; i < window.diables.length; ++i) {
  	  	$table.bootstrapTable('removeByUniqueId', window.diables[i]);
  	  }
  	}
  })

  $table.on('check.bs.table uncheck.bs.table ' +
            'check-all.bs.table uncheck-all.bs.table', function () {
        console.log('selection length: ' + $table.bootstrapTable('getSelections').length)
        $detectall.prop('disabled', !$table.bootstrapTable('getSelections').length);
        window.selections = getIdSelections();
    });
    $table.on('all.bs.table', function (e, name, args) {
        // console.log(name, args);
    });
    $detectall.click(function () {
        var ids = getIdSelections();
        var len = ids.length;
        if (len <= 0) {
        	console.log("no choice..");
        	$.message({message: i18n.t("noChoice"), type: 'warning'});
        	return;
        }
        console.log('开始检测,', ids)
        $detectall.prop('disabled', true);
        // 这里进行对每一行进行遍历并检测
        var index = 0;
        var curId = ids[index];
        var row = $table.bootstrapTable('getRowByUniqueId', curId);
       	detectNow(row, index, doLoop);
       	function doLoop (row, i) {
       		if (++i < len ) {
       			detectNow($table.bootstrapTable('getRowByUniqueId', ids[i]), i, doLoop);	
       		} else {
       			setTimeout(function() {
       				$detectall.prop('disabled', false);
       			}, 1000);
       		}
       	}
        
    });

    function getIdSelections() {
      return $.map($table.bootstrapTable('getSelections'), function (row) {
          return row.id
      });
    }

    // 切换语言事件绑定
    $selelang.find('.dropdown-menu li').on('click', function(e) {
      var $this = $(this)
      var idx = $this.index()
      console.log(idx)
      
      refreshI18n(parseInt(idx) + 7)
    })
}

/**
 * 7: 简体中文
 * 8: 英文
 * 9: 繁体中文
 */
function initLocale(callback) {
  window.current_locale_id = detectLanguage;
  window.locale_map = {'7': 'zh-CN', '8': 'en-US', '9': 'zh-TW'}
  var target_locale = window.locale_map[window.current_locale_id]
  var i18nOption = {
    lng: target_locale,
    ns: 'index',
    resGetPath: 'locale/__lng__/__ns__.json'
  };
  i18n.init(i18nOption, function(err, t) {
      $("#container").i18n();
      $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales[target_locale])
      callback && callback()
  });
}

function refreshI18n(locale_id) {
  window.current_locale_id = locale_id
  var target_locale = window.locale_map[window.current_locale_id]
  i18n.setLng(target_locale, {
      ns: 'index',
      resGetPath: 'locale/__lng__/__ns__.json'
  }, function() {
      $("#container").i18n();
      $('#table').bootstrapTable('changeLocale', target_locale);
      $('#table').bootstrapTable('changeTitle', {
      	keywords: i18n.t('col0'),
      	result: i18n.t('col1'),
      	resolution: i18n.t('col2'),
      	operate: i18n.t('col3')
      });
  });
}

function getScript(url, callback) {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.src = url;

  var done = false;
  script.onload = script.onreadystatechange = function() {
      if (!done && (!this.readyState ||
              this.readyState == 'loaded' || this.readyState == 'complete')) {
          done = true;
          if (callback)
              callback();

          script.onload = script.onreadystatechange = null;
      }
  };

  head.appendChild(script);

  return undefined;
}

function updateByResult(index, row, result, resolution) {
	$('#table').bootstrapTable('updateRow', index, $.extend(row, {'result': result, 'resolution': resolution}))
}

function detectNow(row, index, callback) {
	console.log('detectNow...' + index);
	updateByResult(index, row, "<img src='lib/img/loading.gif'/>", "");
	if (window.ClientFuns && window.ClientFuns[row.id]) {
        window.ClientFuns[row.id](row, function(result, resolution) {
        	// 客户端检测通过,再检测服务端
        	if (resolution === '' && row.api) {
        		detectApi(row, index, callback)
        	} else {
        		updateByResult(index, row, result, resolution)
        		callback && callback(row, index)
        	}
        })
      } else {
      	console.warn('没有定义客户端检测接口...' + index);
      	detectApi(row, index, callback)
      }
      function detectApi(row, index, callback) {
      	// 定义了api接口
	      if (row.api) {
	        // alert('server api test!')
	        if(window.ApiUrl) {
	          // 服务端异常的情况下,ajax超时没有效果
	          var timerId = setTimeout(function() {
	          	updateByResult(index, row, i18n.t("checkTimeout"), i18n.t("tryLater"));
	          }, 30000);
	          var ajaxInstance = $.ajax({
	          	url:window.ApiUrl + row.api,
			   timeout : 30000,
			   type : 'post',
			   dataType:'json',
			   success:function(res){
			    console.log("res ok!", res)
			           clearTimeout(timerId);
			           var result = res.result;
			           var resolution = res.resolution;
			           updateByResult(index, row, result, resolution)
			           callback && callback(row, index);
			   },
			   complete : function(XMLHttpRequest,status){
			    if(status=='timeout'){
                      ajaxInstance.abort();
                      updateByResult(index, row, i18n.t("checkTimeout"), i18n.t("tryLater"));
                      callback && callback(row, index);
			      }
			   }
	          });
	        } else {
	        	throw new Error("没有定义api 访问地址");
	        }
	      } else {
	      	console.warn('没有定义服务端检测接口...' + index);
	      	callback && callback(row, index);
	      }
      }
}

window.operateEvents = {
  'click .detect': function (e, value, row, index) {
      // alert('You click like action, row: ' + JSON.stringify(row));
      detectNow(row, index);
  }
};