| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644 |
- 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 = '<i class="fa fa-angle-double-right"></i>';
- 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: '<span class="fas fa-folder"></span>',//叶子节点
- expandIcon: '<span class="fas fa-folder-plus"></span>',
- collapseIcon: '<span class="fas fa-folder-open"></span>',
- 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 `
- <div class="form-check form-check-sm form-check-custom form-check-solid">
- <input name="check_state" class="form-check-input" type="checkbox" ${checked} value="${data}" />
- </div>`;
- }
- }
- 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 ? `<span data-bs-toggle="tooltip" title="${value}">${value.substr(0, length - 2)}...</span>` : 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 = `
- //<span href="#" class="btn btn-light-primary py-0 fs-9" data-kt-menu-trigger="click" data-kt-menu-placement="bottom-end" data-kt-menu-flip="top-end" style="line-height:23px;">操作
- // <!--Svg Icon | path: icons/duotone/Navigation/Angle-down.svg-->
- // <span class="svg-icon svg-icon-5 m-0 ms-1">
- // <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
- // <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
- // <polygon points="0 0 24 0 24 24 0 24"></polygon>
- // <path d="M6.70710678,15.7071068 C6.31658249,16.0976311 5.68341751,16.0976311 5.29289322,15.7071068 C4.90236893,15.3165825 4.90236893,14.6834175 5.29289322,14.2928932 L11.2928932,8.29289322 C11.6714722,7.91431428 12.2810586,7.90106866 12.6757246,8.26284586 L18.6757246,13.7628459 C19.0828436,14.1360383 19.1103465,14.7686056 18.7371541,15.1757246 C18.3639617,15.5828436 17.7313944,15.6103465 17.3242754,15.2371541 L12.0300757,10.3841378 L6.70710678,15.7071068 Z" fill="#000000" fill-rule="nonzero" transform="translate(12.000003, 11.999999) rotate(-180.000000) translate(-12.000003, -11.999999)"></path>
- // </g>
- // </svg>
- // </span>
- //</span>`;
- 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 += `<div class="menu-item px-3"><a href="#" class="px-3 ${btnClass}" data-id="{0}" onclick="$('#${_el.id}').VbTable('getToolFunctions')['${btnType}_tree'].call(this,'${btnUrl}','{0}')"> <i class="${btnIcon}"></i>${btnName}</a></div>`;*/
- //$(this).remove();
- treeActionMenu += `<span class="table-action" onclick="$('#${_el.id}').VbTable('getToolFunctions')['${btnType}_tree'].call(this,'${btnUrl}','{0}')">${btnIcon ? `<i class="${btnIcon}"></i>` : icon}${btnName}</span>`
- } 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 = `<div class="menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-gray-600 menu-state-bg-light-primary fw-bold fs-7 w-125px py-4 " data-kt-menu-action="true" kt-hidden-height="120" style="">{0}</div>`;*/
- 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 = $(`
- <div id="${containerId}" class="${ClassName.CREATE_BOX}">
- <div id="${_config.modalId}" class="modal fade ${_config.modalClass}">
- <div class="${ClassName.MODAL_DIALOG} modal-dialog-centered modal-dialog-scrollable ${dialogClass}" style="${dialogStyle}">
- <div class="${ClassName.MODAL_CONTENT}"></div>
- </div>
- </div>
- </div>`);
- 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
- : `<div class="${ClassName.MODAL_HEADER} py-3 ${_config.modalHeaderClass ? _config.modalHeaderClass : ""}"><h4 class="modal-title"><span class="modal-title">${_config.title ? _config.title : ""}</span></h4><div class="btn btn-icon btn-sm btn-active-light-primary ms-2" data-bs-dismiss="modal" aria-label="Close">
- <!--Svg Icon | path: icons/duotone/Navigation/Close.svg-->
- <span class="svg-icon svg-icon-2x">
- <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
- <g transform="translate(12.000000, 12.000000) rotate(-45.000000) translate(-12.000000, -12.000000) translate(4.000000, 4.000000)" fill="#000000">
- <rect fill="#000000" x="0" y="7" width="16" height="2" rx="1"></rect>
- <rect fill="#000000" opacity="0.5" transform="translate(8.000000, 8.000000) rotate(-270.000000) translate(-8.000000, -8.000000)" x="0" y="7" width="16" height="2" rx="1"></rect>
- </g>
- </svg>
- </span>
- </div></div>`;
- let modalBody = `<div class="${ClassName.MODAL_BODY} ${_config.modalBodyClass}">${_config.modalBody}</div>`;
- let modalFooter = _config.modalFooter != undefined
- ? _config.modalFooter
- : `<div class="${ClassName.MODAL_FOOTER} py-2 ${_config.modalFooterClass ? _config.modalFooterClass : ""}" style="text-align: center;"><button
- <button type="button" class="btn btn-sm btn-light me-5" data-bs-dismiss="modal">取消</button>
- <button type="submit" class="btn btn-sm btn-primary ${ClassName.SAVE_BUTTON}">保存</button>
- </div>`;
- $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 = $(`<ul id="${ClassName.MODAL_IMAGE}" style="display:none"></ul>`);
- for (let i = 0; i < urls.length; i++) {
- $ul.append(`<li><img src="${urls[i]}" ${ClassName.IMAGE_URL_NAME}="{urls[i]}" /></li>`);
- }
- $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: `<div class="modal-body"><iframe src="${url}" width="100%"; style="min-height: calc(100vh - 300px);" frameborder="0"></iframe></div>`,
- modalFooter: `<div class="modal-footer" style="text-align: center;justify-content: center"><button type="button" class="btn btn-default" data-dismiss="modal" style="min-width: 100px;">关闭窗口</button><button id="${ClassName.DOWNLOAD}" type="button" class="btn btn-primary
- " style="min-width: 100px;">下载文件</button></div>`,
- 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(`<a id="${ClassName.TEMPLINK}" href="${url}" target="_blank" style="display:none"></a>`);
- $(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: '<input class="vb-wang-editor" name="{0}" type="hidden" />'
- }
- 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('>增加</button', '>删除</button');
- html = html.replace(new RegExp('data-select2-id="*"', "g"), '');
- let $html = $(html).addClass('vb-dynamic-box-delete').removeAttr('data-select2-id');
- $html.find('.select2').remove();
- $html.find('select').removeAttr("id").val('');
- $html.find('select:not(.tree)').select2();
- $html.find('select.tree').select2tree();
- $html.find('input').val('');
- $that.parent().append($html);
- return $html;
- }
- function DateFormatter(v) {
- if (!v) {
- return "";
- }
- let date = new Date(v);
- let str = date.format('yyyy-MM-dd');
- return str;
- }
- function DateTimeFormatter(v) {
- if (!v) {
- return "";
- }
- let date = new Date(v);
- let str = date.format('yyyy-MM-dd hh:mm:ss');
- return str;
- }
- //Hex-- > 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;
- };
- })
|