var _LOG = true;
function debug_log() {
if (_LOG) {
console.log(arguments[0], arguments[1] ? arguments[1] : "", arguments[2] ? arguments[2] : "", arguments[3] ? arguments[3] : "", arguments[4] ? arguments[4] : "");
}
}
var abp = abp || {};
let icon = '';
abp.ui.setBusy = function (elm, opts) {
if (!elm) {
$.blockUI(opts);
} else {
$(elm).block(opts);
}
};
abp.ui.clearBusy = function (elm, opts) {
if (!elm) {
$.unblockUI(opts);
} else {
$(elm).unblock(opts);
}
};
if (typeof jQuery === "undefined") {
throw new Error("jQuery plugins need to be before this file");
}
/*JQuery扩展*/
$.extend({
//表单赋值
formDeserialize: function ($form, data) {
//isSelect2 = isSelect2 === undefined;
if (!data) {
return;
}
let $input = $form.find('input:not([type="radio"]):not([type="checkbox"])');
let $textarea = $form.find("textarea");
let $select = $form.find("select");
let $checkbox = $form.find("input[type='checkbox']");
let $radio = $form.find("input[type='radio']");
$.merge($input, $textarea);
$input.each(function () {
let $input = $form.find($(this));
let name = $input.attr("name");
if (data.hasOwnProperty(name)) {
if ($input.hasClass('flatpickr-input')) {
$input.VbDate("setValue", data[name])
} else {
$input.val(data[name]);
}
}
});
$select.each(function () {
let $select = $form.find($(this));
let name = $select.attr("name");
if (data.hasOwnProperty(name)) {
if (typeof data[name] === "boolean") {
data[name] = data[name] + "";
}
if (data[name] !== "") {
let val = data[name];
$select.val(val);
if ($select.hasClass('ajax-select') && window.ChangAjaxSelectValue) {
window.ChangAjaxSelectValue($select, val);
}
}
}
});
$checkbox.each(function () {
let input = $form.find($(this));
let name = input.attr("name");
if (data.hasOwnProperty(name)) {
$("input[name='" + name + "']").prop("checked", false);
if (typeof data[name] == "string") {
if (data[name] === "True" || data[name] === "1" || data[name] === "true") {
$form.find("input[name='" + name + "']").prop("checked", true);
} else if (data[name].indexOf(",") > 0) {
let arr = data[name].split(',');
for (let i = 0; i < arr.length; i++) {
$form.find("input[name='" + name + "'][value='" + arr[i] + "']").prop("checked", true);
}
}
} else if (typeof data[name] == "object") {
for (let i = 0; i < data[name].length; i++) {
$form.find("input[name='" + name + "'][value='" + data[name][i] + "']").prop("checked", true);
}
}
};
});
$radio.each(function () {
let input = $form.find($(this));
let name = input.attr("name");
if (data.hasOwnProperty(name)) {
$form.find("input[name='" + name + "'][value='" + data[name] + "']").prop("checked", true);
//$("input[name='" + name + "'][value!='" + data[name] + "']").prop("checked", false);
}
});
},
//将form表单元素的值序列化成对象
formSerialize: function ($form) {
let disableEle = $form.find("[disabled]");
disableEle.each(function (i, e) {
$(e).prop("disabled", false);
});
let data = {};
$.each($form.serializeArray(),
function () {
if (data[this['name']]) {
data[this['name']] = data[this['name']] + "," + this['value'];
} else {
data[this['name']] = this['value'];
}
});
disableEle.each(function (i, e) {
$(e).prop("disabled", true);
});
return data;
},
//表单验证
formValidate: function ($form, opt) {
let defaults = {
noValid: false,
form: "form",
modal: "modal",
ignore: ".ignore .iwb-wang-editor"
};
opt = opt || {};
let options = $.extend({}, defaults, opt);
let $modal = options.modal
? typeof (options.modal) === 'string'
? $('#' + options.modal)
: $(options.modal)
: null;
$form = $form ? $form : options.form ? $(options.form) : $modal.find('form');
$form.validate(options);
//.settings.ignore = ":disabled";
if (!options.noValid) {
let valid = $form.valid();
debug_log("FormValidate", $form.attr('id'), valid);
return valid;
}
return options.noValid;
},
formatterDate: function (fmt, date, isFix) {
date = date || new Date();
isFix = isFix === undefined ? true : isFix;
let year = date.getFullYear();
let month = date.getMonth() + 1;
fmt = fmt.replace("yyyy", year);
fmt = fmt.replace("yy", year % 100);
fmt = fmt.replace("MM", fix(month));
fmt = fmt.replace("dd", fix(date.getDate()));
fmt = fmt.replace("HH", fix(date.getHours()));
fmt = fmt.replace("mm", fix(date.getMinutes()));
fmt = fmt.replace("ss", fix(date.getSeconds()));
return fmt;
function fix(n) {
return isFix ? (n < 10 ? "0" + n : n) : n;
}
},
blinkTitle: {
start: function (msg) {
msg = msg || abp.localization.iwbZero('NewNotificationRemind');
this.title = document.title;
this.messages = [msg];
if (!this.action) {
try {
this.element = document.getElementsByTagName('title')[0];
this.element.innerHTML = this.title;
this.action = function (ttl) {
this.element.innerHTML = ttl;
};
} catch (e) {
this.action = function (ttl) {
document.title = ttl;
};
delete this.element;
}
this.toggleTitle = function () {
this.index = this.index === 0 ? 1 : 0;
this.action('【' + this.messages[this.index] + '】' + this.title);
};
}
let n = msg.length;
let s = '';
if (this.element) {
let num = msg.match(/\w/g);
if (num) {
let n2 = num.length;
n -= n2;
while (n2 > 0) {
s += " ";
n2--;
}
}
}
while (n > 0) {
s += ' ';
n--;
}
this.messages.push(s);
this.index = 0;
//this.title = this.title.replace("【" + msg + "】", "").replace("【" + s + "】", "");
let _this = this;
this.timer = setInterval(function () {
_this.toggleTitle();
}, 500);
},
stop: function () {
if (this.timer) {
clearInterval(this.timer);
let t = this.title ? this.title : document.title;
this.action(t);
delete this.timer;
delete this.messages;
}
}
},
metPageCss: function (url, id) {
id = id || 'dy-css';
if ($('#' + id).length > 0) {
return;
}
let link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.id = id;
link.href = url + '?v=' + Math.floor(Math.random() * 100000);
let flag = document.getElementById('flag');
let head = document.getElementsByTagName('head')[0];
if (flag) {
head.insertBefore(link, flag.nextSibling);
} else {
head.appendChild(link);
}
},
metPageJs: function (src, id) {
id = id || 'dy-js';
if ($('#' + id).length > 0) {
return;
}
let script = document.createElement('script');
script.id = id;
script.type = 'text/javascript';
script.charset = 'UTF-8';
script.src = src + '?v=' + Math.floor(Math.random() * 100000);
$('head').append(script);
},
loadScript: function (url, loadCallback, failCallback) {
/* UrlStates enum */
let urlStates = {
LOADING: 'LOADING',
LOADED: 'LOADED',
FAILED: 'FAILED'
};
/* UrlInfo class */
function UrlInfo() {
this.state = urlStates.LOADING;
this.loadCallbacks = [];
this.failCallbacks = [];
}
UrlInfo.prototype.succeed = function () {
this.state = urlStates.LOADED;
for (let i = 0; i < this.loadCallbacks.length; i++) {
this.loadCallbacks[i]();
}
};
UrlInfo.prototype.failed = function () {
this.state = urlStates.FAILED;
for (let i = 0; i < this.failCallbacks.length; i++) {
this.failCallbacks[i]();
}
};
UrlInfo.prototype.handleCallbacks = function (loadCallback, failCallback) {
switch (this.state) {
case urlStates.LOADED:
loadCallback && loadCallback();
break;
case urlStates.FAILED:
failCallback && failCallback();
break;
case urlStates.LOADING:
this.addCallbacks(loadCallback, failCallback);
break;
}
};
UrlInfo.prototype.addCallbacks = function (loadCallback, failCallback) {
loadCallback && this.loadCallbacks.push(loadCallback);
failCallback && this.failCallbacks.push(failCallback);
};
let urlInfos = {};
let loadScript = function (url, loadCallback, failCallback) {
let urlInfo = urlInfos[url];
if (urlInfo) {
urlInfo.handleCallbacks(loadCallback, failCallback);
return;
}
urlInfos[url] = urlInfo = new UrlInfo();
urlInfo.addCallbacks(loadCallback, failCallback);
$.getScript(url).done(function (script, textStatus) {
urlInfo.succeed(script, textStatus);
}).fail(function (jqXhr, settings, exception) {
urlInfo.failed(jqXhr, settings, exception);
});
};
loadScript(url, loadCallback, failCallback);
},
//jsonTree 转成 array
Json2Array: function (data, opts) {
let defaults = {
id: 'id',
parentId: 'parentId',
children: 'children'
};
let opt = $.extend({}, defaults, opts || {});
let Json2ArrayChild = function (data, dataArray) {
let newData = $.extend([], data);
let children = data[opt.children];
delete newData[opt.children];
dataArray.push(newData);
if (children && children.length > 0) {
children.forEach(function (v) {
Json2ArrayChild(v, dataArray);
});
}
}
let dataArray = [];
let children = data[opt.children];
let newData = $.extend([], data);
delete newData[opt.children];
dataArray.push(newData);
if (children && children.length > 0) {
children.forEach(function (v) {
Json2ArrayChild(v, dataArray);
});
}
return dataArray;
},
//array 转成 JsonTree
Array2Json: function (dataArray, opts) {
let defaults = {
root: '',
id: 'id',
parentId: 'parentId',
children: 'children'
};
let opt = $.extend({}, defaults, opts || {});
let Json2DataChild = function (parentId, dataArray) {
let children = dataArray.filter(function (v) {
return v[opt.parentId] === parentId;
});
if (children && children.length > 0) {
children.forEach(function (v) {
v[opt.children] = Json2DataChild(v[opt.id], dataArray);
});
}
return children;
}
let index = dataArray.findIndex(function (v) {
return v[opt.parentId] === opt.root;
});
let dataJson = dataArray[index];
dataJson[opt.children] = Json2DataChild(dataJson.id, dataArray);
return dataJson;
}
});
$.fn.formDeserialize = function (data) {
$.formDeserialize($(this), data);
}
$.fn.formSerialize = function () {
return $.formSerialize($(this));
}
/*AJAX*/
$.extend({
//ajax
vbAjax: function (url, opt) {
this.defaults = {
async: true,
type: "Post",
contentType: 'application/json; charset=UTF-8',
//contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: null,
dataFun: null,
log: _LOG,
dataType: "json",
isAlert: true,
successAlert: false,
isValidate: true,
isRefresh: true,//默认刷新表格
success: null,
error: null,
table: undefined,
modal: undefined,
form: undefined,
errorPlacement: function (error, element) {
element.parent().before(error);
element.focus();
},
rules: {},
blockUI: true
};
if (!opt) {
opt = url;
url = opt.url;
}
let options = $.extend({}, this.defaults, opt);
let $table = !options.table ? undefined : typeof options.table === 'string' ? $('#' + options.table) : $(options.table);
let $modal = !options.modal ? undefined : typeof options.modal === 'string' ? $('#' + options.modal) : $(options.modal);
let $form = !options.form ? ($modal ? $modal.find("form") : undefined) : typeof options.form === 'string' ? $('#' + options.form) : $(options.form);
let isValidated = true;
if (options.isValidate && $form) {
isValidated = $.formValidate($form);
}
if (isValidated) {
if (options.dataFun !== null && typeof options.dataFun === 'function') {
options.data = options.dataFun();
} else {
options.data = options.data ? (typeof options.data === 'function' ? options.data() : options.data) : $form ? $.formSerialize($form) : undefined;
}
let guid = Math.floor(Math.random() * 10000);
let log = options.log;
if (log) {
console.log('[' + guid + ']url:' + url, 'data:', options.data);
}
let success = options.success && typeof options.success === 'function'
? function (res) {
if (log) { console.log('[' + guid + ']', res); }
options.success(res);
if (options.isRefresh && $table) {
$table.VbTable('refresh', true);
}
if ($modal) {
$modal.VbModal('hide');
}
}
: function (res) {
if (log) { console.log('[' + guid + ']', res); }
if (options.isRefresh && $table) {
$table.VbTable('refresh', true);
}
if ($modal) {
$modal.VbModal('hide');
}
};
let ajaxSuccess = options.isAlert || options.successAlert ? function (res) { abp.message.success(abp.localization.VberZero('OpSuccess')).done(success(res)); } : success;
let data = typeof (options.data) === 'string' ? options.data : JSON.stringify(options.data);
let ajaxOption = {
url: url,
async: options.async,
type: options.type,
contentType: options.contentType,
data: data,
dataType: options.dataType,
success: ajaxSuccess,
error: options.error,
abpHandleError: options.isAlert,
beforeSend: function () {
abp.ajax.blockUI(ajaxOption);
},
blockUI: options.blockUI
};
abp.ajax(ajaxOption);
}
}
});
$.extend({
vbAjax1: function (opt) {
opt = $.extend({}, { isValidate: false }, opt);
$.vbAjax(opt);
},
vbAjax2: function (opt) {
opt = $.extend({}, { isAlert: false }, opt);
$.vbAjax(opt);
},
vbAjax3: function (opt) {
opt = $.extend({}, { isValidate: false, isAlert: false, blockUI: true }, opt);
$.vbAjax(opt);
},
vbAjax4: function (opt) {
opt = $.extend({}, { isValidate: false, isAlert: false, isRefresh: false, blockUI: true }, opt);
$.vbAjax(opt);
},
vbAjax41: function (opt) {
opt = $.extend({}, { isValidate: false, isAlert: false, isRefresh: false, blockUI: false }, opt);
$.vbAjax(opt);
},
vbAjax5: function (opt) {
opt = $.extend({}, { isValidate: false, isAlert: false, successAlert: true, isRefresh: false, blockUI: true }, opt);
$.vbAjax(opt);
},
vbGet: function (opt) {
opt = $.extend({}, { type: 'get', modal: null, form: null }, opt);
$.vbAjax4(opt);
}
});
/*ajax全局设置*/
$.ajaxSetup({
type: 'get',
timeout: 1000 * 60 * 2,
//contentType: "application/x-www-form-urlencoded;charset=utf-8",
contentType: "application/json",
dataType: "json",
error: function () {
abp.ui.clearBusy();
},
complete: function (xmlHttpRequest, textStatus) {
abp.ui.clearBusy();
if (textStatus === "timeout") {
abp.message.error(abp.localization.iwbZero('OpTimeout'));
debug_log("Complete - 操作超时");
} else if (textStatus !== "success") {
debug_log("Complete - " + textStatus, xmlHttpRequest.responseJSON);
if (xmlHttpRequest.responseJSON) {
//let json = xmlHttpRequest.responseJSON;
} else if (xmlHttpRequest.responseText === "") {
abp.message.error(abp.localization.VberZero('OpServerError')).done(function () {
top.location.reload();
//top.location.href = "/Account/Login/?ReturnUrl=%2F";
});
}
} else {
let result = xmlHttpRequest.responseJSON;
if (result && !result.success && result.error && result.error.message.indexOf('登陆超时') > -1) {
top.location.reload();
}
}
}
});
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
? factory(exports)
: typeof define === 'function' && define.amd
? define(['exports'], factory)
: (global = global || self, factory(global.vber = { a: "1" }));
}(this, (function (exports) {
'use strict';
let abp = window.abp || {};
let VbTable = function ($) {
const NAME = 'VbTable';
const DATA_KEY = 'Vber.DataTable';
const EVENT_KEY = "." + DATA_KEY;
const JQUERY_NO_CONFLICT = $.fn[NAME];
const ClassName = {
TABLE_BOX: 'table-box',
DATE_RANGE: 'vb-date-range',
SEARCH_FIELD: 'search-filed',
SEARCH_FIELD_TYPE: 'search-filed-type',
SEARCH_EXP_TYPE: 'search-exp-type',
TOOL_MENU_TYPE: 'vb-tool-menu-type',
TOOL_MENU_URL: 'vb-tool-menu-url',
TREE_TD_CONTROL: 'vb-treegrid-control',
TREE_TD_CONTROL_OPEN: 'vb-treegrid-control-open',
};
const Selector = {
TABLE_BOX: `.${ClassName.TABLE_BOX}`,
TOOLBAR_BASE: '[data-kt-table-toolbar="base"]',
TOOLBAR_SELECTED: '[data-kt-table-toolbar="selected"]',
TOOLBAR_SELECTED_COUNT: '[data-kt-table-select="selected_count"]',
SEARCH_GLOBAL: `[data-search-keyWord="global"]`,
SEARCH_ADVANCE: `[data-search-keyWord="advance"]`,
TOOL_MENU_ALL: `[data-vb-tool-menu-type]`,
TOOL_MENU: `[data-vb-tool-menu-type="{0}"]`,
TREE_TD_CONTROL: `td.${ClassName.TREE_TD_CONTROL}`,
TREE_TD_CONTROL_OPEN: `td.${ClassName.TREE_TD_CONTROL_OPEN}`
};
const ALLOW_METHOD = [
"addToolFunctions",
"getToolFunctions",
"create",
"update",
"delete",
"getRow",
"getSelection",
"getSelections",
"getSelectionIds",
"getInstance",
"reRender",
"destroy",
"refresh",
"treeExpandAll",
"treeExpand",
"treeCollapse",
];
const Default = {
processing: true,
serverSide: true,
scrollCollapse: true,
paging: true,
autoWidth: true,
searching: false,
ordering: true,
orderClasses: true,
rowId: "id",
pagingType: "full_numbers",//分页样式:simple,simple_numbers,full,full_numbers
select: {
style: 'os',
selector: 'td:first-child',
className: 'row-selected'
},
lengthChange: true,
lengthMenu: [25, 50, 100],
clickToSelect: true,
deferRender: false,
drawCallback: undefined,
searchForm: undefined,
searchList: [],
searchFun: null,
onlySearchList: false,
searchValidate: true,
dateRangeSpliter: "至",
order: [],
toolFunctions: [],
onAllCheck: undefined,
onAllUnCheck: undefined,
onCheck: undefined,
onUnCheck: undefined,
onClickRow: undefined,
onDblClickRow: undefined,
modal: 'modal',
form: 'form',
modalDrag: true,
multipleSelect: false,//多选保存分页数据
isTree: false,
left: 12,//tree的子目录偏移
expandDepth: 2,
leafIcon: '',//叶子节点
expandIcon: '',
collapseIcon: '',
fnDrawCallback: undefined,
root: null,
field: "id",
parentField: "parentNo",
nameField: "name",
parentNameField: "parentName",
};
let Table = function () {
function Table(element, config) {
this._element = element;
this._config = config;
return this._init();
}
let _proto = Table.prototype, dt, _selectedIdArray = [], treeGridRows = {};
_proto._init = function () {
let _this = this, _config = _this._config, _el = _this._element;
$.fn.dataTable.ext.errMode = "none "
let htmlOptions = _this._getHtmlOption();
if (window.lang && window.lang != "en") {
htmlOptions.language = { url: `/libs-ext/dataTable/language_${window.lang}.json` };
}
let options = $.extend(true, {}, htmlOptions, _config, _config.isTree ? { paging: false, pageSelect: false, dom: "tr" } : {});
debug_log("table_options:", options);
dt = $(_el).DataTable(options);
_config.dataTable = dt;
//_this._initToggleToolbar();
dt.on(`init${EVENT_KEY}`, function () {
_this._onEvent();
_this._drawRender();
})
_this._initToolFunction();
if (_config.isTree) {
_this._initTree();
}
};
_proto._getHtmlOption = function () {
let _this = this, _config = _this._config, _el = _this._element;
let htmlOption = $.extend(true, {}, $(_el).data());
if (htmlOption.url) {
htmlOption.ajax = {
contentType: 'application/json; charset=UTF-8',
url: htmlOption.url,
type: htmlOption.method,
data: (param) => {
return _config.queryParams && typeof _config.queryParams == 'function'
? _config.queryParams.call(_this, param)
: _this._queryParams(param);
},
dataFilter: (data) => {
return _config.responseHandler && typeof _config.responseHandler == 'function'
? _config.responseHandler.call(_this, data)
: _this._responseHandler(data);
},
error: function () {
console.error(`Table[${$(_this._element).attr('id')}] load failed`);
$('#table_processing').fadeOut();
abp.message.error("加载出错!");
}
};
}
htmlOption.columns = _config.columnsFunc && typeof _config.columnsFunc == 'function'
? _config.columnsFunc.call(_this, $.extend(true, {}, $(_el).data()))
: htmlOption.columnsFunc && typeof window[htmlOption.columnsFunc] == "function"
? window[htmlOption.columnsFunc].call(_this, $.extend(true, {}, $(_el).data()))
: _this._getColumnOption();
htmlOption.rowCallback = htmlOption.rowCallbackFunc && typeof window[htmlOption.rowCallbackFunc] == "function" ?
function (row, data) {
window[htmlOption.rowCallbackFunc].call(_this, row, data);
_this._rowCallback.call(_this, row, data);
} :
function (row, data) {
_this._rowCallback.call(_this, row, data);
};
return htmlOption;
}
_proto._getColumnOption = function () {
let _this = this, _config = _this._config, _el = _this._element;
let columns = [];
let treeColumns = _config.isTree;
let $th = $(_el).find('thead').eq(0).find('th');
if ($th.length) {
$th.each(function () {
let $this = $(this), data = $this.data();
let column = {
data: data.field ? function (item) { return item[data.field] } : null,
orderable: data.sortable ? true : false,
searchable: false
};
column.name = data.field;
if (data.className) {
column.className = data.className;
}
if (data.width) {
column.width = data.width;
}
//if (data.className) {
// column.className = data.className;
//}
if (data.checkBox) {
column.orderable = false;
column.data = "check_state";
column.render = function (data) {
let checked = data ? "checked=\"checked\"" : "";
return `
`;
}
}
if (data.formatter) {
if (window[data.formatter] && typeof window[data.formatter] === "function") {
column.render = function (d, t, r, m) {
let v = t == "display" ?
window[data.formatter].call(this, d, r) :
d;
return v;
};
} else {
column.render = () => data.formatter + "";
}
}
//formatter 后 tip就不能起作用。
if (data.tip && !data.formatter) {
column.render = function (value, type, row, meta) {
if (type === 'display') {
let length = Number(data.tip) && Number(data.tip) > 0 ? Number(data.tip) : 40;
return value.length > length ? `${value.substr(0, length - 2)}...` : value;
}
return value;
};
}
if (data.tree && treeColumns) {
treeColumns = false;
column.title = '';
column.target = 0;
column.orderable = false;
column.className = ClassName.TREE_TD_CONTROL;
column.data = function (item) {
if (item.children != null && item.children.length > 0) {
return _config.expandIcon;
}
return _config.leafIcon;
}
}
if (data.action) {
// let action = `
//操作
//
//
//
//
//`;
if (data.actionTree) {
column.className = "text-end pe-2";
let treeActionMenu = "";
$(_el).closest(Selector.TABLE_BOX).find(Selector.TOOLBAR_BAS + "," + Selector.TOOLBAR_SELECTED).addClass("d-none").find(Selector.TOOL_MENU_ALL).each(function () {
let btnType = $(this).data(ClassName.TOOL_MENU_TYPE).replace("_", "");
if (btnType !== "btnRefresh" && btnType !== "btnSearch") {
let btnUrl = $(this).data(ClassName.TOOL_MENU_URL) || "";
let btnName = $(this).text();
//let btnClass = $(this).attr("class");
let btnIcon = $(this).find("i").attr("class");
/* treeActionMenu += ``;*/
//$(this).remove();
treeActionMenu += `${btnIcon ? `` : icon}${btnName}`
} else if (btnType !== "btnSearch") {
$(this).prop("disabled", false).attr("onclick", "$.vbAjax1({url: '" + $(this).data(ClassName.TOOL_MENU_URL) + "'});");
}
});
data.actionFormatter = function treeActionFormatter(d, r) {
return treeActionMenu.format(r[_config.rowId]);
};
}
/* let actionMenu = `{0}
`;*/
if (data.actionFormatter) {
let actionMenuFunc = typeof data.actionFormatter == "function" ? data.actionFormatter : typeof window[data.actionFormatter] == "function" ? window[data.actionFormatter] : false;
if (actionMenuFunc) {
column.render = function (d, t, r) {
//return t == "display" ? `${action}\r\n${actionMenu.format(actionMenuFunc.call(this, d, r))}` : d;
return t == "display" ? `${actionMenuFunc.call(this, d, r)}` : d;
}
}
}
}
columns.push(column);
});
}
return columns;
};
_proto._queryParams = function (param) {
let _this = this, _config = _this._config;
let queryParam, sort = "";
if (param.order && param.order.length) {
param.order.forEach((v) => {
sort += (sort == "" ? "" : ",") + `${param.columns[v.column].name} ${v.dir}`;
});
}
let $searchForm = _this._getSearchForm();
let searchList = _this._getSearchList();
if (_config.onlySearchList) {
queryParam = {
maxResultCount: params.limit,
skipCount: params.offset,
sorting: params.sort ? params.sort + ' ' + params.order : '',
searchList: searchList
};
} else {
let $search = $searchForm.find(Selector.SEARCH_GLOBAL);
queryParam = {
maxResultCount: param.length > 0 ? param.length : 1000,
skipCount: param.start,
sorting: sort,
keyField: $search.data(ClassName.SEARCH_FIELD),
fieldType: $search.data(ClassName.SEARCH_FIELD_TYPE) ? $search.data(ClassName.SEARCH_FIELD_TYPE) : 0,
expType: $search.data(ClassName.SEARCH_EXP_TYPE) ? $search.data(ClassName.SEARCH_EXP_TYPE) : 0,
keyWords: $search.val(),
SearchList: searchList
}
}
if (_LOG) {
debug_log("table_queryParam", queryParam);
}
return JSON.stringify(queryParam);
};
_proto._getSearchForm = function () {
let _this = this, _config = _this._config;
let $form;
if (_config.searchForm) {
$form = typeof (_config.searchForm) === 'string'
? $('#' + _config.searchForm)
: $(_config.searchForm);
}
if ($form && $form.length) {
return $form;
}
$form = $(_this._element).closest(Selector.TABLE_BOX).find('form');
return $form;
}
_proto._getSearchList = function () {
let _this = this, _config = _this._config;
let searchList = [];
if (_config.searchFun && typeof _config.searchFun === "function") {
_config.searchFun.call(_this, searchList);
}
if (_config.onlySearchFun) {
return searchList;
}
if (_config.searchList && _config.searchList.length > 0) {
_config.searchList.forEach(function (v) {
if (v.keyWords) {
searchList.push(v);
}
});
}
if (_config.onlySearchList) {
return searchList;
}
let $searchForm = _this._getSearchForm();
$searchForm.find(Selector.SEARCH_ADVANCE).each(function () {
let $this = $(this), keyWords = $this.val();
if (($this.attr('type') == "checkBox" || $this.attr('type') == "radio") && !$this.is(':checked')) {
keyWords = undefined;
}
if (keyWords) {
let field = $this.data(ClassName.SEARCH_FIELD), fieldType = $this.data(ClassName.SEARCH_FIELD_TYPE);
// ReSharper disable once UnknownCssClass
if ($this.hasClass(ClassName.DATE_RANGE)) {
try {
let dates = keyWords.split(` ${_config.dateRangeSpliter} `);
searchList.push({
keyWords: dates[0],
keyField: field,
fieldType: fieldType,
expType: 4
});
if (dates.length === 2) {
let nextDate = new Date(dates[1]);
let newDate = new Date(nextDate.getFullYear(),
nextDate.getMonth(),
nextDate.getDate(),
23,
59,
59,
999);
//let newDate = new Date(date.getTime() + 24 * 60 * 60 * 1000 - 1);
let date2 = $.formatterDate('yyyy-MM-dd HH:mm:ss', newDate);
searchList.push({
keyWords: date2,
keyField: field,
fieldType: fieldType,
expType: 5
});
}
} catch (e) {
console.log(e);
}
} else {
let expType = $this.data(ClassName.SEARCH_EXP_TYPE)
searchList.push({
keyWords: keyWords,
keyField: field,
fieldType: fieldType,
expType: expType
});
}
}
});
return searchList;
}
_proto._responseHandler = function (res) {
let _this = this, _config = _this._config;
let json = jQuery.parseJSON(res);
let result = {
recordsTotal: 0,
recordsFiltered: 0,
data: []
}
if (json.success) {
if (_config.isTree) {
result.data = _this._toTreeData(json.result.items);
} else {
result.recordsTotal = json.result.totalCount;
result.recordsFiltered = json.result.totalCount;
result.data = json.result.items;
}
} else {
console.log(`Table[${$(_this._element).attr('id')}] load failed`);
if (res.error) {
if (res.error.details) {
return abp.message.error(res.error.details, res.error.message);
} else {
if (res.error.message && res.error.message.indexOf('登陆超时') >= 0) {
return abp.message.error(res.error.message).done(function () {
window.top.location.reload();
});
} else {
return abp.message.error(res.error.message || abp.ajax.defaultError.message);
}
}
}
}
debug_log("table_Data:", result);
return JSON.stringify(result); // return JSON string
}
_proto._toTreeData = function (data) {
let _this = this, _config = _this._config;
let treeData = [];
let f = _config.field ? _config.field : "id",
pf = _config.parentField ? _config.parentField : "parentNo";
function getChildren(parent) {
let children = data.filter(function (v) { return v[pf] == parent[f]; });
parent.children = [];
if (children) {
if (children.length) {
parent.children = children;
children.forEach((v) => { getChildren(v) })
}
//else {
// parent.children.push(children);
// getChildren(children)
//}
}
}
let root = data.filter(function (v) { return v[pf] == _config.root; });
if (root) {
if (root.length) {
root.forEach(v => { treeData.push(v); getChildren(v); })
}
//else {
// treeData.push(root);
// getChildren(root);
//}
}
return treeData;
}
_proto._rowCallback = function (row, data) {
let _this = this, _config = _this._config;
if (_config.multipleSelect && _config.clickToSelect) {
if ($.inArray(data.id + "", _selectedIdArray) !== -1) {
$(row).addClass(_config.select.className);
$(row).find(' input[type="checkbox"]').prop("checked", true);
}
} else {
_selectedIdArray = [];
}
}
_proto._onEvent = function () {
let _this = this, _config = _this._config, _el = _this._element;
let timeOutClick;
if (_config.onClickRow && typeof _config.onClickRow == "function") {
$(_el).find('tbody').on(`click${EVENT_KEY}.tr`, 'tr', function () {
clearTimeout(timeOutClick);
let __this = this;
timeOutClick = setTimeout(function () {
let row = dt.row(__this).data();
debug_log("table_tr_ckick", __this.id, row);
_config.onClickRow.call(_this, row);
}, 200)
});
}
if (_config.onDblClickRow && typeof _config.onDblClickRow == "function") {
$(_el).find('tbody').on(`dblclick${EVENT_KEY}.tr`, 'tr', function () {
clearTimeout(timeOutClick);
let row = dt.row(this).data();
debug_log("dbckick", this.id, row);
_config.onDblClickRow.call(_this, row);
});
}
dt.on(`draw${EVENT_KEY}`, function () {
//if ($(_el).find('tbody tr input[type="checkbox"]:not(:checked)').length) {
// $(_el).find('thead tr input[type="checkbox"]').prop("checked", false);
//} else {
// $(_el).find('thead tr input[type="checkbox"]').prop("checked", true);
//}
_this._toggleToolBars();
_this._drawRender();
});
$(_el).on(`resize${EVENT_KEY}`, () => { _this.reRender(); });
if (_config.checkBox) {
$(_el).find('thead tr th').on(`click${EVENT_KEY}.init`, 'input[type="checkbox"]', function (e) {
e.preventDefault();
e.stopPropagation();
let checked = this.checked;
if (checked) {
if (_config.onAllCheck && typeof _config.onAllCheck == "function") {
let rows = _this._mapData(dt.rows().data());
debug_log("table_allcheck", rows)
_config.onAllCheck.call(_this, rows);
}
} else {
if (_config.onAllUnCheck && typeof _config.onAllUnCheck == "function") {
let rows = _this._mapData(dt.rows().data());
debug_log("table_allUncheck", rows)
_config.onAllUnCheck.call(_this, rows);
}
}
setTimeout(() => {
const $allTrs = $(_el).find('tbody tr');
$allTrs.each(function () {
if (checked) {
if (!$(this).hasClass(_config.select.className)) {
$(this).addClass(_config.select.className);
}
} else {
$(this).removeClass(_config.select.className);
}
});
$allTrs.find('input[type="checkbox"]').each(function () {
let id = $(this).closest('tr').attr('id'), index = $.inArray(id, _selectedIdArray);
if (checked) {
$(this).prop("checked", true);
if (index == -1) {
_selectedIdArray.push(id);
}
} else {
$(this).prop("checked", false);
if (index > -1) {
_selectedIdArray.splice(index, 1);
}
}
});
if (_config.clickToSelect) {
_this._toggleToolBars();
}
}, 50);
});
}
$(_el).find('tbody').on(`click${EVENT_KEY}.init`, 'tr', function () {
let __this = this;
let row = dt.row(this).data();
setTimeout(() => {
if (_config.singleSelect) {
if ($(__this).hasClass(_config.select.className)) {
$(__this).find('input[name="check_state"][type="checkbox"]')
.prop("checked", false);
if (_config.clickToSelect) {
$(__this).removeClass(_config.select.className);
}
_selectedIdArray = [];
if (_config.onUnCheck && typeof _config.onUnCheck == "function") {
debug_log("table_tr_uncheck", row)
_config.onUnCheck.call(_this, row);
}
} else {
$(__this).find('input[name="check_state"][type="checkbox"]')
.prop("checked", true);
$(__this).siblings().removeClass(_config.select.className).find('input[name="check_state"][type="checkbox"]')
.prop("checked", false);
if (_config.clickToSelect) {
$(__this).addClass(_config.select.className);
}
_selectedIdArray = [__this.id];
if (_config.onCheck && typeof _config.onCheck == "function") {
debug_log("table_tr_check", row)
_config.onCheck.call(_this, row);
}
}
} else {
let id = __this.id;
let index = $.inArray(id, _selectedIdArray);
if (index === -1) {
_selectedIdArray.push(id);
$(__this).find('input[name="check_state"][type="checkbox"]').prop('checked', true);
if (_config.clickToSelect) {
$(__this).addClass(_config.select.className);
}
if (_config.onCheck && typeof _config.onCheck == "function") {
debug_log("table_tr_check", row)
_config.onCheck.call(_this, row);
}
} else {
_selectedIdArray.splice(index, 1);
$(__this).find('input[name="check_state"][type="checkbox"]').prop('checked', false);
if (_config.clickToSelect) {
$(__this).removeClass(_config.select.className);
}
if (_config.onUnCheck && typeof _config.onUnCheck == "function") {
debug_log("table_tr_uncheck", row)
_config.onUnCheck.call(_this, row);
}
}
}
if (_config.clickToSelect) {
_this._toggleToolBars();
}
}, 50);
});
}
_proto._toggleToolBars = function () {
let _this = this, _config = _this._config, _el = _this._element;
const $box = $(_el).closest(Selector.TABLE_BOX),
$toolbarBase = $box.find(Selector.TOOLBAR_BASE),
$toolbarSelected = $box.find(Selector.TOOLBAR_SELECTED),
$selectedCount = $box.find(Selector.TOOLBAR_SELECTED_COUNT);
if (_config.singleSelect) {
$selectedCount.parent().addClass('d-none');
}
if (_selectedIdArray.length) {
$selectedCount.html(_selectedIdArray.length);
$toolbarBase.addClass('d-none');
$toolbarSelected.removeClass('d-none');
} else {
$toolbarBase.removeClass('d-none');
$toolbarSelected.addClass('d-none');
}
if ($(_el).find('tbody tr input[type="checkbox"]:not(:checked)').length) {
$(_el).find('thead tr input[type="checkbox"]').prop("checked", false);
} else {
$(_el).find('thead tr input[type="checkbox"]').prop("checked", true);
}
debug_log("table_selectIds", _selectedIdArray);
}
_proto._mapData = function (data) {
let rows = [];
for (let i = 0; i < data.length; i++) {
let row = data[i + ""];
rows.push(row);
}
return rows;
};
_proto._renderSelectRows = function () {
let _this = this, _config = _this._config, _el = _this._element;
if (_config.pageSelect && _selectedIdArray.length) {
$(_el).find("tbody tr").each(function () {
let id = $(this).attr('id');
if (_selectedIdArray.indexOf(id) > -1) {
$(this).find('input[name="check_state"][type="checkbox"]').prop('checked', true);
$(this).addClass(_config.select.className);
}
});
}
}
_proto._getModalOption = function (url, opt, title, type) {
let _this = this, _config = _this._config, $table = $(_this._element);
let modalOpts = $.extend({}, { url: "" });
modalOpts.opTitle = title;
modalOpts.draggable = _config.modalDrag;
modalOpts.fromValidate = true;
if (!opt) {
opt = !url || typeof url === "string" ? {} : url;
}
if (opt.hasOwnProperty("url")) {
modalOpts.url = opt.url;
} else if (typeof url === "string") {
modalOpts.url = url;
}
if (!modalOpts.url) {
let $tableToolMENU = $table.closest(Selector.TABLE_BOX).find(Selector.TOOL_MENU.format(type));
modalOpts.url = $tableToolMENU.data([ClassName.TOOL_MENU_URL]);
}
modalOpts.modal =
typeof _config.modal === 'string' ? $("#" + _config.modal) : $(_config.modal);
modalOpts.table = $table;
//modalOptions.type = type.toLowerCase().indexOf('btnupdate') === 0 ? 'put' : 'post';
modalOpts.type = 'post';
modalOpts = $.extend({}, modalOpts, opt);
return modalOpts;
}
_proto._initToolFunction = function () {
let _this = this;
_this.addToolFunctions("btnCreate", function (url) { _this.create(url); });
_this.addToolFunctions("btnUpdate", function (url) { _this.update(url); });
_this.addToolFunctions("btnDelete", function (url) { _this.delete(url); });
_this.addToolFunctions("btnSearch", function () { _this.refresh(true); });
_this.addToolFunctions("none", function () { console.log("No type"); });
let $tableToolMenu = $(_this._element).closest(Selector.TABLE_BOX).find(Selector.TOOL_MENU_ALL);
$tableToolMenu.off().on(`click${EVENT_KEY}.menu`,
function () {
let funs = _this.getToolFunctions();
let type = $(this).data(ClassName.TOOL_MENU_TYPE);
let index = type.lastIndexOf('_');
type = index > -1 ? type.substr(index + 1) : type;
let url = $(this).data(ClassName.TOOL_MENU_URL) || "";
funs[type] ? funs[type].call(this, url) : funs["none"].call(this);
});
};
_proto._drawRender = function () {
$(this._element).find('[data-bs-toggle="tooltip"]').each(function () {
new bootstrap.Tooltip(this, {
delay: 500
});
});
KTMenu.createInstances('[data-kt-menu-action="true"]')
};
_proto._initTree = function () {
let _this = this, _config = _this._config, _el = _this._element;
let treeOption = {
left: _config.left > 0 ? _config.left : 10,
expandAll: _config.expandAll,
leafIcon: _config.leafIcon,
expandIcon: _config.expandIcon,
collapseIcon: _config.collapseIcon,
fnDrawCallback: _config.fnDrawCallback
}
_config.treeOption = treeOption;
_this._onTreeEvent();
_this.addToolFunctions("btnCreate_tree", function (url, id) {
let row = _this.getRow(id);
if (row) {
let data = {};
data[_config.parentField] = row[_config.field];
data[_config.parentNameField] = row[_config.nameField];
_this.create(url, { data: data });
}
})
_this.addToolFunctions("btnUpdate_tree", function (url, id) {
let row = _this.getRow(id);
if (row) {
_this.update(url, { data: row }, row);
}
})
_this.addToolFunctions("btnDelete_tree", function (url, id) {
let row = _this.getRow(id);
if (row) {
_this.delete(url, { data: row }, row);
}
})
_this.addToolFunctions("btnMoveUp_tree", function (url, id) {
console.log("MoveUp", id);
let row = _this.getRow(id);
if (row) {
let $prev = $('#' + row[_config.rowId]).prev();
if ($prev.length) {
let prevRow = _this.getRow($prev.attr('id'));
if (prevRow && prevRow[_config.parentField] == row[_config.parentField]) {
$.vbAjax1({ url: url, data: { Id: id, MoveId: prevRow[_config.rowId] }, table: $(_el) });
return;
}
}
abp.message.warn(abp.localization.VberZero("RecordAtTop"));
}
})
_this.addToolFunctions("btnMoveDown_tree", function (url, id) {
console.log("MoveDown", id);
let row = _this.getRow(id);
if (row) {
let $next = $('#' + row[_config.rowId]).next();
if ($next.length) {
let nextRow = _this.getRow($next.attr('id'));
if (nextRow && nextRow[_config.parentField] == row[_config.parentField]) {
$.vbAjax1({ url: url, data: { Id: id, MoveId: nextRow[_config.rowId] }, table: $(_el) });
return;
}
}
abp.message.warn(abp.localization.VberZero("RecordAtBottom"));
}
})
};
_proto._resetEvenOddClass = function () {
let classes = ['odd', 'even'];
$(dt.table().body()).find('tr').each(function (index, tr) {
$(tr).removeClass('odd even').addClass(classes[index % 2]);
});
};
_proto._resetTreeGridRows = function (id) {
let _this = this, treeOption = _this._config.treeOption;
let subRows = treeGridRows[id];
if (subRows && subRows.length) {
subRows.forEach(function (node) {
let subTrId = $(node).attr('id');
if (treeGridRows[subTrId]) {
_this._resetTreeGridRows(subTrId);
}
dt.row($(node)).remove();
$(node).remove();
});
delete treeGridRows[id];
let p_depth = $('#' + id).data('depth') || 0,
$icon = $(treeOption.expandIcon).css('marginLeft', p_depth * treeOption.left + 'px');
$('#' + id).find(Selector.TREE_TD_CONTROL_OPEN)
.removeClass(ClassName.TREE_TD_CONTROL_OPEN)
.addClass(ClassName.TREE_TD_CONTROL)
.html($icon);
}
};
_proto._onTreeEvent = function () {
let _this = this, _config = _this._config;
//let treeOption = _config.treeOption;
dt.on(`click${EVENT_KEY}.tree`, Selector.TREE_TD_CONTROL, function (e) {
_this.treeExpand($(e.target).closest('tr').attr("id"));
})
dt.on(`click${EVENT_KEY}.tree`, Selector.TREE_TD_CONTROL_OPEN, function (e) {
_this.treeCollapse($(e.target).closest('tr').attr("id"));
})
dt.on(`draw${EVENT_KEY}.tree`, function () {
_this._treeExpandAll(_config.expandDepth);
})
}
_proto._treeExpandAll = function (depth, id) {
let _this = this;
depth = depth == undefined ? true : depth - 1;
let children = _this.treeExpand(id || null);
if (depth && children && children.length) {
children.forEach(v => {
_this._treeExpandAll(depth, $(v).attr('id'));
})
}
}
_proto.treeExpandAll = function () {
this._treeExpandAll();
}
_proto.treeExpand = function (id) {
let _this = this, _config = _this._config;
let treeOption = _config.treeOption;
let $tr = id ? $('#' + id) : $(dt.row(0).node());
let subRows = treeGridRows[$tr.attr('id')] = []
let p_depth = $tr.data('depth') || 0;
let row = dt.row($tr[0]),
index = row.index(),
data = row.data();
debug_log("table_tree_open:", index, data);
if (data.children && data.children.length) {
let $td = $tr.find(Selector.TREE_TD_CONTROL),
//paddingLeft = parseInt($td.css('padding-left'), 10),
//layer = parseInt($td.find('span').css('margin-left') || 0, 10) / treeOption.left,
$icon = $(treeOption.collapseIcon);
$icon.css('marginLeft', p_depth * treeOption.left + 'px');
$td.removeClass(ClassName.TREE_TD_CONTROL).addClass(ClassName.TREE_TD_CONTROL_OPEN).html($icon);
let prevRow = row.node();
p_depth++;
data.children.forEach(function (item) {
let node = dt.row.add(item).node();
$(node).data('depth', p_depth);
//$(node).attr('parent-index', index);
//let $childTd = $(node).find(Selector.TREE_TD_CONTROL);
$(node).find(Selector.TREE_TD_CONTROL).find('span').css('marginLeft', p_depth * treeOption.left + 'px');
//.next().css('paddingLeft', paddingLeft + left + 'px');
$(node).insertAfter(prevRow);
prevRow = node;
subRows.push(node);
})
_this._resetEvenOddClass();
_this._drawRender();
}
return subRows;
}
_proto.treeCollapse = function (id) {
let _this = this, _config = _this._config;
let treeOption = _config.treeOption;
let $tr = $('#' + id), $td = $tr.find(Selector.TREE_TD_CONTROL_OPEN),
//paddingLeft = parseInt($td.css('padding-left'), 10),
//layer = parseInt($td.find('span').css('margin-left') || 0, 10) / treeOption.left,
p_depth = $tr.data('depth') || 0,
$icon = $(treeOption.expandIcon).css('marginLeft', p_depth * treeOption.left + 'px');
$td.removeClass(ClassName.TREE_TD_CONTROL_OPEN).addClass(ClassName.TREE_TD_CONTROL).html($icon);
_this._resetTreeGridRows(id);
_this._resetEvenOddClass();
}
_proto.addToolFunctions = function (key, fun) {
let _this = this;
let toolFunctions = _this.getToolFunctions();
toolFunctions[key] = fun;
_this._config.toolFunctions = toolFunctions;
};
_proto.getToolFunctions = function () {
return this._config.toolFunctions;
}
_proto.create = function (url, opt) {
let _this = this;
console.log("Add---" + _this._element.id);
opt = opt || {};
let modalOpts = _this._getModalOption(url, opt, abp.localization.VberZero('OpCreate'), '_btnCreate');
let $modal = typeof modalOpts.modal === 'string'
? $('#' + modalOpts.modal)
: $(modalOpts.modal);
$modal.VbModal(modalOpts);
}
_proto.update = function (url, opt, row) {
let _this = this;
console.log("Update---" + _this._element.id);
opt = opt || {};
row = row || opt.row || _this.getSelection();
if (row) {
let modalOptions = _this._getModalOption(url, opt, abp.localization.VberZero('OpUpdate'), 'btnUpdate');
if (!modalOptions.data) {
modalOptions.data = row;
}
let $modal = typeof (modalOptions.modal) === 'string'
? $('#' + modalOptions.modal)
: $(modalOptions.modal);
$modal.VbModal(modalOptions);
}
}
_proto.delete = function (url, opt, row) {
let _this = this;
console.log("Delete---" + _this._element.id);
opt = opt || {};
row = row || opt.row || _this.getSelection();
if (row) {
let data = opt.data || { id: row.id };
abp.message.confirm(abp.localization.VberZero('DeleteConfirmContent'),
abp.localization.VberZero('DeleteConfirm'),
function (isConfirmed) {
if (isConfirmed) {
$.vbAjax1({
table: $table,
url: url + '?' + _this._config.id + '=' + data[_this._config.id],
data: data
});
}
});
}
}
_proto.destroy = function () {
let _this = this, $this = $(_this._element);
$this.removeData(DATA_KEY);
$this.DataTable('destroy');
}
_proto.getSelection = function () {
return this.getSelections()[0];
}
_proto.getSelections = function () {
let _this = this, _config = _this._config;
let data = dt.rows("." + _config.select.className).data();
return _this._mapData(data);
}
_proto.getSelectionIds = function () {
return _selectedIdArray;
}
_proto.getRow = function (id) {
let data = dt.row($("#" + id)).data();
debug_log("row", id, data);
return data;
}
_proto.getInstance = function () {
return dt;
}
_proto.reRender = function () {
dt.draw();
}
_proto.refresh = function (resetPaging, callback) {
dt.ajax.reload(callback, resetPaging);
}
Table._jQueryInterface = function _jQueryInterface(option) {
let value, args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
let $this = $(this), data = $this.data(DATA_KEY);
if (typeof option === 'string') {
if ($.inArray(option, ALLOW_METHOD) < 0) {
throw new Error("Unknown method: " + option);
}
if (!data) {
return;
}
value = data[option].apply(data, args);
}
if (!data) {
let options = $.extend({}, Default, $(this).data(), typeof option === 'object' && option);
data = new Table(this, options);
$this.data(DATA_KEY, data);
}
});
return typeof value === 'undefined' ? this : value;
}
return Table;
}();
/*
* jQuery API
* ====================================================
*/
$.fn[NAME] = Table._jQueryInterface;
$.fn[NAME].Constructor = Table;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Table._jQueryInterface;
};
return Table;
}((jQuery));
let VbModal = function ($) {
const NAME = 'VbModal';
const DATA_KEY = 'vb.modal';
const EVENT_KEY = "." + DATA_KEY;
const ClassName = {
CREATE_BOX: "modal-container",
MODAL: 'modal',
MODAL_LG: 'modal-lg',
MODAL_DIALOG: 'modal-dialog',
MODAL_CONTENT: 'modal-content',
MODAL_HEADER: 'modal-header',
MODAL_BODY: 'modal-body',
MODAL_FOOTER: 'modal-footer',
BODY: 'body',
SAVE_BUTTON: 'save-btn',
CLEAN: 'error valid not-clean invalid valid',
NOT_CLEAN_TAG: 'not-clear-tag',
DEFAULT_VALUE: 'default-value',
AJAX_SELECT: 'ajax-select',
AJAX_SELECT_SET_VALUE: 'set-value',
AJAX_SELECT_CODE: 'code-key',
DRAG_SELECT: "drag-select",
INVALID_FEEDBACK: "invalid-feedback",
INVALID_FEEDBACK_SHOW: "invalid-feedback-show"
}
const Selector = {
CREATE_BOX: ".modal-container",
MODAL_DIALOG: '.modal-dialog',
MODAL_CONTENT: '.modal-content',
MODAL_HEADER: '.modal-header',
MODAL_TITLE: '.modal-title',
MODAL_TITLE_PRE: '.modal-title .pre',
MODAL_BODY: '.modal-body',
MODAL_FOOTER: '.modal-footer',
MODAL_TAB_LINK: '.tab-auto .nav-item .nav-link',
SAVE_BUTTON: `.${ClassName.SAVE_BUTTON}`,
CLEAN: 'input,select,textarea',
DISABLED: 'input:not(.disabled),select:not(.disabled),textarea:not(.disabled)',
READONLY: 'input:not(.readonly),select:not(.readonly),textarea:not(.readonly)',
CLEAN_VALUE: `input:not(.${ClassName.DEFAULT_VALUE}):not([type="checkbox"]):not([type="radio"]):not(.${ClassName.NOT_CLEAN_TAG}),select:not(.${ClassName.DEFAULT_VALUE}):not(.${ClassName.NOT_CLEAN_TAG}),textarea:not(.${ClassName.DEFAULT_VALUE}):not(.${ClassName.NOT_CLEAN_TAG})`,
NOT_CLEAN_TAG: `.${ClassName.NOT_CLEAN_TAG}`,
FORM_FIRST: 'input:not(:disabled,[type="hidden"],[readonly="readonly"]):first',
select2: '.select',
select2tree: 'select[data-select-tree="true"]',
AJAX_SELECT: `.${ClassName.AJAX_SELECT}`,
WANG_EDITOR: 'div.vb-wang-editor',
INPUT_FILE: 'input[type="file"]',
SUBMIT_INPUT: '.modal-body input,.modal-body textarea',
INVALID_FEEDBACK: `.${ClassName.INVALID_FEEDBACK}`
}
const JQUERY_NO_CONFLICT = $.fn[NAME];
const ALLOW_METHOD = [
'open',
'show',
'hide',
'create'
];
const WangEditor_DATA_KEY = "WangEditor_DATA_KEY";
const Default = {
modal: undefined,
title: '',
opTitle: '',
data: null,
dataFun: undefined,
form: null,
table: undefined,
rules: {},
readonly: '',
disabled: '',
notClear: '',
select2: undefined,
select2tree: undefined,
url: '',
type: 'post',
saveBtn: null,
save: null,
success: null,
showBefore: null,
showAfter: null,
isRefresh: true,
draggable: true,
backdrop: 'static',
keyboard: true,
//kindeditorOption: {},
content: undefined,
ajaxSelect: true,
needForm: true,
isInit: true,
}
let Modal = function () {
function Modal(element, config, isCreate) {
this._element = element;
this._config = config;
if (!isCreate) {
this._getModal(config);
}
}
let _proto = Modal.prototype;
_proto._getModal = function (opts, modal) {
let _this = this;
_this._config = $.extend({}, _this._config, opts || {});
let $modal;
if (modal) {
$modal = typeof (modal) === 'string'
? $('#' + modal)
: $(modal);
} else {
$modal = _this._config.modalId
? $('#' + _this._config.modalId)
: typeof (_this._config.modal) === 'string'
? $('#' + _this._config.modal)
: $(_this._config.modal);
}
if ($(_this._element).hasClass(ClassName.MODAL)) {
if ($modal.length) {
_this._element = $modal[0];
} else {
$modal = $(_this._element);
}
} else {
if (!$modal.length) {
throw new Error("未发现模态框!");
}
if (!_this._config.modal && !_this._config.modalId) {
throw new Error("未配置模态框!");
}
_this._element = $modal[0];
}
return $modal;
};
_proto._init = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
_this._clearOldVal();
$modal.find(Selector.INVALID_FEEDBACK).html("").removeClass(ClassName.INVALID_FEEDBACK_SHOW);
$modal.find(Selector.CLEAN).removeClass(ClassName.CLEAN);
$modal.find(Selector.INVALID_FEEDBACK).removeClass(ClassName.INVALID_FEEDBACK_SHOW);
$modal.find(Selector.DISABLED).prop('disabled', false);
$modal.find(Selector.READONLY).prop('readonly', false);
$modal.find(Selector.MODAL_TITLE_PRE).html(_config.opTitle);
$modal.find(Selector.MODAL_TAB_LINK).eq(0).tab("show");
_this._setReadonly();
_this._setDisabled();
_this._cleanFile();
$modal.find(Selector.FORM_FIRST).focus();
};
_proto._setReadonly = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
if (_config.readonly) {
let readonly = _config.readonly.split(',');
for (let i = 0; i < readonly.length; i++) {
if (readonly[i]) {
$modal.find(`[name="${readonly[i]}"]`).prop('readonly', true);
}
}
}
if (_config.no_readonly) {
let no_readonly = _config.no_readonly.split(',');
for (let j = 0; j < no_readonly.length; j++) {
if (no_readonly[j]) {
$modal.find(`[name="${no_readonly[j]}"]`).prop('readonly', false);
}
}
}
};
_proto._setDisabled = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
if (_config.disabled) {
let disabled = _config.disabled.split(',');
for (let i = 0; i < disabled.length; i++) {
if (disabled[i]) {
$modal.find(`[name="${disabled[i]}"]`).prop('disabled', true);
}
}
}
if (_config.no_disabled) {
let no_disabled = _config.no_disabled.split(',');
for (let j = 0; j < no_disabled.length; j++) {
if (no_disabled[j]) {
$modal.find(`[name="${no_disabled[j]}"]`).prop('disabled', true);
}
}
}
};
_proto._setSelect2 = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
if (_config.select2) {
let select2 = _config.select2.split(',');
for (let i = 0; i < select2.length; i++) {
$modal.find(`[name="${select2[i]}"]`).select2tree();
}
}
if (_config.select2tree) {
let tree = _config.select2tree.split(',');
for (let j = 0; j < tree.length; j++) {
$modal.find(`[name="${tree[j]}"]`).select2tree();
}
}
$modal.find('select').trigger("change");
$modal.find('select').off("change.ff").on("change.ff", function () {
$(this).focus();
$(this).removeClass(ClassName.CLEAN).parent().find(Selector.INVALID_FEEDBACK).removeClass(ClassName.INVALID_FEEDBACK_SHOW);
$(this).blur();
});
};
_proto._setData = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
let $form = $modal.find('form');
$(Selector.AJAX_SELECT).addClass(ClassName.AJAX_SELECT_SET_VALUE);
$.formDeserialize($form, _config.data);
};
_proto._clearOldVal = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
if (_config.notClear) {
let notClear = _config.notClear.split(',');
for (let i = 0; i < notClear.length; i++) {
if (notClear[i]) {
$modal.find(`[name="${notClear[i]}"]`).addClass(ClassName.NOT_CLEAN_TAG);
}
}
}
$modal.find(Selector.CLEAN_VALUE).val('');
$modal.find(Selector.NOT_CLEAN_TAG).removeClass(ClassName.NOT_CLEAN_TAG);
};
_proto._initWangEditor = function () {
let _this = this, $modal = $(_this._element);
$modal.find(Selector.WANG_EDITOR).each(function () {
if ($.fn.VbWangEditor) {
if (!$(this).data('vb.wang_editor')) {
let config = _this._config.wangEditorOption || {};
$(this).VbWangEditor(config);
$(this).data(WangEditor_DATA_KEY, true);
}
}
});
};
_proto._setWangEditorData = function () {
let _this = this, $modal = $(_this._element);
$modal.find(Selector.WANG_EDITOR).each(function () {
if ($.fn.VbWangEditor) {
if ($(this).data('vb.wang_editor')) {
let val = $modal.find(`[name="${$(this).data('editor-name')}"]`).val();
$(this).VbWangEditor('setContent', val);
}
}
});
};
_proto._cleanFile = function () {
let _this = this, $modal = $(_this._element);
$modal.find(Selector.INPUT_FILE).each(function () {
//TODO
//$(this).parent().VbFile('cleanFile');
});
};
_proto._draggable = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
if (_config.draggable) {
/** 拖拽模态框*/
let dragModal = {
mouseStartPoint: { 'left': 0, 'top': 0 },
mouseEndPoint: { 'left': 0, 'top': 0 },
mouseDragDown: false,
basePoint: { 'left': 0, 'top': 0 },
moveTarget: null,
topLeng: 0
};
$modal.off('mousedown.drag' + EVENT_KEY, Selector.MODAL_HEADER).on('mousedown.drag' + EVENT_KEY,
Selector.MODAL_HEADER,
function (e) {
$modal.find(Selector.MODAL_HEADER).css('cursor', 'move');
//webkit内核和火狐禁止文字被选中
$('body').addClass(ClassName.DRAG_SELECT);
//ie浏览器禁止文字选中
document.body.onselectstart = document.body.ondrag = function () {
return false;
};
if ($(e.target).hasClass('close')) //点关闭按钮不能移动对话框
return;
dragModal.mouseDragDown = true;
dragModal.moveTargetHeader = $(this);
dragModal.moveTarget = $(this).closest(Selector.MODAL_CONTENT);
dragModal.mouseStartPoint = { 'left': e.clientX, 'top': e.pageY };
dragModal.basePoint = dragModal.moveTarget.offset();
dragModal.topLeng = e.pageY - e.clientY;
});
$modal.off(`mouseup.drag${EVENT_KEY}`).on(`mouseup.drag${EVENT_KEY}`,
function () {
$modal.find(Selector.MODAL_HEADER).css('cursor', 'default');
dragModal.mouseDragDown = false;
dragModal.moveTarget = undefined;
dragModal.mouseStartPoint = { 'left': 0, 'top': 0 };
dragModal.basePoint = { 'left': 0, 'top': 0 };
});
$modal.off(`mousemove.drag${EVENT_KEY}`).on(`mousemove.drag${EVENT_KEY}`,
function (e) {
if (!dragModal.mouseDragDown || dragModal.moveTarget === undefined) return;
$modal.find(Selector.MODAL_HEADER).css('cursor', 'move');
let mouseX = e.clientX;
let mouseY = e.pageY;
if (mouseX < 0) mouseX = 0;
if (mouseY < 0) mouseY = 25;
dragModal.mouseEndPoint = { 'left': mouseX, 'top': mouseY };
let width = dragModal.moveTarget.width();
let height = dragModal.moveTargetHeader.height();
let clientWidth = document.body.clientWidth;
let clientHeight = document.body.clientHeight;
if (dragModal.mouseEndPoint.left < dragModal.mouseStartPoint.left - dragModal.basePoint.left) {
dragModal.mouseEndPoint.left = 0;
} else if (dragModal.mouseEndPoint.left >=
clientWidth - width + dragModal.mouseStartPoint.left - dragModal.basePoint.left) {
dragModal.mouseEndPoint.left = clientWidth - width - 2;
} else {
dragModal.mouseEndPoint.left =
dragModal.mouseEndPoint.left -
(dragModal.mouseStartPoint.left - dragModal.basePoint.left); //移动修正,更平滑
}
if (dragModal.mouseEndPoint.top - (dragModal.mouseStartPoint.top - dragModal.basePoint.top) <
dragModal.topLeng) {
dragModal.mouseEndPoint.top = dragModal.topLeng;
} else if (dragModal.mouseEndPoint.top - dragModal.topLeng >
clientHeight - height + dragModal.mouseStartPoint.top - dragModal.basePoint.top) {
dragModal.mouseEndPoint.top = clientHeight - height - 38 + dragModal.topLeng;
} else {
dragModal.mouseEndPoint.top = dragModal.mouseEndPoint.top -
(dragModal.mouseStartPoint.top - dragModal.basePoint.top);
}
dragModal.moveTarget.offset(dragModal.mouseEndPoint);
});
$modal.off(`hidden.bs.modal${EVENT_KEY}.drag`).on(`hidden.bs.modal${EVENT_KEY}.drag`, function () {
$modal.find(Selector.MODAL_HEADER).css('cursor', 'default');
$modal.find(Selector.MODAL_CONTENT).css({ 'top': 0, 'left': 0 });
$('body').removeClass(ClassName.DRAG_SELECT);
document.body.onselectstart = document.body.ondrag = null;
});
} else {
$modal.find(Selector.MODAL_HEADER).css('cursor', 'default');
}
};
_proto._showBefore = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
if (_config.showBefore && typeof (_config.showBefore) === 'function') {
_config.showBefore.call(_this, $modal);
}
};
_proto._showAfter = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
if (_config.showAfter && typeof (_config.showAfter) === 'function') {
_config.showAfter.call(_this, $modal);
}
};
_proto._shown = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
if (_config.shown && typeof (_config.shown) === 'function') {
_config.shown.call(_this, $modal);
}
};
_proto._bindEvent = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
$modal.off(`show.bs.modal${EVENT_KEY}`).on(`show.bs.modal${EVENT_KEY}`,
function () {
_this._draggable();
_this._showBefore();
if (_config.isInit) {
_this._init();
}
_this._initWangEditor();
_this._setData();
_this._setSelect2();
_this._setWangEditorData();
_this._bindSave();
$.formValidate($modal.find('form'), { noValid: true });
_this._showAfter();
});
$modal.off(`shown.bs.modal${EVENT_KEY}`).on(`shown.bs.modal${EVENT_KEY}`,
function () {
_this._shown();
});
};
_proto._bindSave = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
let $saveBtn = _config.saveBtn
? $(_config.saveBtn)
: $modal.find(Selector.SAVE_BUTTON);
if (!$saveBtn.length) {
//throw new Error("未发现保存按钮");
debug_log("未发现保存按钮");
return;
}
let opt = _this._getSaveOptions(), ajaxSelectFun;
if (_config.ajaxSelect) {
ajaxSelectFun = function () {
$modal.find('select' + Selector.AJAX_SELECT).each(function () {
let $this = $(this);
let cKey = $this.data(ClassName.AJAX_SELECT_CODE),
val = $this.val(),
name = $this.find("option[value='" + val + "']").text(), ran = Math.floor(Math.random() * 9999);
debug_log('AjaxSelect[{3}]:{0}-{1}-{2}'.format(cKey, val, name, ran));
$.vbAjax41({
url: abp.appUrl + "Query/AddAcInfo",
data: {
CodeKey: cKey,
ValueKey: val,
NameKey: name
},
success: function () {
debug_log('AjaxSelect[{0}]:Success'.format(ran));
}
});
});
}
}
let save = null;
if (_config.save && typeof (_config.save) === "function") {
save = function () { _config.save(opt); };
} else if (_config.url) {
save = function () { $.vbAjax(_config.url, opt); };
}
let saveFun =
function () {
if (save && $.isFunction(save)) {
save();
}
if (ajaxSelectFun && $.isFunction(ajaxSelectFun)) {
ajaxSelectFun();
}
}
$saveBtn.off('click.save').on('click.save', saveFun);
$modal.find('.modal-body input').keydown(function (e) {
if (e.which === 13) {
if (e.target.tagName.toLocaleLowerCase() === "textarea") {
e.stopPropagation();
} else {
e.preventDefault();
saveFun.call(_this);
}
}
});
};
_proto._getSaveOptions = function () {
let _this = this, _config = _this._config, $modal = $(_this._element);
let $form = $modal.find('form');
if (!$form.length && _config.needForm) {
throw new Error("未发现表单");
}
return {
url: _config.url,
type: _config.type,
table: _config.table,
success: _config.success,
form: $form,
data: null,
dataFun: _config.dataFun,
isValidate: _config.fromValidate,
modal: _config.modal,
blockUI: true,
isRefresh: _config.isRefresh,
isAlert: _config.isAlert
};
};
_proto._show = function ($modal) {
let _this = this, _config = _this._config;
$modal.modal({ backdrop: _config.backdrop, keyboard: _config.keyboard });
$modal.modal('show');
};
_proto.open = function (opts, modal) {
let _this = this;
let $modal = _this._getModal(opts, modal);
_this._bindEvent();
_this._show($modal);
}
_proto.show = function (opts, modal) {
let _this = this;
let $modal = _this._getModal(opts, modal);
_this._bindEvent();
_this._config.isInit = false;
_this._show($modal);
};
_proto.hide = function () {
let _this = this, $modal = $(_this._element);
return $modal.modal('hide');
};
_proto.create = function (opts) {
let _this = this, _config = _this._config = $.extend({}, _this._config, opts);
if (!_config.modalId) {
if (_config.modal) {
_config.modalId = typeof (_config.modal) === 'string' ? _config.modal : $(_config.modal).attr('id');
} else {
_config.modalId = `modal_${Math.floor(Math.random() * 10000000)}`;
}
}
let dialogClass = _config.modalSize === null ?
_config.modalSize = "" :
_config.modalSize ?
_config.modalSize :
ClassName.MODAL_LG;
if (_config.dialogClass) {
dialogClass += _config.dialogClass;
}
let dialogStyle = _config.width ? `max-width:${_config.width}px;` : "";
if (_config.dialogStyle) {
dialogStyle += _config.dialogStyle;
}
let containerId = `modal-container_${_config.modalId}`;
if ($('#' + containerId).length) {
$('#' + containerId).remove();
}
let $container = $(`
`);
let $modalContent = $container.find(Selector.MODAL_CONTENT);
if (_config.content) {
$modalContent.append(_config.content);
} else if (_config.modalBody) {
let modalHeader = _config.modalHeader != undefined
? _config.modalHeader
: ``;
let modalBody = `${_config.modalBody}
`;
let modalFooter = _config.modalFooter != undefined
? _config.modalFooter
: ``;
$modalContent.append(modalHeader);
$modalContent.append(modalBody);
$modalContent.append(modalFooter);
}
$('body').append($container);
if (!$(_this._element).hasClass(ClassName.MODAL)) {
_this._element = $('#' + _config.modalId)[0];
}
_this.show();
}
Modal._jQueryInterface = function _jQueryInterface(option) {
let value;
let data = $(this).data(DATA_KEY);
let args = Array.prototype.slice.call(arguments, 1);
let _options = $.extend(true, {}, Default, (typeof option == "string" ? {} : option) || {});
if (typeof option === 'string') {
if ($.inArray(option, ALLOW_METHOD) < 0) {
throw new Error("Unknown method: " + option);
}
if (!data) {
data = new Modal($(this), _options, option == "create");
}
value = data[option].apply(data, args);
} else {
if (!data) {
data = new Modal($(this), _options);
$(this).data(DATA_KEY, data);
}
data.open(_options);
}
return typeof value === 'undefined' ? this : value;
};
return Modal;
}();
/*
* jQuery API
* ====================================================
*/
$.fn[NAME] = Modal._jQueryInterface;
$.fn[NAME].Constructor = Modal;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Modal._jQueryInterface;
};
}((jQuery));
let VbFile = function ($) {
const NAME = 'VbFile';
const DATA_KEY = 'vb.File';
const EVENT_KEY = "." + DATA_KEY;
const ClassName = {
FILE_URL: "vb-file-url",
FILE_TYPE: "vb-file-type",
MODAL_IMAGE: 'vb-image-modal',
MODAL_FILE: 'vb-file-modal',
IMAGE_URL_NAME: 'data-vb-image-url',
DOWNLOAD: 'download',
TEMPLINK: 'tempLink-fd',
TARGET_INFO: "vb-file-target-info",
TARGET_NAME: "vb-file-target-name",
TARGET_EXT: "vb-file-target-ext",
IS_IMAGE: "vb-file-image",
MAX_SIZE: "vb-file-max-size",
FILE_BOX: 'vb-file-box',
FILE_CLEAN_BTN: 'vb-file-btn="clean"',
VALID_CLASS: "valid",
INVALID_CLASS: "invalid",
INVALID_FEEDBACK: "invalid-feedback",
INVALID_FEEDBACK_SHOW: "invalid-feedback-show"
}
const Selector = {
FILE_UPLOAD: `[data-vb-file="upload"]`,
FILE_SHOW: `[data-vb-file="show"]`,
MODAL_IMAGE: `#${ClassName.MODAL_IMAGE}`,
MODAL_FILE: `#${ClassName.MODAL_FILE}`,
DOWNLOAD: `#${ClassName.DOWNLOAD}`,
TEMPLINK: `#${ClassName.TEMPLINK}`,
FILE_INPUT: 'input[type="file"]',
FILE_BOX: `[data-${ClassName.FILE_BOX}]`,
FILE_CLEAN_BTN: `[data-${ClassName.FILE_CLEAN_BTN}]`,
INVALID_FEEDBACK: `.${ClassName.INVALID_FEEDBACK}`
}
const JQUERY_NO_CONFLICT = $.fn[NAME];
const ALLOW_METHOD = [
'show',
'showImage',
'showOffice',
'showFile',
'download',
'upload',
'cleanFile'
];
const Default = {
url: undefined,
type: 'img',
maxSize: 2,
isImage: false,
targetInfo: undefined,
targetName: "fileName",
targetExt: "fileExt",
callback: undefined
}
let File = function () {
function File(element, config) {
this._element = element;
this._config = config;
}
let _proto = File.prototype;
_proto.show = function () {
let _this = this, _config = _this._config, _el = _this._element;
let config = {
url: _config.url ? _config.url : $(_el).data(ClassName.FILE_URL),
type: _config.type ? _config.type : $(_el).data(ClassName.FILE_TYPE)
};
if (!url) {
throw new Error("Need URL");
return;
}
switch (config.type.toLowerCase()) {
case 'img':
case 'image':
this.showImage(config.url);
break;
case 'office':
case 'doc':
case 'docx':
this.showOffice(config.url);
break;
default:
this.showFile(config.url);
return;
}
};
_proto.showImage = function (url, config) {
if (!url) {
return;
}
let _this = this;
$.metPageCss('/Libs/viewerjs/dist/viewer.min.css', "dy-css-viewer");
$.metPageJs('/Libs/viewerjs/dist/viewer.min.js', "dy-js-viewer");
let Viewer = window.Viewer;
if ($(Selector.MODAL_IMAGE).length > 0) {
$(Selector.MODAL_IMAGE).remove();
}
let urls = url.split(",");
let $ul = $(``);
for (let i = 0; i < urls.length; i++) {
$ul.append(`
`);
}
$ul.appendTo($('body'));
let $image = $(Selector.MODAL_IMAGE), imageView;
let options = $.extend({}, {
// inline: true,
url: ClassName.IMAGE_URL_NAME,
button: true,
navbar: urls.length > 1,
title: false,
toolbar: true,
ready: function (e) {
console.log(e.type);
},
show: function (e) {
console.log(e.type);
},
shown: function (e) {
console.log(e.type);
},
hide: function (e) {
console.log(e.type);
},
view: function (e) {
console.log(e.type);
},
viewed: function (e) {
console.log(e.type);
},
move: function (e) {
console.log(e.type);
},
moved: function (e) {
console.log(e.type);
},
hidden: function () {
imageView.destroy();
$image.remove();
}
}, _this._config, config || {}, { url: ClassName.IMAGE_URL_NAME });
imageView = new Viewer($image[0], options);
imageView.show();
//$image.viewer("show");
$image.css("display", "none");
};
_proto.showOffice = function (url, office_url) {
let _this = this;
url = (office_url || OFFICEURL) + window.location.host + url;
_this.showFile(url);
};
_proto.showFile = function (url) {
let _this = this;
$(document).VbModal('create',
{
modal: ClassName.MODAL_FILE,
title: '文件预览',
dialogStyle: "min-width: calc(100% - 600px);",
modalBody: ``,
modalFooter: ``,
showAfter: function () {
$(Selector.MODAL_FILE + " " + Selector.DOWNLOAD).off('click.download' + EVENT_KEY).on('click.download' + EVENT_KEY, function () { _this.download(url) });
}
});
};
_proto.download = function (url) {
let _this = this;
url = url || _this.config.url;
if ($(Selector.TEMPLINK).length > 0) {
$(Selector.TEMPLINK).remove();
}
$('body').append(``);
$(Selector.TEMPLINK)[0].click();
$(Selector.TEMPLINK).remove();
};
_proto.upload = function () {
let _this = this, $this = $(_this._element), _config = _this._config, $file = _this._getFile();
let targetInfo = $file.data(ClassName.TARGET_INFO), targetName = $file.data(ClassName.TARGET_NAME), targetExt = $file.data(ClassName.TARGET_EXT), isImage = $file.data(ClassName.IS_IMAGE), maxSize = $file.data(ClassName.MAX_SIZE);
if (targetInfo) {
_config.targetInfo = targetInfo;
}
if (targetName) {
_config.targetName = targetName;
}
if (targetExt) {
_config.targetExt = targetExt;
}
if (isImage === "true" || isImage === "1" || isImage === "y" || isImage === "Y" || isImage === "True") {
_config.isImage = true;
}
if (maxSize) {
_config.maxSize = maxSize;
}
$file.off('change' + EVENT_KEY).on('change' + EVENT_KEY, function () {
_this._fileCheck();
});
$file.removeClass(ClassName.INVALID_CLASS).removeClass(ClassName.VALID_CLASS);
$this.closest(Selector.FILE_BOX).parent().find(Selector.INVALID_FEEDBACK).empty().removeClass(ClassName.INVALID_FEEDBACK_SHOW);
$this.closest(Selector.FILE_BOX).find(Selector.FILE_CLEAN_BTN).off('click' + EVENT_KEY).on('click' + EVENT_KEY, () => { _this.cleanFile(); });
};
_proto.cleanFile = function () {
let _this = this, $this = $(_this._element);
let $file = _this._getFile();
let $fileBox = $this.closest(Selector.FILE_BOX);
$file.removeClass(ClassName.INVALID_CLASS).removeClass(ClassName.VALID_CLASS);
$this.closest(Selector.FILE_BOX).parent().find(Selector.INVALID_FEEDBACK).empty().removeClass(ClassName.INVALID_FEEDBACK_SHOW);
$fileBox.find('input').val('');
$file.after($file.clone().val(""));
$file.remove();
$fileBox.find(Selector.FILE_INPUT).off('change' + EVENT_KEY).on('change' + EVENT_KEY, () => { _this._fileCheck(); });
};
_proto._fileCheck = function () {
let _this = this, _config = _this._config;
let $file = _this._getFile();
if (_this._checkSize()) {
let fileName = $file.val().split("\\").pop();
//$this.closest(Selector.FILE_BOX).addClass(ClassName.FILE_SUCCESS).find("label").text(fileName);
let file = $file[0].files[0];
_this._readFile(file);
if (_config.targetName && _config.targetName !== undefined) {
let name = fileName.substring(0, fileName.lastIndexOf("."));
if (!_config.targetName)
return;
let targetName = _config.targetName.split(',');
for (let i = 0; i < targetName.length; i++) {
$(`[name="${targetName[i]}"]`).val(name);
}
}
if (_config.targetExt && _config.targetExt !== undefined) {
let ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
if (!_config.targetExt)
return;
let targetExt = _config.targetExt.split(',');
for (let j = 0; j < targetExt.length; j++) {
$(`[name="${targetExt[j]}"]`).val(ext);
}
}
let callback = _config.callback;
if (callback && typeof (callback) === "function") {
callback(fileName, file);
}
} else {
//let target = _config.targetInfo ? _config.targetInfo : $file.attr('id').replace('_file', '');
//$file.addClass(ClassName.INVALID_CLASS);
//$(`[name="${_config.targetInfo}"]`).closest(Selector.FILE_BOX).parent().find(Selector.INVALID_FEEDBACK).html(abp.localization.VberZero('SelectFile')).addClass(ClassName.INVALID_FEEDBACK_SHOW);
}
};
_proto._checkSize = function () {
let _this = this, _config = _this._config;
let $file = _this._getFile();
let maxsize = _config.maxSize * 1024 * 1024;
//let errMsg = "上传的附件文件不能超过" + _config.maxSize + "M。";
//let tipMsg = "您的浏览器暂不支持计算上传文件的大小,确保上传文件不要超过" + _config.maxSize + "M,建议使用IE、FireFox、Chrome浏览器。";
let errMsg = abp.localization.VberZero('FileUploadErrorMsg', _config.maxSize);
let tipMsg = abp.localization.VberZero('FileUploadTipMsg', _config.maxSize);
let browserCfg = {};
let ua = window.navigator.userAgent;
if (ua.indexOf("MSIE") >= 1) {
browserCfg.ie = true;
} else if (ua.indexOf("Firefox") >= 1) {
browserCfg.firefox = true;
} else if (ua.indexOf("Chrome") >= 1) {
browserCfg.chrome = true;
}
try {
let objFile = $file[0];
if (objFile.value === "") {
//layer.alert("请先选择上传文件", { icon: 7, title: "提示信息" });
return false;
}
let filesize;
if (browserCfg.firefox || browserCfg.chrome) {
filesize = objFile.files[0].size;
} else if (browserCfg.ie) {
let objImg = document.createElement("img");
objImg.id = "tempImg";
objImg.style.display = "none";
document.body.appendChild(objImg);
objImg.dynsrc = objFile.value;
filesize = objImg.fileSize;
} else {
_this.cleanFile();
abp.message.warn(tipMsg);
return false;
}
if (filesize === -1) {
_this.cleanFile();
abp.message.warn(tipMsg);
return false;
} else if (filesize > maxsize) {
_this.cleanFile();
abp.message.warn(errMsg);
return false;
} else {
return true;
}
} catch (e) {
_this.cleanFile();
abp.message.error(e);
return false;
}
};
_proto._readFile = function (file) {
let _this = this, _config = _this._config;
let $file = _this._getFile();
file = file || $file[0].files[0];
if (!file) {
return;
}
if (_config.isImage && !/image\/\w+/.test(file.type)) {
abp.message.warn(abp.localization.VberZero('FileUploadOnlyImage'));
_this.cleanFile();
return;
}
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
let fileinfo = this.result.substring(this.result.indexOf(',') + 1);
//let target = _config.targetInfo ? _config.targetInfo : $file.attr('id').replace('_file', '');
$(`[name="${_config.targetInfo}"]`).val(fileinfo);
};
};
_proto._getFile = function () {
let _this = this, $this = $(_this._element);
let $file = $this.closest(Selector.FILE_BOX).find(Selector.FILE_INPUT);
return $file;
};
File._jQueryInterface = function _jQueryInterface(option) {
let value, args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
let data = $(this).data(DATA_KEY);
let _options = $.extend({}, Default, $(this).data(), typeof option === 'object' && option || {});
if (!data) {
data = new File(this, _options);
$(this).data(DATA_KEY, data);
}
if (!option) {
value = data.show();
} else if (typeof option === 'string') {
if ($.inArray(option, ALLOW_METHOD) < 0) {
throw new Error("Unknown method: " + option);
}
value = data[option].apply(data, args);
}
});
return typeof value === 'undefined' ? this : value;
};
return File;
}();
$(window).on("load" + EVENT_KEY, function () {
$(Selector.FILE_UPLOAD).each(function () {
File._jQueryInterface.call($(this), "upload");
});
$(Selector.FILE_SHOW).each(function () {
File._jQueryInterface.call($(this), "show");
});
});
/*
* jQuery API
* ====================================================
*/
$.fn[NAME] = File._jQueryInterface;
$.fn[NAME].Constructor = File;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return File._jQueryInterface;
};
}((jQuery));
let VbDate = function ($) {
const NAME = 'VbDate';
const DATA_KEY = 'vb.date';
const EVENT_KEY = "." + DATA_KEY;
const ClassName = {
}
const Selector = {
DATE: `[data-vb-date="date"]`,
DATETIME: `[data-vb-date="date-time"]`,
RANGEDATE: `[data-vb-date="r_date"]`,
RANGEDATETIME: `[data-vb-date="r_date-time"]`,
}
const JQUERY_NO_CONFLICT = $.fn[NAME];
const ALLOW_METHOD = [
"load",
"date",
"dateTime",
"dateRange",
"dateTimeRange",
"setValue",
];
const Default = {
//altInput: true,
//altFormat: "Y-m-d",
//allowInput: true,
time_24hr: true,
//wrap: true,//外部元素
//minDate: undefined,
//maxDate: undefined,
//minTime: undefined,
//maxTime: undefined,
//showMonths: 1,//显示的月份数
//mode: undefined,//single,multiple,range
//noCalendar: true,
//weekNumbers: false,//显示第多少周
//enableTime: false,
//hourIncrement: 1, //调整小时输入的步进(包括滚动)
//minuteIncrement: 5,//
//enableSeconds: false,
//defaultDate: undefined,// ["2025-01-05", "2025-01-10"]
//defaultHour: undefined,
//defaultMinute: undefined,
//dateFormat: "Y-m-d H:i",
//disable: undefined,//(disable 禁用日期, enable 禁用其余日期) ["2025-01-10", "22025-01-11"] [ { from: "2025-01-05", to: "2025-01-25" },{...}]
//inline: false,//始终打开状态显示日历
//position: "auto",
//preletrow: "<",//箭头图标的HTML,用于切换月份
//nextArrow: ">"
}
let Date = function () {
function Date(element, config) {
this._element = element;
this._config = config;
}
let _proto = Date.prototype;
_proto._getHtmlOption = function () {
let _this = this, data = $(_this._element).data();
let htmlOption = {};
//htmlOption.mode = data.mode;
htmlOption.defaultDate = data.dateDefaultDate;
htmlOption.defaultHour = data.dateDefaultHour;
htmlOption.defaultMinute = data.dateDefaultMinute;
htmlOption.minDate = data.dateMinDate;
htmlOption.maxDate = data.dateMaxDate;
htmlOption.minTime = data.dateMinTime;
htmlOption.maxTime = data.dateMaxTime;
//htmlOption.enableTime = data.dateEnableTime;
htmlOption.dateFormat = data.dateFormat;
htmlOption.disable = data.dateDisable;
htmlOption.noCalendar = data.dateNoCalendar;
htmlOption.inline = data.dateInline;
htmlOption.showMonths = data.dateShowMonths;
htmlOption.hourIncrement = data.dateHourIncrement;
htmlOption.minuteIncrement = data.dateMinuteIncrement;
htmlOption.enableSeconds = data.dateEnableSeconds;
return htmlOption;
};
_proto._extendOption = function (options) {
let _this = this, _config = _this._config;
let opt = $.extend(true, {}, _config, options || {});
if (opt.noCalendar) {
opt.enableTime = true;
opt.dateFormat = "H:i";
}
if (!opt.dateFormat) {
opt.dateFormat = opt.noCalendar ? "" : "Y-m-d";
if (opt.enableTime) {
opt.dateFormat = opt.dateFormat ? `${opt.dateFormat} H:i` : "H:i";
}
}
opt.locale = window.lang == "zh-CN" ? "zh" : window.lang;
_config = opt;
return opt;
};
_proto.date = function (options) {
let _this = this;
let opt = $.extend(true, {}, _this._getHtmlOption(), options || {});
opt.mode = "single";
opt.enableTime = false;
opt.dateFormat = "Y-m-d";
_this.load(opt);
};
_proto.dateRange = function (options) {
let _this = this;
let opt = $.extend(true, {}, _this._getHtmlOption(), options || {});
opt.enableTime = false;
opt.dateFormat = "Y-m-d";
opt.mode = "range";
_this.load(opt);
};
_proto.dateTime = function (options) {
let _this = this;
let opt = $.extend(true, {}, _this._getHtmlOption(), options || {});
opt.enableTime = true;
opt.dateFormat = "Y-m-d H:i";
opt.mode = "single";
_this.load(opt);
};
_proto.dateTimeRange = function (options) {
let _this = this;
let opt = $.extend(true, {}, _this._getHtmlOption(), options || {});
opt.enableTime = true;
opt.dateFormat = "Y-m-d H:i";
opt.mode = "range";
_this.load(opt);
};
_proto.load = function (options) {
let _this = this, _config = _this._config, _el = _this._element;
let opt = options || _this._getHtmlOption();
let option = _this._extendOption(opt)
debug_log("DateTime:", $(_el).attr('name'), option);
_config.vbDate = $(_el).flatpickr(option);
}
_proto.setValue = function (value) {
let _this = this, _config = _this._config;
let format = _config.noCalendar ? "Y-m-d H:i" : _config.dateFormat;
_config.vbDate.setDate(value, true, format);
debug_log("date_setValue", value, format, $(_this._el).val());
}
Date._jQueryInterface = function _jQueryInterface(option) {
let value, args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
let data = $(this).data(DATA_KEY);
let _options = $.extend({}, Default, $(this).data(), typeof option === 'object' && option || {});
if (!data) {
data = new Date(this, _options);
$(this).data(DATA_KEY, data);
}
if (!option) {
value = data.load();
} else if (typeof option === 'string') {
if ($.inArray(option, ALLOW_METHOD) < 0) {
throw new Error("Unknown method: " + option);
}
value = data[option].apply(data, args);
}
});
return typeof value === 'undefined' ? this : value;
};
return Date;
}();
$(window).on("load" + EVENT_KEY, function () {
$(Selector.DATE).each(function () {
Date._jQueryInterface.call($(this), "date");
});
$(Selector.DATETIME).each(function () {
Date._jQueryInterface.call($(this), "dateTime");
});
$(Selector.RANGEDATE).each(function () {
Date._jQueryInterface.call($(this), "dateRange");
});
$(Selector.RANGEDATETIME).each(function () {
Date._jQueryInterface.call($(this), "dateTimeRange");
});
});
/*
* jQuery API
* ====================================================
*/
$.fn[NAME] = Date._jQueryInterface;
$.fn[NAME].Constructor = Date;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Date._jQueryInterface;
};
}((jQuery));
let VbTreeView = function ($) {
let NAME = 'VbTreeView';
let DATA_KEY = 'vb.tree_view';
//let EVENT_KEY = "." + DATA_KEY;
//let Selector = {
//}
//let ClassName = {
//}
let JQUERY_NO_CONFLICT = $.fn[NAME];
let Default = {
url: undefined,
data: undefined,
levels: 2,
showCheckbox: false,
checkedIcon: 'far fa-check-square',
uncheckedIcon: 'far fa-square',
emptyIcon: 'fas fa-square',
collapseIcon: 'fas fa-minus-square',
expandIcon: 'fas fa-plus-square',
color: '',
selectedBackColor: '',
selectedColor: '',
table: 'table',
selectFiledName: 'id',
selectFiledInput: 'keyWords'
}
let ALLOW_METHOD = [
'init'
];
//[
// {
// id: "1",
// text: "Parent 1",
// nodes: [
// {
// id: "1-1",
// text: "Child 1",
// nodes: [
// {
// id: "1-1-1",
// text: "Grandchild 1"
// },
// {
// id: "1-1-2",
// text: "Grandchild 2"
// }
// ]
// },
// {
// id: "1-2",
// text: "Child 2"
// }
// ]
// },
// {
// id: "2",
// text: "Parent 2"
// }
//];
let TreeView = function () {
function TreeView(element, config) {
this._element = element;
this._config = config;
this.init();
}
// Public
let _proto = TreeView.prototype;
_proto.init = function () {
let _this = this, _config = _this._config;
$.metPageCss('/Libs/bootstrap-treeview/dist/bootstrap-treeview.min.css', "dy-css-treeview");
$.metPageJs('/Libs/bootstrap-treeview/dist/bootstrap-treeview.min.js', "dy-js-treeview");
_config.onNodeSelected = _config.onNodeSelected && typeof _config.onNodeSelected == 'function' ?
function (e, data) { _config.onNodeSelected.call(_this, e, data); } : _this._onNodeSelected;
_config.onNodeUnselected = _config.onNodeUnselected && typeof _config.onNodeUnselected == 'function' ?
function (e, data) { _config.onNodeUnselected.call(_this, e, data); } : _this._onNodeUnselected;
if (_config.data) {
_this.loadTree();
} else if (_config.url) {
_this.postData();
}
};
_proto._onNodeSelected = function (e, data) {
let _this = this, _config = _this._config;
if (!data || !data[_config.selectFiledName]) {
return;
}
let $input = (typeof (_config.selectFiledInput) === 'string' ? $('#' + _config.selectFiledInput) : $(_config.selectFiledInput));
let tempId = data[_config.selectFiledName];
$input.val(tempId);
let $table = (typeof (_config.table) === 'string' ? $('#' + _config.table) : $(_config.table));
$table.VbTable('refresh', true);
};
_proto._onNodeUnselected = function () {
let _this = this, _config = _this._config;
let $input = (typeof (_config.selectFiledInput) === 'string' ? $('#' + _config.selectFiledInput) : $(_config.selectFiledInput));
$input.val('');
let $table = (typeof (_config.table) === 'string' ? $('#' + _config.table) : $(_config.table));
$table.VbTable('refresh', true);
};
_proto.loadTree = function (data) {
let _this = this;
let option = $.extend({}, _this._config);
if (data) {
option.data = data;
}
$(_this._element).treeview(option);
};
_proto.postData = function (url) {
let _this = this;
url = url || _this._config.url;
$.vbAjax({
url: window.appUrl + url,
isAlert: false,
isValidate: false,
isRefresh: false,
success: function (res) {
if (res) {
_this.loadTree(res);
}
}
});
};
TreeView._jQueryInterface = function _jQueryInterface(option) {
let value, args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
let data = $(this).data(DATA_KEY);
let _options = $.extend({}, Default, $(this).data(), typeof option === 'object' && option);
if (!data) {
data = new TreeView(this, _options);
$(this).data(DATA_KEY, data);
}
if (typeof option === 'string') {
if ($.inArray(option, ALLOW_METHOD) < 0) {
throw new Error("Unknown method: " + option);
}
value = data[option].apply(data, args);
}
});
return typeof value === 'undefined' ? this : value;
};
return TreeView;
}();
/**
* jQuery API
* ====================================================
*/
$.fn[NAME] = TreeView._jQueryInterface;
$.fn[NAME].Constructor = TreeView;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return TreeView._jQueryInterface;
};
return TreeView;
}(jQuery);
let VbWangEditor = function ($) {
const NAME = 'VbWangEditor';
const DATA_KEY = 'vb.wang_editor';
const EVENT_KEY = "." + DATA_KEY;
const Selector = {
WANG_EDITOR: '[data-vb-editor="wang"]',
INPUT: ''
}
const Event = {
CHANGE: "change" + EVENT_KEY,
LOAD_DATA_API: "load" + EVENT_KEY
};
const JQUERY_NO_CONFLICT = $.fn[NAME];
const Default = {
name: undefined,
showFullScreen: true,
menus: undefined, excludeMenus: undefined,
colors: undefined,
/*[
'#000000',
'#eeece0',
'#1c487f',
'#4d80bf'
],*/
fontNames: undefined,
/*[
'黑体',
'仿宋',
'楷体',
'标楷体',
'华文仿宋',
'华文楷体',
'宋体',
'微软雅黑',
'Arial',
'Tahoma',
'Verdana',
'Times New Roman',
'Courier New',
],*/
lineHeights: undefined,
//['1', '1.15', '1.6', '2', '2.5', '3'],
pasteFilterStyle: false, //粘贴样式的过滤
pasteIgnoreImg: true, //来忽略粘贴的图片
pasteTextHandle: undefined, // 对粘贴的文本进行处理,然后返回处理后的结果
onchange: undefined,
onblur: function () {
},
onfocus: function () {
//debug_log(ss);
},
linkImgCallback: undefined, // 插入网络图片的回调
onlineVideoCallback: undefined, // 自定义检查插入视频的回调
uploadImgServer: "", // 配置 server 接口地址
uploadImgMaxSize: 2 * 1024 * 1024, //限制大小 2M
uploadImgAccept: ['jpg', 'jpeg', 'png', 'gif', 'bmp'], //限制类型
uploadFileName: undefined, //自定义 fileName
uploadImgHeaders: undefined, //自定义 header
withCredentials: false, //跨域传递 cookie
customUploadImg: undefined, //自己实现上传图片
/*
function (resultFiles, insertImgFn) {
// resultFiles 是 input 中选中的文件列表
// insertImgFn 是获取图片 url 后,插入到编辑器的方法
// 上传图片,返回结果,将图片插入到编辑器中
insertImgFn(imgUrl)
}
*/
uploadImgTimeout: 5 * 1000, //自定义 timeout 时间
uploadImgParams: undefined, //自定义上传参数
uploadImgHooks: undefined, //回调函数
/*
{
// 上传图片之前
before: function(xhr) {
console.log(xhr)
// 可阻止图片上传
return {
prevent: true,
msg: '需要提示给用户的错误信息'
}
},
// 图片上传并返回了结果,图片插入已成功
success: function(xhr) {
console.log('success', xhr)
},
// 图片上传并返回了结果,但图片插入时出错了
fail: function(xhr, editor, resData) {
console.log('fail', resData)
},
// 上传图片出错,一般为 http 请求的错误
error: function(xhr, editor, resData) {
console.log('error', xhr, resData)
},
// 上传图片超时
timeout: function(xhr) {
console.log('timeout')
},
// 图片上传并返回了结果,想要自己把图片插入到编辑器中
// 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式,可使用 customInsert
customInsert: function(insertImgFn, result) {
// result 即服务端返回的接口
console.log('customInsert', result)
// insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可
insertImgFn(result.data[0])
}
}
*/
uploadImgMaxLength: 5, // 一次最多上传 5 个图片,
uploadImgShowBase64: true, // 可使用 base64 格式保存图片
showLinkImg: false
}
window.editor_W = {};
let E, editor = undefined;
let WangEditor = function () {
function WangEditor(element, config) {
this._element = element;
this._config = config;
$.metPageJs('/libs/wangEditor/dist/wangEditor.min.js', "dy-js-wangEditor");
E = window.wangEditor;
//this._init();
}
// Public
let _proto = WangEditor.prototype;
_proto._init = function (options) {
let _this = this, $this = $(_this._element);
options = options || {};
editor = new E(_this._element);
$this.form = $this.closest('form');
_this.createEditor(options);
}
_proto.createEditor = function (options) {
let _this = this;
let $this = $(_this._element);
options = options || {};
let _config = $.extend(true, {}, _this._config, options);
let name = _config.name || $this.data('editorName');
if (!name) {
throw new Error("请配置【name】");
}
let $Input = $this.parent().find($('#' + name));
$Input = $Input.length > 0 ? $Input : $(Selector.INPUT.format(name));
$Input.off(Event.CHANGE).on(Event.CHANGE, function () {
$this.setContent($Input.val());
});
$this.before($Input.val(""));
_config.onchange = function (html) {
// 监控变化,同步更新到 input
$Input.val(html);
}
if (!_config.excludeMenus) {
let menuStr = $this.data('editorMenu');
let menu = menuStr ? menuStr.split(',') : undefined;
if (menu) {
editor.config.menus = menu;
}
}
let opt = $this.data('editorOption');
if (!(typeof (opt) === "object" && Object.prototype.toString.call(opt).toLowerCase() === "[object object]")) {
try {
opt = opt ? JSON.parse(opt) : {};
} catch (e) {
console.log(e);
opt = {};
}
}
editor.config = $.extend({}, editor.config, _config, opt || {});
if (editor.config.excludeMenus) {
editor.config.excludeMenus = _config.excludeMenus;
}
if (!editor.config.excludeMenus && _config.menus && $.isArray(_config.menus)) {
editor.config.menus = _config.menus;
}
if (_config.colors && $.isArray(_config.colors)) {
editor.config.colors = _config.colors;
}
if (_config.fontNames && $.isArray(_config.fontNames)) {
editor.config.fontNames = _config.fontNames;
}
if (_config.lineHeights && $.isArray(_config.lineHeights)) {
editor.config.lineHeights = _config.lineHeights;
}
debug_log("WangEditor_option:", editor.config);
editor.create();
}
_proto.setContent = function (txt) {
editor.txt.html(txt);
}
WangEditor._jQueryInterface = function _jQueryInterface(option) {
let value, args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
let data = $(this).data(DATA_KEY);
let _options = $.extend({}, Default, $(this).data(), typeof option === 'object' && option);
if (!data) {
data = new WangEditor(this, _options);
$(this).data(DATA_KEY, data);
}
if (typeof option === 'string') {
if (data[option] === 'undefined') {
throw new Error("Unknown method: " + option);
}
value = data[option].apply(data, args);
} else {
data['_init'].apply(data, args);
}
});
return typeof value === 'undefined' ? this : value;
};
return WangEditor;
}();
$(window).on("load" + EVENT_KEY, function () {
$("div" + Selector.WANG_EDITOR).each(function () {
WangEditor._jQueryInterface.call($(this));
});
});
/**
* jQuery API
* ====================================================
*/
$.fn[NAME] = WangEditor._jQueryInterface;
$.fn[NAME].Constructor = WangEditor;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return WangEditor._jQueryInterface;
};
return WangEditor;
}(jQuery);
exports.vbTable = VbTable;
exports.vbModal = VbModal;
exports.vbFile = VbFile;
exports.vbDate = VbDate;
exports.vbTreeView = VbTreeView;
exports.vbWangEditor = VbWangEditor;
Object.defineProperty(exports, '__esModule', { value: true });
})));
String.prototype.format = function (args) {
let result = this;
if (arguments.length > 0) {
let reg;
if (arguments.length === 1 && typeof args === "object") {
for (let key in args) {
if (args.hasOwnProperty(key)) {
if (args[key] !== undefined) {
reg = new RegExp("({" + key + "})", "g");
result = result.replace(reg, args[key]);
}
}
}
} else {
for (let i = 0; i < arguments.length; i++) {
if (arguments[i] !== undefined) {
reg = new RegExp("({[" + i + "]})", "g");
result = result.replace(reg, arguments[i]);
}
}
}
}
return result;
};
Date.prototype.format = function (fmt) {
let o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (let k in o) {
if (o.hasOwnProperty(k))
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
return fmt;
};
Date.prototype.diff = function (diffType, endTime, startTime) {
diffType = diffType.toLowerCase();
let sTime = startTime ? (typeof startTime === 'string' ? new Date(startTime) : startTime) : this; //开始时间
let eTime = typeof endTime === 'string' ? new Date(endTime) : endTime; //结束时间
//作为除数的数字
let divNum = 1;
switch (diffType) {
case "second":
case "s":
divNum = 1000;
break;
case "minute":
case "m":
divNum = 1000 * 60;
break;
case "hour":
case "h":
divNum = 1000 * 3600;
break;
case "day":
case "d":
divNum = 1000 * 3600 * 24;
break;
default:
break;
}
return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
};
var funs;
function LoadTable(option, backFuns) {
if (!option) {
option = { table: "table" };
}
option.table = option.table ? option.table : "table";
let $table = typeof option.table === 'string' ? $('#' + option.table) : $(option.table);
if ($table.length < 1) {
throw new Error("没有发现表格" + option.table);
}
$table.VbTable(option);
backFuns = backFuns == undefined ? true : backFuns;
if (backFuns) {
return GetTableFuns($table);
}
window.funs = GetTableFuns($table);
return $table;
}
function GetTableFuns(table) {
let $table = typeof table === 'string' ? $('#' + table) : $(table);
return $table.VbTable('getToolFunctions');
}
function GetSelections(table) {
let $table = typeof table === 'string' ? $('#' + table) : $(table);
return $table.VbTable("getSelections");
}
function RefreshTable(table, isForce) {
table = table || "table";
isForce = isForce === undefined;
let $table = typeof table === 'string' ? $('#' + table) : $(table);
if ($table.length < 1) {
console.log('没有发现表格:', table);
}
try {
$table.VbTable('refresh', isForce);
} catch (e) {
debug_log("RefreshTable", e);
}
}
function BtnCreate(option) {
option = option || {};
option.table = option.table ? option.table : "table";
let $table = typeof option.table === 'string' ? $('#' + option.table) : $(option.table);
let url = option.url || $table.closest('.table-box').find('[data-vb-tool-menu-type="_btnCreate"]').data('vb-tool-menu-url') || $table.closest('.table-box').find('[data-vb-tool-menu-type="_btnCreate"]').data('vb-tool-menu-url');
option.type = 'post';
$table.VbTable('create', url, option);
}
function BtnUpdate(option, row) {
option = option || {};
option.table = option.table ? option.table : "table";
let $table = typeof option.table === 'string' ? $('#' + option.table) : $(option.table);
let url = option.url || $table.closest('.table-box').find('[data-vb-tool-menu-type="btnUpdate"]').data('vb-tool-menu-url');
row = row || option.row || $table.VbTable("getSelection");
option.data = option.data || row;
option.type = 'post';
$table.VbTable('update', url, option, row);
}
function BtnDelete(option, row) {
option = option || {};
option.table = option.table ? option.table : "table";
let $table = typeof option.table === 'string' ? $('#' + option.table) : $(option.table);
let url = option.url || $table.closest('.table-box').find('[data-vb-tool-menu-type="btnDelete"]').data('vb-tool-menu-url');
row = row || option.row || $table.VbTable("getSelection");
option.type = 'post';
$table.VbTable('delete', url, option, row);
}
function BtnConfirm(message, title, url, rowOrTableId, data) {
let row, $table;
if (!data) {
if (rowOrTableId) {
if (typeof rowOrTableId === 'object' && !(rowOrTableId instanceof jQuery)) {
row = rowOrTableId;
} else {
$table = typeof rowOrTableId === 'string' ? $('#' + rowOrTableId) : $(rowOrTableId);
row = $table.bootstrapTable("getSelections")[0];
}
} else {
row = $("#table").bootstrapTable("getSelections")[0];
}
if (row) {
data = { Id: row.id };
}
} else {
$table = typeof rowOrTableId === 'string' ? $('#' + rowOrTableId) : $(rowOrTableId);
}
if (data) {
MsgConfirm(message, title, function () {
$.vbAjax1({ url: url, data: data, table: $table });
});
} else
abp.message.warn(abp.localization.iwbZero('SelectRecordOperation'));
}
function MsgConfirm(message, title, callback, opt) {
abp.message.confirm(message, title, function (isConfirmed) {
if (isConfirmed && callback) {
callback(opt);
}
});
}
function OpenModal(opt) {
opt = opt || {};
let ele = opt.modal ? opt.modal : "modal";
let $modal = typeof ele === 'string' ? $('#' + ele) : $(ele);
if ($modal.length < 1) {
console.log('没有发现模态框:', ele);
}
try {
$modal.VbModal(opt);
} catch (e) {
debug_log("OpenModal", e);
}
}
function ShowModal(ele) {
ele = ele || "modal";
let $modal = typeof ele === 'string' ? $('#' + ele) : $(ele);
if ($modal.length < 1) {
console.log('没有发现模态框:', ele);
}
try {
$modal.VbModal('show');
} catch (e) {
debug_log("ShowModal", e);
}
}
let queryModalTarget = '';
function ShowQueryModal(ele, target) {
ele = ele || "modal";
queryModalTarget = !target ? '' : target.indexOf('.') === 0 ? target : target.indexOf('#') === 0 ? target : '#' + target;
let $modal = typeof ele === 'string' ? $('#' + ele) : $(ele);
if ($modal.length < 1) {
console.log('没有发现模态框:', ele);
}
try {
let modalId = $modal.attr("id");//, treeField = $modal.data('search-tree-field'), searchBindFunc = `SearchList_${modalId}` //$modal.data('search-bind-func');
let _shown = function () {
let show = `${modalId}Search`;
if (show && window[show] && typeof window[show] == "function") {
window[show].call();
}
}
$modal.VbModal('show', {
shown: _shown,
needForm: false
});
} catch (e) {
debug_log("ShowModal", e);
}
}
function ClearSearchValue(target, clear, that) {
let $target = $(!target ? $(that) : target.indexOf('.') === 0 ? target : target.indexOf('#') === 0 ? target : '#' + target);
let arr = clear.split(",");
arr.forEach(function (v) {
if (v) {
let vStr = v.indexOf('.') === 0 ? v : v.indexOf('#') === 0 ? v : '#' + v;
let $t = $target.find(vStr);
$t.val('');
if ($t.is("select")) {
$t.trigger('change');
}
}
});
}
function ChangAjaxSelectValue($this, val, name) {
if (name && val) {
let option = new Option(name, val);
$this.html(option).trigger('change');
} else if (val) {
let key = $this.data('param-key');
$.vbAjax41({
url: abp.appUrl + "Query/AcInfo",
data: {
CodeKey: key,
ValueKey: val
},
success: function (res) {
if (res) {
let option = new Option(res.nameKey, res.valueKey);
$this.html(option).trigger('change');
}
}
});
}
}
function AddDynamicBox(that) {
let $that = $(that).closest('.vb-dynamic-box'), html = $that.clone().prop("outerHTML");
html = html.replace('btn-add', 'btn-delete');
html = html.replace('AddDynamicBox()', `$(this).closest('.vb-dynamic-box').remove();`);
html = html.replace('>增加删除 RGB
function HexToRgb(str) {
//replace替换查找的到的字符串
str = str.replace("#", "");
if (str.length === 3) {
str = str + str;
}
//match得到查询数组
let hxs = str.match(/../g);
for (let i = 0; i < 3; i++) hxs[i] = parseInt(hxs[i], 16);
return hxs;
}
//Hex-- > RGB
function HexToRgbStr(str) {
let hxs = HexToRgb(str);
return 'rgb(' + hxs[0] + ', ' + hxs[1] + ', ' + hxs[2] + ')';
}
//RGB-- > Hex
function RgbToHex(a, b, c) {
let hexs = [a.toString(16), b.toString(16), c.toString(16)];
for (let i = 0; i < 3; i++)
if (hexs[i].length == 1)
hexs[i] = "0" + hexs[i];
return "#" + hexs.join("");
}
$(function () {
$('select[data-select-tree="true"]').select2tree();
$('select[data-select-ajax="true"]').each(function () {
let $this = $(this);
let cKey = function () { return $this.data('param-key') },
take = function () { return $this.data('param-count') },
funResultTemplate = function () { return $this.data('result-template-function') };
debug_log("ajax-select", cKey(), take(), funResultTemplate());
$this.select2({
language: window.lang,
ajax: {
url: abp.appUrl + "Query/AcInfos",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
let page = params.page || 1;
let queryParam = {
CodeKey: cKey(),
NameKey: params.term, // search term
Skip: (page - 1) * take(),
Take: take()
};
return queryParam;
},
processResults: function (data, params) {
debug_log("ajax-select_processResults", data, params);
params.page = params.page || 1;
let result = {
results: data.items.map(function (v) {
v.id = v.valueKey;
v.text = v.nameKey;
return v;
}),
pagination: {
more: (params.page * take()) < data.totalCount
}
};
return result;
},
transport: function (params, success, failure) {
params = params || {};
params.success = success;
params.error = failure;
let $request = $.vbAjax41(params);
return $request;
},
cache: true
},
cache: true,
minimumInputLength: 0,
templateResult: function (res) {
if (res.loading) {
return res.text;
}
let funTemplate = window[funResultTemplate()];
if (funTemplate && $.isFunction(funTemplate)) {
return funTemplate(res);
} else {
return '{0}'.format(res.text);
}
},
templateSelection: function (res) {
return res.text;
}
});
});
//Configure blockUI
if ($.blockUI) {
$.blockUI.defaults.baseZ = 2000;
}
//Configure validator
$.validator.setDefaults({
highlight: (el) => {
$(el).addClass('invalid');
$(el).removeClass('valid');
},
unhighlight: (el) => {
$(el).removeClass('invalid');
$(el).addClass('valid');
},
errorPlacement: (error, element) => {
let $el = element.closest('.d-flex').find('.invalid-feedback')
if ($el.length) {
$el.html(error).addClass('invalid-feedback-show');
}
let $tab = element.closest('.form-auto-tab');
if ($tab && $tab.length) {
$("#" + $tab.data("tab-name")).tab("show");
}
element.focus();
}
});
//serializeFormToObject plugin for jQuery
$.fn.serializeFormToObject = function (camelCased = false) {
//serialize to array
let data = $(this).serializeArray();
//add also disabled items
$(':disabled[name]', this).each(function () {
data.push({ name: this.name, value: $(this).val() });
});
//map to object
let obj = {};
data.map(function (x) { obj[x.name] = x.value; });
if (camelCased && camelCased === true) {
return convertToCamelCasedObject(obj);
}
function convertToCamelCasedObject(obj) {
let newObj, origKey, newKey, value;
if (obj instanceof Array) {
return obj.map(value => {
if (typeof value === 'object') {
value = convertToCamelCasedObject(value);
}
return value;
});
} else {
newObj = {};
for (origKey in obj) {
if (obj.hasOwnProperty(origKey)) {
newKey = (
origKey.charAt(0).toLowerCase() + origKey.slice(1) || origKey
).toString();
value = obj[origKey];
if (
value instanceof Array || (value && value.constructor === Object)
) {
value = convertToCamelCasedObject(value);
}
newObj[newKey] = value;
}
}
}
return newObj;
}
return obj;
};
})