| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639 |
- 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;
- 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);
- }
- };
- }
- 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;
- };
- })
|