One Hat Cyber Team
  • Dir : ~/www/server/panel/BTPanel/static/vite/oldjs/
  • Edit File: tools.js
    '; break; case 'select': var options = config.options, optionsHtml = ''; for (var i = 0; i < options.length; i++) { var item = options[i], newItem = item; if (typeof item === 'string') newItem = { label: item, value: item }; optionsHtml += ''; } $form = ''; break; case 'text': $form = ''; break; } $form = $($form); $form.width(config.width || '100%').attr(props); if (!config.on) config.on = {}; for (var onKey in config.on) { (function (onKey) { $form.on(onKey, function (ev) { config.on[onKey].apply(this, [ev, $(this).val()]); }); })(onKey); } return $form; }, /** * @description 渲染表单行组 * @param {object} el 配置参数 * @param {object} config 配置参数 * @param {object|undefined} formData 表单数据 */ fromGroup: function (el, config, formData) { var $el = $(el), lineList = {}; for (var i = 0; i < config.length; i++) { var item = config[i]; if (item.type === 'tips') { $el.append(this.help(item)); } else { var line = this.line(item); if (typeof formData != 'undefined') line.$form.val(formData[item.name] || ''); lineList[line.$form.attr('name')] = line; $el.append(line.$line); } } return lineList; }, /** * @description 渲染Form表单 * @param {*} config * @return 当前实例对象 */ form: function (config) { var _that = this; function ReaderForm(config) { this.config = config; this.el = config.el; this.submit = config.submit; this.data = config.data || {}; this.$load(); } ReaderForm.prototype = { element: null, style_list: [], // 样式列表 event_list: {}, // 事件列表,已绑定事件 event_type: ['click', 'event', 'focus', 'keyup', 'blur', 'change', 'input'], hide_list: [], form_element: {}, form_config: {}, random: bt.get_random(5), $load: function () { var that = this; if (this.el) { $(this.el).html(this.$reader_content()); if ($('#editCrontabForm .bt_multiple_select_updown').length > 0) { var height = $('#editCrontabForm .bt_multiple_select_updown').parent().height(); $('#editCrontabForm .line:eq(3) .tname').css({ height: height + 'px', 'line-height': height + 'px', }); } this.$event_bind(); } }, /** * @description 渲染Form内容 * @param {Function} callback 回调函数 */ $reader_content: function (callback) { var that = this, html = '', _content = ''; $.each(that.config.form, function (index, item) { if (item.separate) { html += '
    ' + item.separate + '
    '; } else { html += that.$reader_content_row(index, item); } }); that.element = $('' + html + '
    '); _content = $('
    '); _content.append(that.element); if (callback) callback(); return _content[0].outerHTML; }, /** * @description 渲染行内容 * @param {object} data Form数据 * @param {number} index 下标 * @return {string} HTML结构 */ $reader_content_row: function (index, data) { try { var that = this, help = data.help || false, labelWidth = data.formLabelWidth || this.config.formLabelWidth; if (data.display === false) return ''; return ( '
    ' + (typeof data.label !== 'undefined' ? '' + (typeof data.must !== 'undefined' && data.must != '' ? '' + data.must + '' : '') + data.label + '' : '') + '
    ' + that.$reader_form_element(data.group, index) + (help ? '
    ' + help.list.join('
    ') + '
    ' : '') + '
    ' + '
    ' ); } catch (error) { console.log(error); } }, /** * @description 渲染form类型 * @param {object} data 表单数据 * @param {number} index 下标 * @return {string} HTML结构 */ $reader_form_element: function (data, index) { var that = this, html = ''; if (!Array.isArray(data)) data = [data]; $.each(data, function (key, item) { item.find_index = index; html += that.$reader_form_find(item); that.form_config[item.name] = item; }); return html; }, /** * @descripttion 渲染单个表单元素 * @param {Object} item 配置 * @return: viod */ $reader_form_find: function (item) { var that = this, html = '', style = that.$reader_style(item.style) + _that.$verify(item.width, 'width', 'style'), attribute = that.$verify_group(item, ['name', 'placeholder', 'disabled', 'readonly', 'autofocus', 'autocomplete', 'min', 'max']), event_group = that.$create_event_config(item), eventName = '', index = item.find_index; if (item.display === false) return html; html += item.label ? '' + item.label + '' : ''; if (typeof item['name'] !== 'undefined') { that.$check_event_bind(item.name, event_group); } html += '
    '; var _value = typeof that.data[item.name] !== 'undefined' && that.data[item.name] != '' ? that.data[item.name] : item.value || ''; switch (item.type) { case 'text': // 文本选择 case 'checkbox': // 复选框 case 'password': // 密码 case 'radio': // 单选框 case 'number': // 数字 var _event = 'event_' + item.name + '_' + that.random; switch (item.type) { case 'checkbox': // 复选框 html += ''; if (typeof item.disabled != 'undefined' && item.disabled) { //禁止复选框 同时可设置class:'check_disabled',使鼠标手为禁止状态 } else { that.$check_event_bind(_event + '_label', { click: { type: 'checkbox_icon', config: item }, }); that.$check_event_bind(_event, { input: { type: 'checkbox', config: item, event: item.event, }, }); } break; case 'radio': $.each(item.list, function (keys, rItem) { var radioRandom = _event + '_radio_' + keys; html += ''; that.$check_event_bind(radioRandom, { input: { type: 'radio', config: item, event: item.event } }); }); break; default: html += ''; break; } if (item.btn && !item.disabled) { html += '' + item.btn.title + ''; if (typeof item.btn.event !== 'undefined') { that.$check_event_bind(item.name + '_btn', { click: { config: item, event: item.btn.event, }, }); } } if (item.icon) { html += ''; if (typeof item.icon.event !== 'undefined') { that.$check_event_bind(item.name + '_icon', { click: { type: 'select_path', select: item.icon.select || '', config: item, children: '.' + item.name + '_icon', event: item.icon.event, callback: item.icon.callback, }, }); } } break; case 'textarea': html += ''; $.each(['blur', 'focus', 'input'], function (index, items) { if (item.tips) { var added = null, event = {}; switch (items) { case 'blur': added = function (ev, item, element) { if ($(this).val() === '') $(this).next().show(); layer.close(item.tips.loadT); $(ev.target).data('layer', ''); }; break; case 'focus': added = function (ev, item) { $(this).next().hide(); item.tips.loadT = layer.tips(tips, $(this), { tips: [1, '#20a53a'], time: 0, area: $(this).width(), }); }; break; } } that.event_list[item.name][items] ? (that.event_list[item.name][items]['added'] = added) : (that.event_list[item.name][items] = { type: item.type, cust: false, event: item[items], added: added, }); }); if (item.tips) { var tips = ''; if (typeof item.tips.list === 'undefined') { tips = item.tips.text; } else { tips = item.tips.list.join('
    '); } html += '
    ' + tips + '
    '; that.$check_event_bind(item.name + '_tips', { click: { type: 'textarea_tips', config: item, }, }); } break; case 'multipleSelect': // 使用规则 【配置中必须含有value字段(无需默认值设置空数组)、需要选中的下拉项以数组逗号隔开】 html += that.$reader_multipleSelect(item, style, attribute, index); that.$check_event_bind('custom_select', { click: { type: 'custom_select', children: '.bt_select_value', }, }); that.$check_event_bind('custom_select_item', { click: { type: 'custom_select_item', children: 'li.item', }, }); that.$check_event_bind('icon_trem_close', { click: { type: 'icon_trem_close', children: '.icon-trem-close', }, }); break; case 'secondaryMenu': //下拉二级菜单 html += that.$reader_secondaryMenu(item, style, attribute, index); that.$check_event_bind('secondary_menu_parent', { 'mouseover click': { type: 'secondary_menu_parent', children: '.item-parent', }, }); that.$check_event_bind('secondary_menu_child', { click: { type: 'secondary_menu_child', children: '.item-child', }, }); break; case 'select': html += that.$reader_select(item, style, attribute, index); that.$check_event_bind('custom_select', { click: { type: 'custom_select', children: '.bt_select_value', }, }); that.$check_event_bind('custom_select_item', { click: { type: 'custom_select_item', children: 'li.item', }, }); break; case 'link': eventName = 'event_link_' + that.random + '_' + item.name; html += '' + item.title + ''; that.$check_event_bind(eventName, { click: { type: 'link_event', event: item.event, }, }); break; case 'button': html += // ''; break; case 'help': var _html = ''; $.each(item.list, function (index, items) { _html += '
  • ' + items + '
  • '; }); html += ''; break; case 'other': html += item.boxcontent; } html += item.unit ? '' + item.unit + '' : ''; html += item.suffix ? '' + item.suffix + '' : ''; html += '
    '; return html; }, /** * @descripttion 检测检测名称 * @param {string} eventName 配置 * @param {object} config 事件配置 */ $check_event_bind: function (eventName, config) { if (!this.event_list[eventName]) { if (!this.event_list.hasOwnProperty(eventName)) { this.event_list[eventName] = config; } } }, /** * @description 创建事件配置 * @param {object} item 行内配置 * @return {object} 配置信息 */ $create_event_config: function (item) { var config = {}; if (typeof item['name'] === 'undefined') return {}; $.each(this.event_type, function (key, items) { if (item[items]) { config[items === 'event' ? 'click' : items] = { type: item.type, event: item[items], cust: ['select', 'checkbox', 'radio'].indexOf(item.type) > -1, config: item, }; } }); return config; }, /** * @description 渲染样式 * @param {object|string} data 样式配置 * @return {string} 样式 */ $reader_style: function (data) { var style = ''; if (typeof data === 'string') return data; if (typeof data === 'undefined') return ''; $.each(data, function (key, item) { style += key + ':' + item + ';'; }); return style; }, /** * @descripttion 局部刷新form表单元素 * @param {String} name 需要刷新的元素 * @param {String} name 元素新数据 * @return: viod */ $local_refresh: function (name, config) { var formFind = this.element.find('[data-name=' + name + ']'); if (this.element.find('[data-name=' + name + ']').length === 0) formFind = this.element.find('[name=' + name + ']'); formFind.parent().replaceWith(this.$reader_form_find(config)); }, /** * @description 渲染下拉,内容方法 */ $reader_select: function (item, style, attribute, index) { var that = this, list = '', option = '', active = {}; if (typeof item.list === 'function') { var event = item.list; event.call(this, this.config.form); item.list = []; } if (!Array.isArray(item.list)) { var config = item.list; bt_tools.send( { url: config.url, data: config.param || config.data || {}, }, function (res) { if (res.status !== false) { var list = item.list.dataFilter ? item.list.dataFilter(res, that) : res; if (item.list.success) item.list.success(res, that, that.config.form[index], list); item.list = list; if (!item.list.length) { item.disabled = true; layer.msg(item.placeholder || '数据获取为空', { icon: 2 }); } that.$replace_render_content(index); } else { bt.msg(res); } } ); return false; } if (typeof that.data[item.name] === 'undefined') active = item.list[0]; $.each(item.list, function (key, items) { if (items.value === item.value || items.value === that.data[item.name]) { active = items; return false; } }); $.each(item.list, function (key, items) { list += '
  • ' + items.title + '
  • '; option += ''; }); var title = !Array.isArray(item.list) ? 'Getting data...' : active ? active.title : item.placeholder; return ( '
    ' + '' + (title || item.placeholder) + '' + '' + '' + (option || '') + '' + '
    ' ); }, /** * @description 渲染多选下拉,内容方法 */ $reader_multipleSelect: function (item, style, attribute, index) { var that = this, list = '', option = '', active = {}, mulpActive = [], str = ''; if (typeof item.list === 'function') { var event = item.list; event.call(this, this.config.form); item.list = []; } if ($.isArray(item.value)) { mulpActive = item.value; } else { if (!Array.isArray(item.list)) { var config = item.list; bt_tools.send( { url: config.url, data: config.param || config.data || {}, }, function (res) { if (res.status !== false) { var list = item.list.dataFilter ? item.list.dataFilter(res, that) : res; if (item.list.success) item.list.success(res, that, that.config.form[index], list); item.list = list; if (!item.list.length) { item.disabled = true; layer.msg(item.placeholder || '数据获取为空', { icon: 2 }); } that.$replace_render_content(index); } else { bt.msg(res); } } ); return false; } if (typeof that.data[item.name] === 'undefined') active = item.list[0]; $.each(item.list, function (key, items) { if (items.value === item.value || items.value === that.data[item.name]) { active = items; return false; } }); } $.each(item.list, function (key, items) { if ($.isArray(item.value)) { for (var i = 0; i < mulpActive.length; i++) { if (mulpActive.indexOf(items.value) > -1) { active.value = items.value; } } } list += '
  • \ ' + items.title + '\ \
  • '; option += ''; }); for (var i = 0; i < item.list.length; i++) { if (mulpActive.indexOf(item.list[i].value) > -1) { str += '' + item.list[i].title + ''; } } var title = !Array.isArray(item.list) ? '获取数据中' : active ? active.title : item.placeholder; return ( '
    ' + '' + (item.value.length == 0 ? '' + (title || item.placeholder) + '' : str) + '
    Created with Pixso.
    \
    ' + '' + '' + (option || '') + '' + '
    ' + '
    ' ); }, /** * @description 渲染二级下拉 */ $reader_secondaryMenu: function (item, style, attribute, index) { // 规则限制 【通过配置中的data.xx值设置为空,可清除上次选中的内容】 // 1.不可通过请求数据来渲染 // 2.至少有一个一级内容,一级下拉不可点击 var that = this, list = '', active = {}; $.each(item.list, function (key, items) { list += '
  • ' + items.title + '
    ' + (function () { var _con = ''; if (items.child.length > 0) { _con = '\ \ \t\ \t\t\tCreated with Pixso.\ \t\ \t\ \t\
    \
      ' + (function () { var str = ''; $.each(items.child, function (key, child) { str += '
    • ' + child.title + '
    • '; }); return str; })() + '
    '; } else { _con = '[空]'; } return _con; })() + '
  • '; }); return ( '
    \ ' + (!$.isEmptyObject(active) ? active.title : item.placeholder) + '\
    Created with Pixso.
    \
    \ \ \
    \
    ' ); }, /** * @description 替换渲染内容 */ $replace_render_content: function (index) { var that = this, config = this.config.form[index], html = that.$reader_content_row(index, config); $('[data-form=' + that.random + ']') .find('.line:eq(' + index + ')') .replaceWith(html); this.$event_bind(); }, /** * @description 重新渲染内容 * @param {object} formConfig 配置 */ $again_render_form: function (formConfig) { var formElement = $('[data-form=' + this.random + ']'), that = this; formConfig = formConfig || this.config.form; formElement.empty(); for (var i = 0; i < formConfig.length; i++) { var config = formConfig[i]; if (config.display === false) continue; formElement.append(that.$reader_content_row(i, config)); } this.config.form = formConfig; this.$event_bind(); // 处理复选框重新渲染第一次点击无效 formElement.find('.form-checkbox-label').click(); formElement.find('.form-checkbox-label').click(); }, /** * @description 事件绑定功能 * @param {Object} eventList 事件列表 * @param {Function} callback 回调函数 * @return void */ $event_bind: function (eventList, callback) { var that = this, _event = {}; that.element = $(typeof eventList === 'object' ? that.element : '[data-form=' + that.random + ']'); _event = eventList; if (typeof eventList === 'undefined') _event = that.event_list; $.each(_event, function (key, item) { if ($.isEmptyObject(item)) return true; $.each(item, function (keys, items) { if (!!item.type) return false; if (!items.hasOwnProperty('bind')) { items.bind = true; } else { return false; } var childNode = ''; if (typeof items.cust === 'boolean') { childNode = '[' + (items.cust ? 'data-' : '') + 'name=' + key + ']'; } else { childNode = '.' + key; } (function (items, key) { if (items.onEvent === false) { switch (items.type) { case 'input_checked': $(childNode).on(keys != 'event' ? keys : 'click', function (ev) { items.event.apply(this, [ev, that]); }); break; } return true; } else { if (items.type === 'select') return true; that.element.on(keys !== 'event' ? keys : 'click', items.children ? items.children : childNode, function (ev) { var form = that.$get_form_element(true), config = that.form_config[key]; switch (items.type) { case 'textarea_tips': $(this).hide().prev().focus(); break; case 'custom_select': if ($(this).parent().hasClass('bt-disabled')) return false; var select_value = $(this).next(); if (!select_value.hasClass('show')) { // var $target = $(ev.currentTarget); // var $layer = $target.parents('.layui-layer'); // var layerTop = $layer.length > 0 ? parseFloat($layer.css('top')) : 0; // var layerLeft = $layer.length > 0 ? parseFloat($layer.css('left')) : 0; // var offset = $target[0].getBoundingClientRect(); // var top = offset.top - layerTop + offset.height + 2; // var left = offset.left - layerLeft; // $('.bt_select_list').css({ // position: 'fixed', // width: offset.width + 'px', // top: top + 'px', // left: left + 'px', // }); $('.bt_select_list').removeClass('show'); select_value.addClass('show'); } else { select_value.removeClass('show'); } $(document).click(function () { that.element.find('.bt_select_list').removeClass('show'); $(this).unbind('click'); return false; }); return false; break; case 'custom_select_item': config = that.form_config[$(this).parents('.bt_select_updown').attr('data-name')]; var item_config = config.list[$(this).index()]; var item = $(this).parent().find('.item'), arry = [], _html = '', mulpVal = []; if ($(this).hasClass('disabled')) { $(this).parent().removeClass('show'); if (item_config.tips) layer.msg(item_config.tips, { icon: 2 }); return true; } if (!$(this).hasClass('active') && !$(this).hasClass('disabled')) { var value = item_config.value.toString(); $(this).parent().prev().find('.bt_select_content').text($(this).text()); $(this).parent().prev().find('.bt_select_content').prop('title', $(this).text()); if (config.type != 'multipleSelect') { $(this).addClass('active').siblings().removeClass('active'); $(this).parent().next().val(value); $(this).parent().slideUp('fast'); $(this).parent().removeClass('show'); $('.bt_select_list_arrow').fadeOut(200); $('.bt_select_list_arrow_fff').fadeOut(200); } else { $(this).addClass('active'); } } else { if (config.type == 'multipleSelect') { // if($(this).parent().find('.active').length <= 1) return layer.msg('最少选择一个!!!') $(this).removeClass('active'); } } if (config.type == 'multipleSelect') { for (var i = 0; i < item.length; i++) { if (item.eq(i).hasClass('active')) { arry.push(item.eq(i).text().trim().replace(/\s/g, '')); } } for (var i = 0; i < config.list.length; i++) { if (arry.indexOf(config.list[i].title.trim().replace(/\s/g, '')) > -1) { mulpVal.push(config.list[i].value); } } if (arry.length == 0) { _html += '' + config.placeholder + ''; } else { $(this).parent().prev().find('.bt_select_content_def').remove(); for (var i = 0; i < arry.length; i++) { _html += '' + arry[i] + ''; } } $(this).parent().prev().find('.bt_select_content').remove(); $(this).parent().prev().find('.icon-down').before(_html); $(this).parent().next().val(mulpVal); var height = $(this).parent().parent().parent().height(); $(this) .parent() .parent() .parent() .parent() .siblings() .css({ height: height + 'px', 'line-height': height + 'px', }); $(this) .parent() .css('top', height + 12 + 'px'); $('.bt_select_list_arrow_fff').css('top', height - 3 + 'px'); $('.bt_select_list_arrow').css('top', height - 4 + 'px'); } $('.icon-trem-close').click(function () { var str = $(this).siblings().text().trim().replace(/\s/g, ''); for (var i = 0; i < item.length; i++) { if (str == item.eq(i).prop('title')) { item.eq(i).click(); } } return false; }); that.data[config.name] = config.type == 'multipleSelect' ? mulpVal : value; if (items.event) items.event = null; if (config.change) items.event = config.change; ev.stopPropagation(); break; case 'icon_trem_close': var str = $(this).siblings().text().trim().replace(/\s/g, ''), item = $(this).parent().parent().siblings('.bt_select_list').find('.item'); for (var i = 0; i < item.length; i++) { if (str == item.eq(i).prop('title')) { item.eq(i).click(); } } return false; break; case 'secondary_menu_parent': $('.item-menu-title').removeAttr('style'); $(this).addClass('down').siblings().removeClass('down').find('.item-menu-body-list').removeClass('show'); $(this).siblings().children('svg').css('fill', '#999999'); $('.down').children('svg').css('fill', '#666666'); if ($(this).find('.item-menu-body-list').length > 0) { $(this).find('.item-menu-body-list').addClass('show').parent().siblings().find('.item-menu-body-list').removeClass('show'); } ev.stopPropagation(); break; case 'secondary_menu_child': var _value = $(this).attr('data-value'); config = that.form_config[$(this).parents('.bt_select_updown').attr('data-name')]; that.data[config.name] = _value; if (items.event) items.event = null; if (config.change) items.event = config.change; ev.stopPropagation(); break; case 'select_path': bt.select_path('event_' + $(this).prev().attr('name') + '_' + that.random, items.select || '', !items.callback || items.callback.bind(that), items.defaultPath || ''); break; case 'checkbox': var checked = $(this).is(':checked'); if (checked) { $(this).prev().addClass('active'); } else { $(this).prev().removeClass('active'); } break; } if (items.event) items.event.apply(this, [that.$get_form_value(), form, that, config, ev]); // 事件 if (items.added) items.added.apply(this, [ev, config, form]); }); } })(items, key); }); }); if (callback) callback(); }, /** * @description 获取表单数据 * @return {object} 表单数据 */ $get_form_value: function () { var form = {}, ev = this.element; ev.find('input,textarea[disabled="disabled"]').each(function (index, item) { var val = $(this).val(); if ($(this).attr('type') === 'checkbox') { val = $(this).prop('checked'); } if ($(this).attr('type') === 'radio') { val = ev.find('input[name=' + $(this).attr('name') + ']:radio:checked').val(); } form[$(this).attr('name')] = val; }); return $.extend({}, ev.serializeObject(), form); }, /** * @description 设置指定数据 * */ $set_find_value: function (name, value) { var config = {}, that = this; typeof name != 'string' ? (config = name) : (config[name] = value); $.each(config, function (key, item) { that.form_element[key].val(item); }); }, /** * @description 获取Form,jquery节点 * @param {Boolean} afresh 是否强制刷新 * @return {object} */ $get_form_element: function (afresh) { var form = {}, that = this; if (afresh || $.isEmptyObject(that.form_element)) { this.element.find(':input').each(function (index) { form[$(this).attr('name')] = $(this); }); that.form_element = form; return form; } else { return that.form_element; } }, /** * @description 验证值整个列表是否存在,存在则转换成属性字符串格式 */ $verify_group: function (config, group) { var that = this, str = ''; $.each(group, function (index, item) { if (typeof config[item] === 'undefined') return true; if (['disabled', 'readonly'].indexOf(item) > -1) { str += ' ' + (config[item] ? item + '="' + item + '"' : ''); } else { str += ' ' + item + '="' + config[item] + '"'; } }); return str; }, /** * @description 验证绑定事件 * @param {String} value */ $verify_bind_event: function (eventName, row, group) { var event_list = {}; $.each(group, function (index, items) { var event_fun = row[items]; if (event_fun) { if (typeof event_list[eventName] === 'object') { if (!Array.isArray(event_list[eventName])) event_list[eventName] = [event_list[eventName]]; event_list[eventName].push({ event: event_fun, eventType: items, }); } else { event_list[eventName] = { event: event_fun, eventType: items, }; } } }); return event_list; }, /** * @description 验证值是否存在 * @param {String} value 内容/值 * @param {String|Boolean} attr 属性 * @param {String} type 属性 */ $verify: function (value, attr, type) { if (!value) return ''; if (type === true) return value ? ' ' + attr : ''; if (type === 'style') return attr ? attr + ':' + value + ';' : value; return attr ? ' ' + attr + '="' + value + '"' : ' ' + value; }, /** * @description 验证form表单 */ $verify_form: function () { var form_list = {}, form = this.config.form, form_value = this.$get_form_value(), form_element = this.$get_form_element(true), is_verify = true; for (var key = 0; key < form.length; key++) { var item = form[key]; if (!Array.isArray(item.group)) item.group = [item.group]; if (item.separate) continue; for (var i = 0; i < item.group.length; i++) { var items = item.group[i], name = items.name; if (items.type === 'help') continue; if (typeof items.verify == 'function') { var is_verify = items.verify(form_value[name], form_element[name], items, true); is_verify = typeof is_verify == 'boolean' ? false : true; } } } if (!is_verify) return is_verify; return form_value; }, /** * @description 提交内容,需要传入url * @param {Object|Function} param 附加参数或回调函数 * @param {Function} callback 回调 */ $submit: function (param, callback, tips) { var form = this.$verify_form(); if (typeof param === 'function') (tips = callback), (callback = param), (param = {}); if (!form) return false; form = $.extend(form, param); if (typeof this.config.url == 'undefined') { bt_tools.msg('Request Submission address cannot be empty!', false); return false; } bt_tools.send( { url: this.config.url, data: form, }, function (res) { if (callback) { callback(res, form); } else { bt_tools.msg(res); } }, tips || 'Submit' ); }, }; return new ReaderForm(config); }, /** * @description tab切换,支持三种模式 * @param {object} config * @return 当前实例对象 */ tab: function (config) { var _that = this; function ReaderTab(config) { this.config = config; this.theme = this.config.theme || {}; this.$load(); } ReaderTab.prototype = { type: 1, theme_list: [ { content: 'tab-body', nav: 'tab-nav', body: 'tab-con', active: 'on', }, { content: 'bt-w-body', nav: 'bt-w-menu', body: 'bt-w-con', }, ], random: bt.get_random(5), $init: function () { var that = this, active = this.config.active, config = that.config.list, _theme = {}; this.$event_bind(); if (config[that.active].success) config[that.active].success(); config[that.active]['init'] = true; }, $load: function () { var that = this; }, $reader_content: function () { var that = this, _list = that.config.list, _tab = '', _tab_con = '', _theme = that.theme, config = that.config; if (typeof that.active === 'undefined') that.active = 0; if (!$.isEmptyObject(config.theme)) { _theme = this.theme_list[that.active]; $.each(config.theme, function (key, item) { if (_theme[key]) _theme[key] += ' ' + item; }); that.theme = _theme; } if (config.type && $.isEmptyObject(config.theme)) this.theme = this.theme_list[that.active]; $.each(_list, function (index, item) { var active = that.active === index, _active = _theme['active'] || 'active'; _tab += '' + item.title + ''; _tab_con += '
    ' + (active ? item.content : '') + '
    '; }); that.element = $( '
    ' + _tab + '
    ' + _tab_con + '
    ' ); return that.element[0].outerHTML; }, /** * @description 事件绑定 * */ $event_bind: function () { var that = this, _theme = that.theme, active = _theme['active'] || 'active'; if (!that.el) that.element = $('#tab_' + that.random); that.element.on('click', '.' + _theme['nav'].replace(/\s+/g, '.') + ' span', function () { var index = $(this).index(), config = that.config.list[index]; $(this).addClass(active).siblings().removeClass(active); $('#tab_' + that.random + ' .' + _theme['body'] + '>div:eq(' + index + ')') .addClass(active) .siblings() .removeClass(active); that.active = index; if (!config.init) { // console.log(_theme) var contentItem = $('#tab_' + that.random + ' .' + _theme['body'] + '>div:eq(' + index + ')'); contentItem.html(config.content); if (config.success) config.success(contentItem); config.init = true; } }); }, }; return new ReaderTab(config); }, /** * @description loading过渡 * @param {*} title * @param {*} is_icon * @return void */ load: function (title) { var random = bt.get_random(5), layel = $( '
    ' + title + ',please wait...
    ' ), mask = '', loadT = ''; $('body').append(layel); var win = $(window), msak = $('.layer-loading-mask'), layel = $('#' + random); layel.css({ top: (win.height() - 64) / 2, left: (win.width() - 320) / 2 }); if (title === true) loadT = layer.load(); return { close: function () { if (typeof loadT == 'number') { layer.close(loadT); } else { $('body') .find('#' + random + ',#layer-mask-' + random) .remove(); } }, }; }, /** * @description 弹窗方法,有默认的参数和重构的参数 * @param {object} config 和layer参数一致 * @require 当前关闭弹窗方法 */ open: function (config) { var _config = {}, layerT = null, form = null; _config = $.extend({ type: 1, area: '640px', closeBtn: 2, btn: ['Yes', 'No'] }, config); if (typeof _config.content == 'object') { var param = _config.content; form = bt_tools.form(param); _config.success = function (layero, indexs) { form.$event_bind(); if (typeof config.success != 'undefined') config.success(layero, indexs); }; _config.yes = function (indexs, layero) { var form_val = form.$verify_form(); if (!form_val) return false; if (typeof config.yes != 'undefined') { var yes = config.yes.apply(form, [form_val, indexs, layero]); if (!yes) return false; } }; _config.content = form.$reader_content(); } layerT = layer.open(_config); return { close: function () { layer.close(layerT); }, form: form, }; }, /** * @description 封装msg方法 * @param {object|string} param1 配置参数,请求方法参数 * @param {number} param2 图标ID * @require 当前关闭弹窗方法 */ msg: function (param1, param2) { var layerT = null, msg = '', config = {}; if (typeof param1 === 'object') { if (typeof param1.status === 'boolean') { (msg = param1.msg), (config = { icon: param1.status ? 1 : 2 }); if (!param1.status) config = $.extend(config, { time: !param2 ? 0 : 3000, closeBtn: 2, shade: 0.3 }); } } if (typeof param1 === 'string') { (msg = param1), (config = { icon: typeof param2 !== 'undefined' ? param2 : 1, }); } layerT = layer.msg(msg, config); return { close: function () { layer.close(layerT); }, }; }, /** * @description 成功提示 * @param {string} msg 信息 */ success: function (msg) { this.msg({ msg: msg, status: true }); }, /** * @description 错误提示 * @param {string} msg 信息 */ error: function (msg) { this.msg({ msg: msg, status: false }); }, /** * @description 请求封装 * @param {string|object} conifg ajax配置参数/请求地址 * @param {function|object} callback 回调函数/请求参数 * @param {function} callback1 回调函数/可为空 * @returns void 无 */ send: function (param1, param2, param3, param4, param5, param6) { var params = {}, success = null, error = null, config = [], param_one = ''; $.each(arguments, function (index, items) { config.push([items, typeof items]); }); function diff_data(i) { try { success = config[i][1] == 'function' ? config[i][0] : null; error = config[i + 1][1] == 'function' ? config[i + 1][0] : null; } catch (error) {} } param_one = config[0]; switch (param_one[1]) { case 'string': $.each(config, function (index, items) { var value = items[0], type = items[1]; if (index > 1 && (type == 'boolean' || type == 'string' || type == 'object')) { var arry = param_one[0].split('/'); params['url'] = '/' + arry[0] + '?action=' + arry[1]; if (type == 'object') { params['load'] = value.load; params['verify'] = value.verify; if (value.plugin) params['url'] = '/plugin?action=a&name=' + arry[0] + '&s=' + arry[1]; } else if (type == 'string') { params['load'] = value; } return false; } else { params['url'] = param_one[0]; } }); if (config[1][1] === 'object') { params['data'] = config[1][0]; diff_data(2); } else { diff_data(1); } break; case 'object': params['url'] = param_one[0].url; params['data'] = param_one[0].data || {}; $.each(config, function (index, items) { var value = items[0], type = items[1]; if (index > 1 && (type == 'boolean' || type == 'string' || type == 'object')) { switch (type) { case 'object': params['load'] = value.load; params['verify'] = value.verify; break; case 'string': params['load'] = value; break; } return true; } }); if (config[1][1] === 'object') { params['data'] = config[1][0]; diff_data(2); } else { diff_data(1); } break; } if (params.load) params.load = this.load(params.load); $.ajax({ type: params.type || 'POST', url: params.url, data: params.data || {}, dataType: params.dataType || 'JSON', complete: function (res) { if (params.load) params.load.close(); }, success: function (res) { if (typeof params.verify == 'boolean' && !params.verify) { if (success) success(res); return false; } if (typeof res === 'string') { layer.msg(res, { icon: 2, time: 0, closeBtn: 2, }); return false; } if (params.batch) { if (success) success(res); return false; } if (res.status === false && (res.hasOwnProperty('msg') || res.hasOwnProperty('error_msg'))) { if (error) { error(res); } else { bt_tools.msg({ status: res.status, msg: !res.hasOwnProperty('msg') ? res.error_msg : res.msg }); } return false; } if (params.tips) { bt_tools.msg(res); } if (success) success(res); }, }); }, /** * @description 命令行输入 */ command_line_output: function (config) { var _that = this, uuid = bt.get_random(15); /** * @description 渲染 * @param config * @return {object} * @constructor */ function ReaderCommand(config) { var that = this; for (var key in _that.commandConnectionPool) { var item = _that.commandConnectionPool[key], element = $(item.config.el); if (config.shell === item.config.shell && element.length) { item.el = element; return item; } } if (typeof config === 'undefined') config = {}; this.config = $.extend({ route: '/sock_shell' }, config); this.xterm_config = $.extend(this.xterm_config, this.config.xterm); this.el = $(this.config.el); this.open = config.open; this.close = config.close; this.message = config.message; if (!this.config.hasOwnProperty('el')) { _that.msg({ msg: '请输入选择器element,不可为空', status: false }); return false; } if (!this.config.hasOwnProperty('shell')) { _that.msg({ msg: '请输入命令,不可为空', status: false }); return false; } if (this.config.hasOwnProperty('time')) { setTimeout(function () { that.close_connect(); }, this.config.time); } this.init(); } ReaderCommand.prototype = { socket: null, //websocket 连接保持的对象 socketToken: null, timeout: 0, // 连接到期时间,为0代表永久有效 monitor_interval: 2000, element_detection: null, uuid: uuid, fragment: [], error: 0, // 错误次数,用于监听元素内容是否还存在 retry: 0, // 重试次数 forceExit: false, // 强制断开连接 /** * @description 程序初始化 */ init: function () { var oldUUID = bt.get_cookie('commandInputViewUUID'), that = this; if (!this.el[0]) { if (this.error > 10) return false; setTimeout(function () { that.init(); this.error++; }, 2000); return false; } this.error = 0; if (this.el[0].localName !== 'pre') { this.el.append('
    ');
    					this.el = this.el.find('pre');
    					this.config.el = this.config.el + ' pre';
    				} else {
    					this.el.addClass('command_output_pre');
    				}
    				if (Array.isArray(this.config.area)) {
    					this.el.css({ width: this.config.area[0], height: this.config.area[1] });
    				} else {
    					this.el.css({ width: '100%', height: '100%' });
    				}
    				if (oldUUID && typeof _that.commandConnectionPool[oldUUID] != 'undefined') {
    					_that.commandConnectionPool[oldUUID].close_connect();
    					delete _that.commandConnectionPool[oldUUID];
    				}
    				bt.set_cookie('commandInputViewUUID', this.uuid);
    				this.element_detection = setInterval(function () {
    					if (!$(that.config.el).length) {
    						clearInterval(that.element_detection);
    						that.forceExit = true;
    						that.close_connect();
    					}
    				}, 1 * 60 * 1000);
    				this.set_full_screen();
    				this.create_websocket_connect(this.config.route, this.config.shell);
    				this.monitor_element();
    			},
    			/**
    			 * @description 创建websocket连接
    			 * @param {string} url websocket连接地址
    			 * @param {string} shell 需要传递的命令
    			 */
    			create_websocket_connect: function (url, shell) {
    				var that = this;
    				this.socket = new WebSocket((location.protocol === 'http:' ? 'ws://' : 'wss://') + location.host + url);
    				this.socket.addEventListener('open', function (ev) {
    					if (!this.socketToken) {
    						var _token = document.getElementById('request_token_head').getAttribute('token');
    						this.socketToken = { 'x-http-token': _token };
    					}
    					this.send(JSON.stringify(this.socketToken));
    					this.send(shell);
    					if (that.open) that.open();
    					that.retry = 0;
    				});
    				this.socket.addEventListener('close', function (ev) {
    					if (!that.forceExit) {
    						if (ev.code !== 1000 && that.retry <= 10) {
    							that.socket = that.create_websocket_connect(that.config.route, that.config.shell);
    							that.retry++;
    						}
    						if (that.close) that.close(ev);
    					}
    				});
    				this.socket.addEventListener('message', function (ws_event) {
    					var result = ws_event.data;
    					if (!result) return;
    					that.refresh_data(result);
    					if (that.message) that.message(result);
    				});
    				return this.socket;
    			},
    
    			/**
    			 * @description 设置全屏视图
    			 */
    			set_full_screen: function () {
    				// 1
    			},
    
    			htmlEncodeByRegExp: function (str) {
    				if (str.length == 0) return '';
    				return str.replace(/&/g, '&').replace(//g, '>').replace(/ /g, ' ').replace(/\'/g, ''').replace(/\"/g, '"');
    			},
    
    			/**
    			 * @description 刷新Pre数据
    			 * @param {object} data 需要插入的数据
    			 */
    			refresh_data: function (data) {
    				var data = this.htmlEncodeByRegExp(data);
    				this.fragment.push(data);
    				if (this.fragment.length >= 300) {
    					this.fragment.splice(0, 150);
    					this.el.html(this.fragment.join(''));
    				} else {
    					this.el.append(data);
    				}
    				if (this.el.length > 0) {
    					this.el.scrollTop(this.el[0].scrollHeight);
    				}
    			},
    
    			/**
    			 * @description 监听元素状态,判断是否移除当前的ws连接
    			 *
    			 */
    			monitor_element: function () {
    				var that = this;
    				this.monitor_interval = setInterval(function () {
    					if (!that.el.length) {
    						that.close_connect();
    						clearInterval(that.monitor_interval);
    					}
    				}, that.config.monitorTime || 2000);
    			},
    
    			/**
    			 * @description 断开命令响应和websocket连接
    			 */
    			close_connect: function () {
    				this.socket.send('');
    				this.socket.close();
    				delete _that.commandConnectionPool[this.uuid];
    			},
    		};
    		this.commandConnectionPool[uuid] = new ReaderCommand(config);
    		return this.commandConnectionPool[uuid];
    	},
    
    	/**
    	 * @description 清理验证提示样式
    	 * @param {object} element  元素节点
    	 */
    	$clear_verify_tips: function (element) {
    		element.removeClass('bt-border-error bt-border-sucess');
    		layer.close('tips');
    	},
    
    	/**
    	 * @description 验证提示
    	 * @param {object} element  元素节点
    	 * @param {string} tips 警告提示
    	 * @return void
    	 */
    	$verify_tips: function (element, tips, is_error) {
    		if (typeof is_error === 'undefined') is_error = true;
    		element.removeClass('bt-border-error bt-border-sucess').addClass(is_error ? 'bt-border-error' : 'bt-border-sucess');
    		element.focus();
    		layer.tips('' + tips + '', element, {
    			tips: [1, is_error ? 'red' : '#20a53a'],
    			time: 3000,
    			area: element.width(),
    		});
    	},
    	/**
    	 * @description 验证值是否存在
    	 * @param {String} value 内容/值
    	 * @param {String|Boolean} attr 属性
    	 * @param {String} type 属性
    	 */
    	$verify: function (value, attr, type) {
    		if (!value) return '';
    		if (type === true) return value ? ' ' + attr : '';
    		if (type === 'style') return attr ? attr + ':' + value + ';' : value;
    		return attr ? ' ' + attr + '="' + value + '"' : ' ' + value;
    	},
    
    	/**
    	 * @description 批量操作的结果
    	 * @param {*} config
    	 */
    	$batch_success_table: function (config) {
    		var _that = this,
    			length = $(config.html).length;
    		bt.open({
    			type: 1,
    			title: config.title,
    			area: config.area || ['400px'],
    			shadeClose: false,
    			closeBtn: 2,
    			content:
    				config.content ||
    				'
    ' + config.title + ' ' + lan['public'].success + '
    ' + config.html + '
    ' + config.th + '' + lan['public'].result + '
    ', success: function () { if (length > 4) _that.$fixed_table_thead('.fiexd_thead'); }, }); }, /** * @description 固定表头 * @param {string} el DOM选择器 * @return void */ $fixed_table_thead: function (el) { $(el).scroll(function () { var scrollTop = this.scrollTop; this.querySelector('thead').style.transform = 'translateY(' + scrollTop + 'px)'; }); }, /** * @description 插件视图设置 * @param {object|string} layid dom元素或layer_id * @param {object} config 插件宽度高度或其他配置 */ $piugin_view_set: function (layid, config) { var element = $(typeof layid === 'string' ? '#layui-layer' + layid : layid).hide(), win = $(window); setTimeout(function () { var width = config.width || element.width(), height = config.height || element.height(); element .css( $.extend(config, { left: (win.width() - width) / 2, top: (win.height() - height) / 2, }) ) .addClass('custom_layer'); }, 50); setTimeout(function () { element.show(); }, 500); }, }; setTimeout(function () { $.fn.serializeObject = function () { var hasOwnProperty = Object.prototype.hasOwnProperty; return this.serializeArray().reduce(function (data, pair) { if (!hasOwnProperty.call(data, pair.name)) { data[pair.name] = pair.value; } return data; }, {}); }; }, 300); function arryCopy(arrys) { var list = arrys.concat(), arry = []; for (var i = 0; i < list.length; i++) { arry.push($.extend(true, {}, list[i])); } return arry; }