vber.base.js 158 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639
  1. var _LOG = true;
  2. function debug_log() {
  3. if (_LOG) {
  4. console.log(arguments[0], arguments[1] ? arguments[1] : "", arguments[2] ? arguments[2] : "", arguments[3] ? arguments[3] : "", arguments[4] ? arguments[4] : "");
  5. }
  6. }
  7. var abp = abp || {};
  8. let icon = '<i class="fa fa-angle-double-right"></i>';
  9. abp.ui.setBusy = function (elm, opts) {
  10. if (!elm) {
  11. $.blockUI(opts);
  12. } else {
  13. $(elm).block(opts);
  14. }
  15. };
  16. abp.ui.clearBusy = function (elm, opts) {
  17. if (!elm) {
  18. $.unblockUI(opts);
  19. } else {
  20. $(elm).unblock(opts);
  21. }
  22. };
  23. if (typeof jQuery === "undefined") {
  24. throw new Error("jQuery plugins need to be before this file");
  25. }
  26. /*JQuery扩展*/
  27. $.extend({
  28. //表单赋值
  29. formDeserialize: function ($form, data) {
  30. //isSelect2 = isSelect2 === undefined;
  31. if (!data) {
  32. return;
  33. }
  34. let $input = $form.find('input:not([type="radio"]):not([type="checkbox"])');
  35. let $textarea = $form.find("textarea");
  36. let $select = $form.find("select");
  37. let $checkbox = $form.find("input[type='checkbox']");
  38. let $radio = $form.find("input[type='radio']");
  39. $.merge($input, $textarea);
  40. $input.each(function () {
  41. let $input = $form.find($(this));
  42. let name = $input.attr("name");
  43. if (data.hasOwnProperty(name)) {
  44. if ($input.hasClass('flatpickr-input')) {
  45. $input.VbDate("setValue", data[name])
  46. } else {
  47. $input.val(data[name]);
  48. }
  49. }
  50. });
  51. $select.each(function () {
  52. let $select = $form.find($(this));
  53. let name = $select.attr("name");
  54. if (data.hasOwnProperty(name)) {
  55. if (typeof data[name] === "boolean") {
  56. data[name] = data[name] + "";
  57. }
  58. if (data[name] !== "") {
  59. let val = data[name];
  60. $select.val(val);
  61. if ($select.hasClass('ajax-select') && window.ChangAjaxSelectValue) {
  62. window.ChangAjaxSelectValue($select, val);
  63. }
  64. }
  65. }
  66. });
  67. $checkbox.each(function () {
  68. let input = $form.find($(this));
  69. let name = input.attr("name");
  70. if (data.hasOwnProperty(name)) {
  71. $("input[name='" + name + "']").prop("checked", false);
  72. if (typeof data[name] == "string") {
  73. if (data[name] === "True" || data[name] === "1" || data[name] === "true") {
  74. $form.find("input[name='" + name + "']").prop("checked", true);
  75. } else if (data[name].indexOf(",") > 0) {
  76. let arr = data[name].split(',');
  77. for (let i = 0; i < arr.length; i++) {
  78. $form.find("input[name='" + name + "'][value='" + arr[i] + "']").prop("checked", true);
  79. }
  80. }
  81. } else if (typeof data[name] == "object") {
  82. for (let i = 0; i < data[name].length; i++) {
  83. $form.find("input[name='" + name + "'][value='" + data[name][i] + "']").prop("checked", true);
  84. }
  85. }
  86. };
  87. });
  88. $radio.each(function () {
  89. let input = $form.find($(this));
  90. let name = input.attr("name");
  91. if (data.hasOwnProperty(name)) {
  92. $form.find("input[name='" + name + "'][value='" + data[name] + "']").prop("checked", true);
  93. //$("input[name='" + name + "'][value!='" + data[name] + "']").prop("checked", false);
  94. }
  95. });
  96. },
  97. //将form表单元素的值序列化成对象
  98. formSerialize: function ($form) {
  99. let disableEle = $form.find("[disabled]");
  100. disableEle.each(function (i, e) {
  101. $(e).prop("disabled", false);
  102. });
  103. let data = {};
  104. $.each($form.serializeArray(),
  105. function () {
  106. if (data[this['name']]) {
  107. data[this['name']] = data[this['name']] + "," + this['value'];
  108. } else {
  109. data[this['name']] = this['value'];
  110. }
  111. });
  112. disableEle.each(function (i, e) {
  113. $(e).prop("disabled", true);
  114. });
  115. return data;
  116. },
  117. //表单验证
  118. formValidate: function ($form, opt) {
  119. let defaults = {
  120. noValid: false,
  121. form: "form",
  122. modal: "modal",
  123. ignore: ".ignore .iwb-wang-editor"
  124. };
  125. opt = opt || {};
  126. let options = $.extend({}, defaults, opt);
  127. let $modal = options.modal
  128. ? typeof (options.modal) === 'string'
  129. ? $('#' + options.modal)
  130. : $(options.modal)
  131. : null;
  132. $form = $form ? $form : options.form ? $(options.form) : $modal.find('form');
  133. $form.validate(options);
  134. //.settings.ignore = ":disabled";
  135. if (!options.noValid) {
  136. let valid = $form.valid();
  137. debug_log("FormValidate", $form.attr('id'), valid);
  138. return valid;
  139. }
  140. return options.noValid;
  141. },
  142. formatterDate: function (fmt, date, isFix) {
  143. date = date || new Date();
  144. isFix = isFix === undefined ? true : isFix;
  145. let year = date.getFullYear();
  146. let month = date.getMonth() + 1;
  147. fmt = fmt.replace("yyyy", year);
  148. fmt = fmt.replace("yy", year % 100);
  149. fmt = fmt.replace("MM", fix(month));
  150. fmt = fmt.replace("dd", fix(date.getDate()));
  151. fmt = fmt.replace("HH", fix(date.getHours()));
  152. fmt = fmt.replace("mm", fix(date.getMinutes()));
  153. fmt = fmt.replace("ss", fix(date.getSeconds()));
  154. return fmt;
  155. function fix(n) {
  156. return isFix ? (n < 10 ? "0" + n : n) : n;
  157. }
  158. },
  159. blinkTitle: {
  160. start: function (msg) {
  161. msg = msg || abp.localization.iwbZero('NewNotificationRemind');
  162. this.title = document.title;
  163. this.messages = [msg];
  164. if (!this.action) {
  165. try {
  166. this.element = document.getElementsByTagName('title')[0];
  167. this.element.innerHTML = this.title;
  168. this.action = function (ttl) {
  169. this.element.innerHTML = ttl;
  170. };
  171. } catch (e) {
  172. this.action = function (ttl) {
  173. document.title = ttl;
  174. };
  175. delete this.element;
  176. }
  177. this.toggleTitle = function () {
  178. this.index = this.index === 0 ? 1 : 0;
  179. this.action('【' + this.messages[this.index] + '】' + this.title);
  180. };
  181. }
  182. let n = msg.length;
  183. let s = '';
  184. if (this.element) {
  185. let num = msg.match(/\w/g);
  186. if (num) {
  187. let n2 = num.length;
  188. n -= n2;
  189. while (n2 > 0) {
  190. s += " ";
  191. n2--;
  192. }
  193. }
  194. }
  195. while (n > 0) {
  196. s += ' ';
  197. n--;
  198. }
  199. this.messages.push(s);
  200. this.index = 0;
  201. //this.title = this.title.replace("【" + msg + "】", "").replace("【" + s + "】", "");
  202. let _this = this;
  203. this.timer = setInterval(function () {
  204. _this.toggleTitle();
  205. }, 500);
  206. },
  207. stop: function () {
  208. if (this.timer) {
  209. clearInterval(this.timer);
  210. let t = this.title ? this.title : document.title;
  211. this.action(t);
  212. delete this.timer;
  213. delete this.messages;
  214. }
  215. }
  216. },
  217. metPageCss: function (url, id) {
  218. id = id || 'dy-css';
  219. if ($('#' + id).length > 0) {
  220. return;
  221. }
  222. let link = document.createElement('link');
  223. link.type = 'text/css';
  224. link.rel = 'stylesheet';
  225. link.id = id;
  226. link.href = url + '?v=' + Math.floor(Math.random() * 100000);
  227. let flag = document.getElementById('flag');
  228. let head = document.getElementsByTagName('head')[0];
  229. if (flag) {
  230. head.insertBefore(link, flag.nextSibling);
  231. } else {
  232. head.appendChild(link);
  233. }
  234. },
  235. metPageJs: function (src, id) {
  236. id = id || 'dy-js';
  237. if ($('#' + id).length > 0) {
  238. return;
  239. }
  240. let script = document.createElement('script');
  241. script.id = id;
  242. script.type = 'text/javascript';
  243. script.charset = 'UTF-8';
  244. script.src = src + '?v=' + Math.floor(Math.random() * 100000);
  245. $('head').append(script);
  246. },
  247. loadScript: function (url, loadCallback, failCallback) {
  248. /* UrlStates enum */
  249. let urlStates = {
  250. LOADING: 'LOADING',
  251. LOADED: 'LOADED',
  252. FAILED: 'FAILED'
  253. };
  254. /* UrlInfo class */
  255. function UrlInfo() {
  256. this.state = urlStates.LOADING;
  257. this.loadCallbacks = [];
  258. this.failCallbacks = [];
  259. }
  260. UrlInfo.prototype.succeed = function () {
  261. this.state = urlStates.LOADED;
  262. for (let i = 0; i < this.loadCallbacks.length; i++) {
  263. this.loadCallbacks[i]();
  264. }
  265. };
  266. UrlInfo.prototype.failed = function () {
  267. this.state = urlStates.FAILED;
  268. for (let i = 0; i < this.failCallbacks.length; i++) {
  269. this.failCallbacks[i]();
  270. }
  271. };
  272. UrlInfo.prototype.handleCallbacks = function (loadCallback, failCallback) {
  273. switch (this.state) {
  274. case urlStates.LOADED:
  275. loadCallback && loadCallback();
  276. break;
  277. case urlStates.FAILED:
  278. failCallback && failCallback();
  279. break;
  280. case urlStates.LOADING:
  281. this.addCallbacks(loadCallback, failCallback);
  282. break;
  283. }
  284. };
  285. UrlInfo.prototype.addCallbacks = function (loadCallback, failCallback) {
  286. loadCallback && this.loadCallbacks.push(loadCallback);
  287. failCallback && this.failCallbacks.push(failCallback);
  288. };
  289. let urlInfos = {};
  290. let loadScript = function (url, loadCallback, failCallback) {
  291. let urlInfo = urlInfos[url];
  292. if (urlInfo) {
  293. urlInfo.handleCallbacks(loadCallback, failCallback);
  294. return;
  295. }
  296. urlInfos[url] = urlInfo = new UrlInfo();
  297. urlInfo.addCallbacks(loadCallback, failCallback);
  298. $.getScript(url).done(function (script, textStatus) {
  299. urlInfo.succeed(script, textStatus);
  300. }).fail(function (jqXhr, settings, exception) {
  301. urlInfo.failed(jqXhr, settings, exception);
  302. });
  303. };
  304. loadScript(url, loadCallback, failCallback);
  305. },
  306. //jsonTree 转成 array
  307. Json2Array: function (data, opts) {
  308. let defaults = {
  309. id: 'id',
  310. parentId: 'parentId',
  311. children: 'children'
  312. };
  313. let opt = $.extend({}, defaults, opts || {});
  314. let Json2ArrayChild = function (data, dataArray) {
  315. let newData = $.extend([], data);
  316. let children = data[opt.children];
  317. delete newData[opt.children];
  318. dataArray.push(newData);
  319. if (children && children.length > 0) {
  320. children.forEach(function (v) {
  321. Json2ArrayChild(v, dataArray);
  322. });
  323. }
  324. }
  325. let dataArray = [];
  326. let children = data[opt.children];
  327. let newData = $.extend([], data);
  328. delete newData[opt.children];
  329. dataArray.push(newData);
  330. if (children && children.length > 0) {
  331. children.forEach(function (v) {
  332. Json2ArrayChild(v, dataArray);
  333. });
  334. }
  335. return dataArray;
  336. },
  337. //array 转成 JsonTree
  338. Array2Json: function (dataArray, opts) {
  339. let defaults = {
  340. root: '',
  341. id: 'id',
  342. parentId: 'parentId',
  343. children: 'children'
  344. };
  345. let opt = $.extend({}, defaults, opts || {});
  346. let Json2DataChild = function (parentId, dataArray) {
  347. let children = dataArray.filter(function (v) {
  348. return v[opt.parentId] === parentId;
  349. });
  350. if (children && children.length > 0) {
  351. children.forEach(function (v) {
  352. v[opt.children] = Json2DataChild(v[opt.id], dataArray);
  353. });
  354. }
  355. return children;
  356. }
  357. let index = dataArray.findIndex(function (v) {
  358. return v[opt.parentId] === opt.root;
  359. });
  360. let dataJson = dataArray[index];
  361. dataJson[opt.children] = Json2DataChild(dataJson.id, dataArray);
  362. return dataJson;
  363. }
  364. });
  365. $.fn.formDeserialize = function (data) {
  366. $.formDeserialize($(this), data);
  367. }
  368. $.fn.formSerialize = function () {
  369. return $.formSerialize($(this));
  370. }
  371. /*AJAX*/
  372. $.extend({
  373. //ajax
  374. vbAjax: function (url, opt) {
  375. this.defaults = {
  376. async: true,
  377. type: "Post",
  378. contentType: 'application/json; charset=UTF-8',
  379. //contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
  380. data: null,
  381. dataFun: null,
  382. log: _LOG,
  383. dataType: "json",
  384. isAlert: true,
  385. successAlert: false,
  386. isValidate: true,
  387. isRefresh: true,//默认刷新表格
  388. success: null,
  389. error: null,
  390. table: undefined,
  391. modal: undefined,
  392. form: undefined,
  393. errorPlacement: function (error, element) {
  394. element.parent().before(error);
  395. element.focus();
  396. },
  397. rules: {},
  398. blockUI: true
  399. };
  400. if (!opt) {
  401. opt = url;
  402. url = opt.url;
  403. }
  404. let options = $.extend({}, this.defaults, opt);
  405. let $table = !options.table ? undefined : typeof options.table === 'string' ? $('#' + options.table) : $(options.table);
  406. let $modal = !options.modal ? undefined : typeof options.modal === 'string' ? $('#' + options.modal) : $(options.modal);
  407. let $form = !options.form ? ($modal ? $modal.find("form") : undefined) : typeof options.form === 'string' ? $('#' + options.form) : $(options.form);
  408. let isValidated = true;
  409. if (options.isValidate && $form) {
  410. isValidated = $.formValidate($form);
  411. }
  412. if (isValidated) {
  413. if (options.dataFun !== null && typeof options.dataFun === 'function') {
  414. options.data = options.dataFun();
  415. } else {
  416. options.data = options.data ? (typeof options.data === 'function' ? options.data() : options.data) : $form ? $.formSerialize($form) : undefined;
  417. }
  418. let guid = Math.floor(Math.random() * 10000);
  419. let log = options.log;
  420. if (log) {
  421. console.log('[' + guid + ']url:' + url, 'data:', options.data);
  422. }
  423. let success = options.success && typeof options.success === 'function'
  424. ? function (res) {
  425. if (log) { console.log('[' + guid + ']', res); }
  426. options.success(res);
  427. if (options.isRefresh && $table) {
  428. $table.VbTable('refresh', true);
  429. }
  430. if ($modal) {
  431. $modal.VbModal('hide');
  432. }
  433. }
  434. : function (res) {
  435. if (log) { console.log('[' + guid + ']', res); }
  436. if (options.isRefresh && $table) {
  437. $table.VbTable('refresh', true);
  438. }
  439. if ($modal) {
  440. $modal.VbModal('hide');
  441. }
  442. };
  443. let ajaxSuccess = options.isAlert || options.successAlert ? function (res) { abp.message.success(abp.localization.VberZero('OpSuccess')).done(success(res)); } : success;
  444. let data = typeof (options.data) === 'string' ? options.data : JSON.stringify(options.data);
  445. let ajaxOption = {
  446. url: url,
  447. async: options.async,
  448. type: options.type,
  449. contentType: options.contentType,
  450. data: data,
  451. dataType: options.dataType,
  452. success: ajaxSuccess,
  453. error: options.error,
  454. abpHandleError: options.isAlert,
  455. beforeSend: function () {
  456. abp.ajax.blockUI(ajaxOption);
  457. },
  458. blockUI: options.blockUI
  459. };
  460. abp.ajax(ajaxOption);
  461. }
  462. }
  463. });
  464. $.extend({
  465. vbAjax1: function (opt) {
  466. opt = $.extend({}, { isValidate: false }, opt);
  467. $.vbAjax(opt);
  468. },
  469. vbAjax2: function (opt) {
  470. opt = $.extend({}, { isAlert: false }, opt);
  471. $.vbAjax(opt);
  472. },
  473. vbAjax3: function (opt) {
  474. opt = $.extend({}, { isValidate: false, isAlert: false, blockUI: true }, opt);
  475. $.vbAjax(opt);
  476. },
  477. vbAjax4: function (opt) {
  478. opt = $.extend({}, { isValidate: false, isAlert: false, isRefresh: false, blockUI: true }, opt);
  479. $.vbAjax(opt);
  480. },
  481. vbAjax41: function (opt) {
  482. opt = $.extend({}, { isValidate: false, isAlert: false, isRefresh: false, blockUI: false }, opt);
  483. $.vbAjax(opt);
  484. },
  485. vbAjax5: function (opt) {
  486. opt = $.extend({}, { isValidate: false, isAlert: false, successAlert: true, isRefresh: false, blockUI: true }, opt);
  487. $.vbAjax(opt);
  488. },
  489. vbGet: function (opt) {
  490. opt = $.extend({}, { type: 'get', modal: null, form: null }, opt);
  491. $.vbAjax4(opt);
  492. }
  493. });
  494. /*ajax全局设置*/
  495. $.ajaxSetup({
  496. type: 'get',
  497. timeout: 1000 * 60 * 2,
  498. //contentType: "application/x-www-form-urlencoded;charset=utf-8",
  499. contentType: "application/json",
  500. dataType: "json",
  501. error: function () {
  502. abp.ui.clearBusy();
  503. },
  504. complete: function (xmlHttpRequest, textStatus) {
  505. abp.ui.clearBusy();
  506. if (textStatus === "timeout") {
  507. abp.message.error(abp.localization.iwbZero('OpTimeout'));
  508. debug_log("Complete - 操作超时");
  509. } else if (textStatus !== "success") {
  510. debug_log("Complete - " + textStatus, xmlHttpRequest.responseJSON);
  511. if (xmlHttpRequest.responseJSON) {
  512. //let json = xmlHttpRequest.responseJSON;
  513. } else if (xmlHttpRequest.responseText === "") {
  514. abp.message.error(abp.localization.VberZero('OpServerError')).done(function () {
  515. top.location.reload();
  516. //top.location.href = "/Account/Login/?ReturnUrl=%2F";
  517. });
  518. }
  519. } else {
  520. let result = xmlHttpRequest.responseJSON;
  521. if (result && !result.success && result.error && result.error.message.indexOf('登陆超时') > -1) {
  522. top.location.reload();
  523. }
  524. }
  525. }
  526. });
  527. (function (global, factory) {
  528. typeof exports === 'object' && typeof module !== 'undefined'
  529. ? factory(exports)
  530. : typeof define === 'function' && define.amd
  531. ? define(['exports'], factory)
  532. : (global = global || self, factory(global.vber = { a: "1" }));
  533. }(this, (function (exports) {
  534. 'use strict';
  535. let abp = window.abp || {};
  536. let VbTable = function ($) {
  537. const NAME = 'VbTable';
  538. const DATA_KEY = 'Vber.DataTable';
  539. const EVENT_KEY = "." + DATA_KEY;
  540. const JQUERY_NO_CONFLICT = $.fn[NAME];
  541. const ClassName = {
  542. TABLE_BOX: 'table-box',
  543. DATE_RANGE: 'vb-date-range',
  544. SEARCH_FIELD: 'search-filed',
  545. SEARCH_FIELD_TYPE: 'search-filed-type',
  546. SEARCH_EXP_TYPE: 'search-exp-type',
  547. TOOL_MENU_TYPE: 'vb-tool-menu-type',
  548. TOOL_MENU_URL: 'vb-tool-menu-url',
  549. TREE_TD_CONTROL: 'vb-treegrid-control',
  550. TREE_TD_CONTROL_OPEN: 'vb-treegrid-control-open',
  551. };
  552. const Selector = {
  553. TABLE_BOX: `.${ClassName.TABLE_BOX}`,
  554. TOOLBAR_BASE: '[data-kt-table-toolbar="base"]',
  555. TOOLBAR_SELECTED: '[data-kt-table-toolbar="selected"]',
  556. TOOLBAR_SELECTED_COUNT: '[data-kt-table-select="selected_count"]',
  557. SEARCH_GLOBAL: `[data-search-keyWord="global"]`,
  558. SEARCH_ADVANCE: `[data-search-keyWord="advance"]`,
  559. TOOL_MENU_ALL: `[data-vb-tool-menu-type]`,
  560. TOOL_MENU: `[data-vb-tool-menu-type="{0}"]`,
  561. TREE_TD_CONTROL: `td.${ClassName.TREE_TD_CONTROL}`,
  562. TREE_TD_CONTROL_OPEN: `td.${ClassName.TREE_TD_CONTROL_OPEN}`
  563. };
  564. const ALLOW_METHOD = [
  565. "addToolFunctions",
  566. "getToolFunctions",
  567. "create",
  568. "update",
  569. "delete",
  570. "getRow",
  571. "getSelection",
  572. "getSelections",
  573. "getSelectionIds",
  574. "getInstance",
  575. "reRender",
  576. "destroy",
  577. "refresh",
  578. "treeExpandAll",
  579. "treeExpand",
  580. "treeCollapse",
  581. ];
  582. const Default = {
  583. processing: true,
  584. serverSide: true,
  585. scrollCollapse: true,
  586. paging: true,
  587. autoWidth: true,
  588. searching: false,
  589. ordering: true,
  590. orderClasses: true,
  591. rowId: "id",
  592. pagingType: "full_numbers",//分页样式:simple,simple_numbers,full,full_numbers
  593. select: {
  594. style: 'os',
  595. selector: 'td:first-child',
  596. className: 'row-selected'
  597. },
  598. lengthChange: true,
  599. lengthMenu: [25, 50, 100],
  600. clickToSelect: true,
  601. deferRender: false,
  602. drawCallback: undefined,
  603. searchForm: undefined,
  604. searchList: [],
  605. searchFun: null,
  606. onlySearchList: false,
  607. searchValidate: true,
  608. dateRangeSpliter: "至",
  609. order: [],
  610. toolFunctions: [],
  611. onAllCheck: undefined,
  612. onAllUnCheck: undefined,
  613. onCheck: undefined,
  614. onUnCheck: undefined,
  615. onClickRow: undefined,
  616. onDblClickRow: undefined,
  617. modal: 'modal',
  618. form: 'form',
  619. modalDrag: true,
  620. multipleSelect: false,//多选保存分页数据
  621. isTree: false,
  622. left: 12,//tree的子目录偏移
  623. expandDepth: 2,
  624. leafIcon: '<span class="fas fa-folder"></span>',//叶子节点
  625. expandIcon: '<span class="fas fa-folder-plus"></span>',
  626. collapseIcon: '<span class="fas fa-folder-open"></span>',
  627. fnDrawCallback: undefined,
  628. root: null,
  629. field: "id",
  630. parentField: "parentNo",
  631. nameField: "name",
  632. parentNameField: "parentName",
  633. };
  634. let Table = function () {
  635. function Table(element, config) {
  636. this._element = element;
  637. this._config = config;
  638. return this._init();
  639. }
  640. let _proto = Table.prototype, dt, _selectedIdArray = [], treeGridRows = {};
  641. _proto._init = function () {
  642. let _this = this, _config = _this._config, _el = _this._element;
  643. let htmlOptions = _this._getHtmlOption();
  644. if (window.lang && window.lang != "en") {
  645. htmlOptions.language = { url: `/libs-ext/dataTable/language_${window.lang}.json` };
  646. }
  647. let options = $.extend(true, {}, htmlOptions, _config, _config.isTree ? { paging: false, pageSelect: false, dom: "tr" } : {});
  648. debug_log("table_options:", options);
  649. dt = $(_el).DataTable(options);
  650. _config.dataTable = dt;
  651. //_this._initToggleToolbar();
  652. dt.on(`init${EVENT_KEY}`, function () {
  653. _this._onEvent();
  654. _this._drawRender();
  655. })
  656. _this._initToolFunction();
  657. if (_config.isTree) {
  658. _this._initTree();
  659. }
  660. };
  661. _proto._getHtmlOption = function () {
  662. let _this = this, _config = _this._config, _el = _this._element;
  663. let htmlOption = $.extend(true, {}, $(_el).data());
  664. if (htmlOption.url) {
  665. htmlOption.ajax = {
  666. contentType: 'application/json; charset=UTF-8',
  667. url: htmlOption.url,
  668. type: htmlOption.method,
  669. data: (param) => {
  670. return _config.queryParams && typeof _config.queryParams == 'function'
  671. ? _config.queryParams.call(_this, param)
  672. : _this._queryParams(param);
  673. },
  674. dataFilter: (data) => {
  675. return _config.responseHandler && typeof _config.responseHandler == 'function'
  676. ? _config.responseHandler.call(_this, data)
  677. : _this._responseHandler(data);
  678. }
  679. };
  680. }
  681. htmlOption.columns = _config.columnsFunc && typeof _config.columnsFunc == 'function'
  682. ? _config.columnsFunc.call(_this, $.extend(true, {}, $(_el).data()))
  683. : htmlOption.columnsFunc && typeof window[htmlOption.columnsFunc] == "function"
  684. ? window[htmlOption.columnsFunc].call(_this, $.extend(true, {}, $(_el).data()))
  685. : _this._getColumnOption();
  686. htmlOption.rowCallback = htmlOption.rowCallbackFunc && typeof window[htmlOption.rowCallbackFunc] == "function" ?
  687. function (row, data) {
  688. window[htmlOption.rowCallbackFunc].call(_this, row, data);
  689. _this._rowCallback.call(_this, row, data);
  690. } :
  691. function (row, data) {
  692. _this._rowCallback.call(_this, row, data);
  693. };
  694. return htmlOption;
  695. }
  696. _proto._getColumnOption = function () {
  697. let _this = this, _config = _this._config, _el = _this._element;
  698. let columns = [];
  699. let treeColumns = _config.isTree;
  700. let $th = $(_el).find('thead').eq(0).find('th');
  701. if ($th.length) {
  702. $th.each(function () {
  703. let $this = $(this), data = $this.data();
  704. let column = {
  705. data: data.field ? function (item) { return item[data.field] } : null,
  706. orderable: data.sortable ? true : false,
  707. searchable: false
  708. };
  709. column.name = data.field;
  710. if (data.className) {
  711. column.className = data.className;
  712. }
  713. if (data.width) {
  714. column.width = data.width;
  715. }
  716. //if (data.className) {
  717. // column.className = data.className;
  718. //}
  719. if (data.checkBox) {
  720. column.orderable = false;
  721. column.data = "check_state";
  722. column.render = function (data) {
  723. let checked = data ? "checked=\"checked\"" : "";
  724. return `
  725. <div class="form-check form-check-sm form-check-custom form-check-solid">
  726. <input name="check_state" class="form-check-input" type="checkbox" ${checked} value="${data}" />
  727. </div>`;
  728. }
  729. }
  730. if (data.formatter) {
  731. if (window[data.formatter] && typeof window[data.formatter] === "function") {
  732. column.render = function (d, t, r, m) {
  733. let v = t == "display" ?
  734. window[data.formatter].call(this, d, r) :
  735. d;
  736. return v;
  737. };
  738. } else {
  739. column.render = () => data.formatter + "";
  740. }
  741. }
  742. //formatter 后 tip就不能起作用。
  743. if (data.tip && !data.formatter) {
  744. column.render = function (value, type, row, meta) {
  745. if (type === 'display') {
  746. let length = Number(data.tip) && Number(data.tip) > 0 ? Number(data.tip) : 40;
  747. return value.length > length ? `<span data-bs-toggle="tooltip" title="${value}">${value.substr(0, length - 2)}...</span>` : value;
  748. }
  749. return value;
  750. };
  751. }
  752. if (data.tree && treeColumns) {
  753. treeColumns = false;
  754. column.title = '';
  755. column.target = 0;
  756. column.orderable = false;
  757. column.className = ClassName.TREE_TD_CONTROL;
  758. column.data = function (item) {
  759. if (item.children != null && item.children.length > 0) {
  760. return _config.expandIcon;
  761. }
  762. return _config.leafIcon;
  763. }
  764. }
  765. if (data.action) {
  766. // let action = `
  767. //<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;">操作
  768. // <!--Svg Icon | path: icons/duotone/Navigation/Angle-down.svg-->
  769. // <span class="svg-icon svg-icon-5 m-0 ms-1">
  770. // <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">
  771. // <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
  772. // <polygon points="0 0 24 0 24 24 0 24"></polygon>
  773. // <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>
  774. // </g>
  775. // </svg>
  776. // </span>
  777. //</span>`;
  778. if (data.actionTree) {
  779. column.className = "text-end pe-2";
  780. let treeActionMenu = "";
  781. $(_el).closest(Selector.TABLE_BOX).find(Selector.TOOLBAR_BAS + "," + Selector.TOOLBAR_SELECTED).addClass("d-none").find(Selector.TOOL_MENU_ALL).each(function () {
  782. let btnType = $(this).data(ClassName.TOOL_MENU_TYPE).replace("_", "");
  783. if (btnType !== "btnRefresh" && btnType !== "btnSearch") {
  784. let btnUrl = $(this).data(ClassName.TOOL_MENU_URL) || "";
  785. let btnName = $(this).text();
  786. //let btnClass = $(this).attr("class");
  787. let btnIcon = $(this).find("i").attr("class");
  788. /* 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>`;*/
  789. //$(this).remove();
  790. treeActionMenu += `<span class="table-action" onclick="$('#${_el.id}').VbTable('getToolFunctions')['${btnType}_tree'].call(this,'${btnUrl}','{0}')">${btnIcon ? `<i class="${btnIcon}"></i>` : icon}${btnName}</span>`
  791. } else if (btnType !== "btnSearch") {
  792. $(this).prop("disabled", false).attr("onclick", "$.vbAjax1({url: '" + $(this).data(ClassName.TOOL_MENU_URL) + "'});");
  793. }
  794. });
  795. data.actionFormatter = function treeActionFormatter(d, r) {
  796. return treeActionMenu.format(r[_config.rowId]);
  797. };
  798. }
  799. /* 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>`;*/
  800. if (data.actionFormatter) {
  801. let actionMenuFunc = typeof data.actionFormatter == "function" ? data.actionFormatter : typeof window[data.actionFormatter] == "function" ? window[data.actionFormatter] : false;
  802. if (actionMenuFunc) {
  803. column.render = function (d, t, r) {
  804. //return t == "display" ? `${action}\r\n${actionMenu.format(actionMenuFunc.call(this, d, r))}` : d;
  805. return t == "display" ? `${actionMenuFunc.call(this, d, r)}` : d;
  806. }
  807. }
  808. }
  809. }
  810. columns.push(column);
  811. });
  812. }
  813. return columns;
  814. };
  815. _proto._queryParams = function (param) {
  816. let _this = this, _config = _this._config;
  817. let queryParam, sort = "";
  818. if (param.order && param.order.length) {
  819. param.order.forEach((v) => {
  820. sort += (sort == "" ? "" : ",") + `${param.columns[v.column].name} ${v.dir}`;
  821. });
  822. }
  823. let $searchForm = _this._getSearchForm();
  824. let searchList = _this._getSearchList();
  825. if (_config.onlySearchList) {
  826. queryParam = {
  827. maxResultCount: params.limit,
  828. skipCount: params.offset,
  829. sorting: params.sort ? params.sort + ' ' + params.order : '',
  830. searchList: searchList
  831. };
  832. } else {
  833. let $search = $searchForm.find(Selector.SEARCH_GLOBAL);
  834. queryParam = {
  835. maxResultCount: param.length > 0 ? param.length : 1000,
  836. skipCount: param.start,
  837. sorting: sort,
  838. keyField: $search.data(ClassName.SEARCH_FIELD),
  839. fieldType: $search.data(ClassName.SEARCH_FIELD_TYPE) ? $search.data(ClassName.SEARCH_FIELD_TYPE) : 0,
  840. expType: $search.data(ClassName.SEARCH_EXP_TYPE) ? $search.data(ClassName.SEARCH_EXP_TYPE) : 0,
  841. keyWords: $search.val(),
  842. SearchList: searchList
  843. }
  844. }
  845. if (_LOG) {
  846. debug_log("table_queryParam", queryParam);
  847. }
  848. return JSON.stringify(queryParam);
  849. };
  850. _proto._getSearchForm = function () {
  851. let _this = this, _config = _this._config;
  852. let $form;
  853. if (_config.searchForm) {
  854. $form = typeof (_config.searchForm) === 'string'
  855. ? $('#' + _config.searchForm)
  856. : $(_config.searchForm);
  857. }
  858. if ($form && $form.length) {
  859. return $form;
  860. }
  861. $form = $(_this._element).closest(Selector.TABLE_BOX).find('form');
  862. return $form;
  863. }
  864. _proto._getSearchList = function () {
  865. let _this = this, _config = _this._config;
  866. let searchList = [];
  867. if (_config.searchFun && typeof _config.searchFun === "function") {
  868. _config.searchFun.call(_this, searchList);
  869. }
  870. if (_config.onlySearchFun) {
  871. return searchList;
  872. }
  873. if (_config.searchList && _config.searchList.length > 0) {
  874. _config.searchList.forEach(function (v) {
  875. if (v.keyWords) {
  876. searchList.push(v);
  877. }
  878. });
  879. }
  880. if (_config.onlySearchList) {
  881. return searchList;
  882. }
  883. let $searchForm = _this._getSearchForm();
  884. $searchForm.find(Selector.SEARCH_ADVANCE).each(function () {
  885. let $this = $(this), keyWords = $this.val();
  886. if (($this.attr('type') == "checkBox" || $this.attr('type') == "radio") && !$this.is(':checked')) {
  887. keyWords = undefined;
  888. }
  889. if (keyWords) {
  890. let field = $this.data(ClassName.SEARCH_FIELD), fieldType = $this.data(ClassName.SEARCH_FIELD_TYPE);
  891. // ReSharper disable once UnknownCssClass
  892. if ($this.hasClass(ClassName.DATE_RANGE)) {
  893. try {
  894. let dates = keyWords.split(` ${_config.dateRangeSpliter} `);
  895. searchList.push({
  896. keyWords: dates[0],
  897. keyField: field,
  898. fieldType: fieldType,
  899. expType: 4
  900. });
  901. if (dates.length === 2) {
  902. let nextDate = new Date(dates[1]);
  903. let newDate = new Date(nextDate.getFullYear(),
  904. nextDate.getMonth(),
  905. nextDate.getDate(),
  906. 23,
  907. 59,
  908. 59,
  909. 999);
  910. //let newDate = new Date(date.getTime() + 24 * 60 * 60 * 1000 - 1);
  911. let date2 = $.formatterDate('yyyy-MM-dd HH:mm:ss', newDate);
  912. searchList.push({
  913. keyWords: date2,
  914. keyField: field,
  915. fieldType: fieldType,
  916. expType: 5
  917. });
  918. }
  919. } catch (e) {
  920. console.log(e);
  921. }
  922. } else {
  923. let expType = $this.data(ClassName.SEARCH_EXP_TYPE)
  924. searchList.push({
  925. keyWords: keyWords,
  926. keyField: field,
  927. fieldType: fieldType,
  928. expType: expType
  929. });
  930. }
  931. }
  932. });
  933. return searchList;
  934. }
  935. _proto._responseHandler = function (res) {
  936. let _this = this, _config = _this._config;
  937. let json = jQuery.parseJSON(res);
  938. let result = {
  939. recordsTotal: 0,
  940. recordsFiltered: 0,
  941. data: []
  942. }
  943. if (json.success) {
  944. if (_config.isTree) {
  945. result.data = _this._toTreeData(json.result.items);
  946. } else {
  947. result.recordsTotal = json.result.totalCount;
  948. result.recordsFiltered = json.result.totalCount;
  949. result.data = json.result.items;
  950. }
  951. } else {
  952. console.log(`Table[${$(_this._element).attr('id')}] load failed`);
  953. if (res.error) {
  954. if (res.error.details) {
  955. return abp.message.error(res.error.details, res.error.message);
  956. } else {
  957. if (res.error.message && res.error.message.indexOf('登陆超时') >= 0) {
  958. return abp.message.error(res.error.message).done(function () {
  959. window.top.location.reload();
  960. });
  961. } else {
  962. return abp.message.error(res.error.message || abp.ajax.defaultError.message);
  963. }
  964. }
  965. }
  966. }
  967. debug_log("table_Data:", result);
  968. return JSON.stringify(result); // return JSON string
  969. }
  970. _proto._toTreeData = function (data) {
  971. let _this = this, _config = _this._config;
  972. let treeData = [];
  973. let f = _config.field ? _config.field : "id",
  974. pf = _config.parentField ? _config.parentField : "parentNo";
  975. function getChildren(parent) {
  976. let children = data.filter(function (v) { return v[pf] == parent[f]; });
  977. parent.children = [];
  978. if (children) {
  979. if (children.length) {
  980. parent.children = children;
  981. children.forEach((v) => { getChildren(v) })
  982. }
  983. //else {
  984. // parent.children.push(children);
  985. // getChildren(children)
  986. //}
  987. }
  988. }
  989. let root = data.filter(function (v) { return v[pf] == _config.root; });
  990. if (root) {
  991. if (root.length) {
  992. root.forEach(v => { treeData.push(v); getChildren(v); })
  993. }
  994. //else {
  995. // treeData.push(root);
  996. // getChildren(root);
  997. //}
  998. }
  999. return treeData;
  1000. }
  1001. _proto._rowCallback = function (row, data) {
  1002. let _this = this, _config = _this._config;
  1003. if (_config.multipleSelect && _config.clickToSelect) {
  1004. if ($.inArray(data.id + "", _selectedIdArray) !== -1) {
  1005. $(row).addClass(_config.select.className);
  1006. $(row).find(' input[type="checkbox"]').prop("checked", true);
  1007. }
  1008. } else {
  1009. _selectedIdArray = [];
  1010. }
  1011. }
  1012. _proto._onEvent = function () {
  1013. let _this = this, _config = _this._config, _el = _this._element;
  1014. let timeOutClick;
  1015. if (_config.onClickRow && typeof _config.onClickRow == "function") {
  1016. $(_el).find('tbody').on(`click${EVENT_KEY}.tr`, 'tr', function () {
  1017. clearTimeout(timeOutClick);
  1018. let __this = this;
  1019. timeOutClick = setTimeout(function () {
  1020. let row = dt.row(__this).data();
  1021. debug_log("table_tr_ckick", __this.id, row);
  1022. _config.onClickRow.call(_this, row);
  1023. }, 200)
  1024. });
  1025. }
  1026. if (_config.onDblClickRow && typeof _config.onDblClickRow == "function") {
  1027. $(_el).find('tbody').on(`dblclick${EVENT_KEY}.tr`, 'tr', function () {
  1028. clearTimeout(timeOutClick);
  1029. let row = dt.row(this).data();
  1030. debug_log("dbckick", this.id, row);
  1031. _config.onDblClickRow.call(_this, row);
  1032. });
  1033. }
  1034. dt.on(`draw${EVENT_KEY}`, function () {
  1035. //if ($(_el).find('tbody tr input[type="checkbox"]:not(:checked)').length) {
  1036. // $(_el).find('thead tr input[type="checkbox"]').prop("checked", false);
  1037. //} else {
  1038. // $(_el).find('thead tr input[type="checkbox"]').prop("checked", true);
  1039. //}
  1040. _this._toggleToolBars();
  1041. _this._drawRender();
  1042. });
  1043. $(_el).on(`resize${EVENT_KEY}`, () => { _this.reRender(); });
  1044. if (_config.checkBox) {
  1045. $(_el).find('thead tr th').on(`click${EVENT_KEY}.init`, 'input[type="checkbox"]', function (e) {
  1046. e.preventDefault();
  1047. e.stopPropagation();
  1048. let checked = this.checked;
  1049. if (checked) {
  1050. if (_config.onAllCheck && typeof _config.onAllCheck == "function") {
  1051. let rows = _this._mapData(dt.rows().data());
  1052. debug_log("table_allcheck", rows)
  1053. _config.onAllCheck.call(_this, rows);
  1054. }
  1055. } else {
  1056. if (_config.onAllUnCheck && typeof _config.onAllUnCheck == "function") {
  1057. let rows = _this._mapData(dt.rows().data());
  1058. debug_log("table_allUncheck", rows)
  1059. _config.onAllUnCheck.call(_this, rows);
  1060. }
  1061. }
  1062. setTimeout(() => {
  1063. const $allTrs = $(_el).find('tbody tr');
  1064. $allTrs.each(function () {
  1065. if (checked) {
  1066. if (!$(this).hasClass(_config.select.className)) {
  1067. $(this).addClass(_config.select.className);
  1068. }
  1069. } else {
  1070. $(this).removeClass(_config.select.className);
  1071. }
  1072. });
  1073. $allTrs.find('input[type="checkbox"]').each(function () {
  1074. let id = $(this).closest('tr').attr('id'), index = $.inArray(id, _selectedIdArray);
  1075. if (checked) {
  1076. $(this).prop("checked", true);
  1077. if (index == -1) {
  1078. _selectedIdArray.push(id);
  1079. }
  1080. } else {
  1081. $(this).prop("checked", false);
  1082. if (index > -1) {
  1083. _selectedIdArray.splice(index, 1);
  1084. }
  1085. }
  1086. });
  1087. if (_config.clickToSelect) {
  1088. _this._toggleToolBars();
  1089. }
  1090. }, 50);
  1091. });
  1092. }
  1093. $(_el).find('tbody').on(`click${EVENT_KEY}.init`, 'tr', function () {
  1094. let __this = this;
  1095. let row = dt.row(this).data();
  1096. setTimeout(() => {
  1097. if (_config.singleSelect) {
  1098. if ($(__this).hasClass(_config.select.className)) {
  1099. $(__this).find('input[name="check_state"][type="checkbox"]')
  1100. .prop("checked", false);
  1101. if (_config.clickToSelect) {
  1102. $(__this).removeClass(_config.select.className);
  1103. }
  1104. _selectedIdArray = [];
  1105. if (_config.onUnCheck && typeof _config.onUnCheck == "function") {
  1106. debug_log("table_tr_uncheck", row)
  1107. _config.onUnCheck.call(_this, row);
  1108. }
  1109. } else {
  1110. $(__this).find('input[name="check_state"][type="checkbox"]')
  1111. .prop("checked", true);
  1112. $(__this).siblings().removeClass(_config.select.className).find('input[name="check_state"][type="checkbox"]')
  1113. .prop("checked", false);
  1114. if (_config.clickToSelect) {
  1115. $(__this).addClass(_config.select.className);
  1116. }
  1117. _selectedIdArray = [__this.id];
  1118. if (_config.onCheck && typeof _config.onCheck == "function") {
  1119. debug_log("table_tr_check", row)
  1120. _config.onCheck.call(_this, row);
  1121. }
  1122. }
  1123. } else {
  1124. let id = __this.id;
  1125. let index = $.inArray(id, _selectedIdArray);
  1126. if (index === -1) {
  1127. _selectedIdArray.push(id);
  1128. $(__this).find('input[name="check_state"][type="checkbox"]').prop('checked', true);
  1129. if (_config.clickToSelect) {
  1130. $(__this).addClass(_config.select.className);
  1131. }
  1132. if (_config.onCheck && typeof _config.onCheck == "function") {
  1133. debug_log("table_tr_check", row)
  1134. _config.onCheck.call(_this, row);
  1135. }
  1136. } else {
  1137. _selectedIdArray.splice(index, 1);
  1138. $(__this).find('input[name="check_state"][type="checkbox"]').prop('checked', false);
  1139. if (_config.clickToSelect) {
  1140. $(__this).removeClass(_config.select.className);
  1141. }
  1142. if (_config.onUnCheck && typeof _config.onUnCheck == "function") {
  1143. debug_log("table_tr_uncheck", row)
  1144. _config.onUnCheck.call(_this, row);
  1145. }
  1146. }
  1147. }
  1148. if (_config.clickToSelect) {
  1149. _this._toggleToolBars();
  1150. }
  1151. }, 50);
  1152. });
  1153. }
  1154. _proto._toggleToolBars = function () {
  1155. let _this = this, _config = _this._config, _el = _this._element;
  1156. const $box = $(_el).closest(Selector.TABLE_BOX),
  1157. $toolbarBase = $box.find(Selector.TOOLBAR_BASE),
  1158. $toolbarSelected = $box.find(Selector.TOOLBAR_SELECTED),
  1159. $selectedCount = $box.find(Selector.TOOLBAR_SELECTED_COUNT);
  1160. if (_config.singleSelect) {
  1161. $selectedCount.parent().addClass('d-none');
  1162. }
  1163. if (_selectedIdArray.length) {
  1164. $selectedCount.html(_selectedIdArray.length);
  1165. $toolbarBase.addClass('d-none');
  1166. $toolbarSelected.removeClass('d-none');
  1167. } else {
  1168. $toolbarBase.removeClass('d-none');
  1169. $toolbarSelected.addClass('d-none');
  1170. }
  1171. if ($(_el).find('tbody tr input[type="checkbox"]:not(:checked)').length) {
  1172. $(_el).find('thead tr input[type="checkbox"]').prop("checked", false);
  1173. } else {
  1174. $(_el).find('thead tr input[type="checkbox"]').prop("checked", true);
  1175. }
  1176. debug_log("table_selectIds", _selectedIdArray);
  1177. }
  1178. _proto._mapData = function (data) {
  1179. let rows = [];
  1180. for (let i = 0; i < data.length; i++) {
  1181. let row = data[i + ""];
  1182. rows.push(row);
  1183. }
  1184. return rows;
  1185. };
  1186. _proto._renderSelectRows = function () {
  1187. let _this = this, _config = _this._config, _el = _this._element;
  1188. if (_config.pageSelect && _selectedIdArray.length) {
  1189. $(_el).find("tbody tr").each(function () {
  1190. let id = $(this).attr('id');
  1191. if (_selectedIdArray.indexOf(id) > -1) {
  1192. $(this).find('input[name="check_state"][type="checkbox"]').prop('checked', true);
  1193. $(this).addClass(_config.select.className);
  1194. }
  1195. });
  1196. }
  1197. }
  1198. _proto._getModalOption = function (url, opt, title, type) {
  1199. let _this = this, _config = _this._config, $table = $(_this._element);
  1200. let modalOpts = $.extend({}, { url: "" });
  1201. modalOpts.opTitle = title;
  1202. modalOpts.draggable = _config.modalDrag;
  1203. modalOpts.fromValidate = true;
  1204. if (!opt) {
  1205. opt = !url || typeof url === "string" ? {} : url;
  1206. }
  1207. if (opt.hasOwnProperty("url")) {
  1208. modalOpts.url = opt.url;
  1209. } else if (typeof url === "string") {
  1210. modalOpts.url = url;
  1211. }
  1212. if (!modalOpts.url) {
  1213. let $tableToolMENU = $table.closest(Selector.TABLE_BOX).find(Selector.TOOL_MENU.format(type));
  1214. modalOpts.url = $tableToolMENU.data([ClassName.TOOL_MENU_URL]);
  1215. }
  1216. modalOpts.modal =
  1217. typeof _config.modal === 'string' ? $("#" + _config.modal) : $(_config.modal);
  1218. modalOpts.table = $table;
  1219. //modalOptions.type = type.toLowerCase().indexOf('btnupdate') === 0 ? 'put' : 'post';
  1220. modalOpts.type = 'post';
  1221. modalOpts = $.extend({}, modalOpts, opt);
  1222. return modalOpts;
  1223. }
  1224. _proto._initToolFunction = function () {
  1225. let _this = this;
  1226. _this.addToolFunctions("btnCreate", function (url) { _this.create(url); });
  1227. _this.addToolFunctions("btnUpdate", function (url) { _this.update(url); });
  1228. _this.addToolFunctions("btnDelete", function (url) { _this.delete(url); });
  1229. _this.addToolFunctions("btnSearch", function () { _this.refresh(true); });
  1230. _this.addToolFunctions("none", function () { console.log("No type"); });
  1231. let $tableToolMenu = $(_this._element).closest(Selector.TABLE_BOX).find(Selector.TOOL_MENU_ALL);
  1232. $tableToolMenu.off().on(`click${EVENT_KEY}.menu`,
  1233. function () {
  1234. let funs = _this.getToolFunctions();
  1235. let type = $(this).data(ClassName.TOOL_MENU_TYPE);
  1236. let index = type.lastIndexOf('_');
  1237. type = index > -1 ? type.substr(index + 1) : type;
  1238. let url = $(this).data(ClassName.TOOL_MENU_URL) || "";
  1239. funs[type] ? funs[type].call(this, url) : funs["none"].call(this);
  1240. });
  1241. };
  1242. _proto._drawRender = function () {
  1243. $(this._element).find('[data-bs-toggle="tooltip"]').each(function () {
  1244. new bootstrap.Tooltip(this, {
  1245. delay: 500
  1246. });
  1247. });
  1248. KTMenu.createInstances('[data-kt-menu-action="true"]')
  1249. };
  1250. _proto._initTree = function () {
  1251. let _this = this, _config = _this._config, _el = _this._element;
  1252. let treeOption = {
  1253. left: _config.left > 0 ? _config.left : 10,
  1254. expandAll: _config.expandAll,
  1255. leafIcon: _config.leafIcon,
  1256. expandIcon: _config.expandIcon,
  1257. collapseIcon: _config.collapseIcon,
  1258. fnDrawCallback: _config.fnDrawCallback
  1259. }
  1260. _config.treeOption = treeOption;
  1261. _this._onTreeEvent();
  1262. _this.addToolFunctions("btnCreate_tree", function (url, id) {
  1263. let row = _this.getRow(id);
  1264. if (row) {
  1265. let data = {};
  1266. data[_config.parentField] = row[_config.field];
  1267. data[_config.parentNameField] = row[_config.nameField];
  1268. _this.create(url, { data: data });
  1269. }
  1270. })
  1271. _this.addToolFunctions("btnUpdate_tree", function (url, id) {
  1272. let row = _this.getRow(id);
  1273. if (row) {
  1274. _this.update(url, { data: row }, row);
  1275. }
  1276. })
  1277. _this.addToolFunctions("btnDelete_tree", function (url, id) {
  1278. let row = _this.getRow(id);
  1279. if (row) {
  1280. _this.delete(url, { data: row }, row);
  1281. }
  1282. })
  1283. _this.addToolFunctions("btnMoveUp_tree", function (url, id) {
  1284. console.log("MoveUp", id);
  1285. let row = _this.getRow(id);
  1286. if (row) {
  1287. let $prev = $('#' + row[_config.rowId]).prev();
  1288. if ($prev.length) {
  1289. let prevRow = _this.getRow($prev.attr('id'));
  1290. if (prevRow && prevRow[_config.parentField] == row[_config.parentField]) {
  1291. $.vbAjax1({ url: url, data: { Id: id, MoveId: prevRow[_config.rowId] }, table: $(_el) });
  1292. return;
  1293. }
  1294. }
  1295. abp.message.warn(abp.localization.VberZero("RecordAtTop"));
  1296. }
  1297. })
  1298. _this.addToolFunctions("btnMoveDown_tree", function (url, id) {
  1299. console.log("MoveDown", id);
  1300. let row = _this.getRow(id);
  1301. if (row) {
  1302. let $next = $('#' + row[_config.rowId]).next();
  1303. if ($next.length) {
  1304. let nextRow = _this.getRow($next.attr('id'));
  1305. if (nextRow && nextRow[_config.parentField] == row[_config.parentField]) {
  1306. $.vbAjax1({ url: url, data: { Id: id, MoveId: nextRow[_config.rowId] }, table: $(_el) });
  1307. return;
  1308. }
  1309. }
  1310. abp.message.warn(abp.localization.VberZero("RecordAtBottom"));
  1311. }
  1312. })
  1313. };
  1314. _proto._resetEvenOddClass = function () {
  1315. let classes = ['odd', 'even'];
  1316. $(dt.table().body()).find('tr').each(function (index, tr) {
  1317. $(tr).removeClass('odd even').addClass(classes[index % 2]);
  1318. });
  1319. };
  1320. _proto._resetTreeGridRows = function (id) {
  1321. let _this = this, treeOption = _this._config.treeOption;
  1322. let subRows = treeGridRows[id];
  1323. if (subRows && subRows.length) {
  1324. subRows.forEach(function (node) {
  1325. let subTrId = $(node).attr('id');
  1326. if (treeGridRows[subTrId]) {
  1327. _this._resetTreeGridRows(subTrId);
  1328. }
  1329. dt.row($(node)).remove();
  1330. $(node).remove();
  1331. });
  1332. delete treeGridRows[id];
  1333. let p_depth = $('#' + id).data('depth') || 0,
  1334. $icon = $(treeOption.expandIcon).css('marginLeft', p_depth * treeOption.left + 'px');
  1335. $('#' + id).find(Selector.TREE_TD_CONTROL_OPEN)
  1336. .removeClass(ClassName.TREE_TD_CONTROL_OPEN)
  1337. .addClass(ClassName.TREE_TD_CONTROL)
  1338. .html($icon);
  1339. }
  1340. };
  1341. _proto._onTreeEvent = function () {
  1342. let _this = this, _config = _this._config;
  1343. //let treeOption = _config.treeOption;
  1344. dt.on(`click${EVENT_KEY}.tree`, Selector.TREE_TD_CONTROL, function (e) {
  1345. _this.treeExpand($(e.target).closest('tr').attr("id"));
  1346. })
  1347. dt.on(`click${EVENT_KEY}.tree`, Selector.TREE_TD_CONTROL_OPEN, function (e) {
  1348. _this.treeCollapse($(e.target).closest('tr').attr("id"));
  1349. })
  1350. dt.on(`draw${EVENT_KEY}.tree`, function () {
  1351. _this._treeExpandAll(_config.expandDepth);
  1352. })
  1353. }
  1354. _proto._treeExpandAll = function (depth, id) {
  1355. let _this = this;
  1356. depth = depth == undefined ? true : depth - 1;
  1357. let children = _this.treeExpand(id || null);
  1358. if (depth && children && children.length) {
  1359. children.forEach(v => {
  1360. _this._treeExpandAll(depth, $(v).attr('id'));
  1361. })
  1362. }
  1363. }
  1364. _proto.treeExpandAll = function () {
  1365. this._treeExpandAll();
  1366. }
  1367. _proto.treeExpand = function (id) {
  1368. let _this = this, _config = _this._config;
  1369. let treeOption = _config.treeOption;
  1370. let $tr = id ? $('#' + id) : $(dt.row(0).node());
  1371. let subRows = treeGridRows[$tr.attr('id')] = []
  1372. let p_depth = $tr.data('depth') || 0;
  1373. let row = dt.row($tr[0]),
  1374. index = row.index(),
  1375. data = row.data();
  1376. debug_log("table_tree_open:", index, data);
  1377. if (data.children && data.children.length) {
  1378. let $td = $tr.find(Selector.TREE_TD_CONTROL),
  1379. //paddingLeft = parseInt($td.css('padding-left'), 10),
  1380. //layer = parseInt($td.find('span').css('margin-left') || 0, 10) / treeOption.left,
  1381. $icon = $(treeOption.collapseIcon);
  1382. $icon.css('marginLeft', p_depth * treeOption.left + 'px');
  1383. $td.removeClass(ClassName.TREE_TD_CONTROL).addClass(ClassName.TREE_TD_CONTROL_OPEN).html($icon);
  1384. let prevRow = row.node();
  1385. p_depth++;
  1386. data.children.forEach(function (item) {
  1387. let node = dt.row.add(item).node();
  1388. $(node).data('depth', p_depth);
  1389. //$(node).attr('parent-index', index);
  1390. //let $childTd = $(node).find(Selector.TREE_TD_CONTROL);
  1391. $(node).find(Selector.TREE_TD_CONTROL).find('span').css('marginLeft', p_depth * treeOption.left + 'px');
  1392. //.next().css('paddingLeft', paddingLeft + left + 'px');
  1393. $(node).insertAfter(prevRow);
  1394. prevRow = node;
  1395. subRows.push(node);
  1396. })
  1397. _this._resetEvenOddClass();
  1398. _this._drawRender();
  1399. }
  1400. return subRows;
  1401. }
  1402. _proto.treeCollapse = function (id) {
  1403. let _this = this, _config = _this._config;
  1404. let treeOption = _config.treeOption;
  1405. let $tr = $('#' + id), $td = $tr.find(Selector.TREE_TD_CONTROL_OPEN),
  1406. //paddingLeft = parseInt($td.css('padding-left'), 10),
  1407. //layer = parseInt($td.find('span').css('margin-left') || 0, 10) / treeOption.left,
  1408. p_depth = $tr.data('depth') || 0,
  1409. $icon = $(treeOption.expandIcon).css('marginLeft', p_depth * treeOption.left + 'px');
  1410. $td.removeClass(ClassName.TREE_TD_CONTROL_OPEN).addClass(ClassName.TREE_TD_CONTROL).html($icon);
  1411. _this._resetTreeGridRows(id);
  1412. _this._resetEvenOddClass();
  1413. }
  1414. _proto.addToolFunctions = function (key, fun) {
  1415. let _this = this;
  1416. let toolFunctions = _this.getToolFunctions();
  1417. toolFunctions[key] = fun;
  1418. _this._config.toolFunctions = toolFunctions;
  1419. };
  1420. _proto.getToolFunctions = function () {
  1421. return this._config.toolFunctions;
  1422. }
  1423. _proto.create = function (url, opt) {
  1424. let _this = this;
  1425. console.log("Add---" + _this._element.id);
  1426. opt = opt || {};
  1427. let modalOpts = _this._getModalOption(url, opt, abp.localization.VberZero('OpCreate'), '_btnCreate');
  1428. let $modal = typeof modalOpts.modal === 'string'
  1429. ? $('#' + modalOpts.modal)
  1430. : $(modalOpts.modal);
  1431. $modal.VbModal(modalOpts);
  1432. }
  1433. _proto.update = function (url, opt, row) {
  1434. let _this = this;
  1435. console.log("Update---" + _this._element.id);
  1436. opt = opt || {};
  1437. row = row || opt.row || _this.getSelection();
  1438. if (row) {
  1439. let modalOptions = _this._getModalOption(url, opt, abp.localization.VberZero('OpUpdate'), 'btnUpdate');
  1440. if (!modalOptions.data) {
  1441. modalOptions.data = row;
  1442. }
  1443. let $modal = typeof (modalOptions.modal) === 'string'
  1444. ? $('#' + modalOptions.modal)
  1445. : $(modalOptions.modal);
  1446. $modal.VbModal(modalOptions);
  1447. }
  1448. }
  1449. _proto.delete = function (url, opt, row) {
  1450. let _this = this;
  1451. console.log("Delete---" + _this._element.id);
  1452. opt = opt || {};
  1453. row = row || opt.row || _this.getSelection();
  1454. if (row) {
  1455. let data = opt.data || { id: row.id };
  1456. abp.message.confirm(abp.localization.VberZero('DeleteConfirmContent'),
  1457. abp.localization.VberZero('DeleteConfirm'),
  1458. function (isConfirmed) {
  1459. if (isConfirmed) {
  1460. $.vbAjax1({
  1461. table: $table,
  1462. url: url + '?' + _this._config.id + '=' + data[_this._config.id],
  1463. data: data
  1464. });
  1465. }
  1466. });
  1467. }
  1468. }
  1469. _proto.destroy = function () {
  1470. let _this = this, $this = $(_this._element);
  1471. $this.removeData(DATA_KEY);
  1472. $this.DataTable('destroy');
  1473. }
  1474. _proto.getSelection = function () {
  1475. return this.getSelections()[0];
  1476. }
  1477. _proto.getSelections = function () {
  1478. let _this = this, _config = _this._config;
  1479. let data = dt.rows("." + _config.select.className).data();
  1480. return _this._mapData(data);
  1481. }
  1482. _proto.getSelectionIds = function () {
  1483. return _selectedIdArray;
  1484. }
  1485. _proto.getRow = function (id) {
  1486. let data = dt.row($("#" + id)).data();
  1487. debug_log("row", id, data);
  1488. return data;
  1489. }
  1490. _proto.getInstance = function () {
  1491. return dt;
  1492. }
  1493. _proto.reRender = function () {
  1494. dt.draw();
  1495. }
  1496. _proto.refresh = function (resetPaging, callback) {
  1497. dt.ajax.reload(callback, resetPaging);
  1498. }
  1499. Table._jQueryInterface = function _jQueryInterface(option) {
  1500. let value, args = Array.prototype.slice.call(arguments, 1);
  1501. this.each(function () {
  1502. let $this = $(this), data = $this.data(DATA_KEY);
  1503. if (typeof option === 'string') {
  1504. if ($.inArray(option, ALLOW_METHOD) < 0) {
  1505. throw new Error("Unknown method: " + option);
  1506. }
  1507. if (!data) {
  1508. return;
  1509. }
  1510. value = data[option].apply(data, args);
  1511. }
  1512. if (!data) {
  1513. let options = $.extend({}, Default, $(this).data(), typeof option === 'object' && option);
  1514. data = new Table(this, options);
  1515. $this.data(DATA_KEY, data);
  1516. }
  1517. });
  1518. return typeof value === 'undefined' ? this : value;
  1519. }
  1520. return Table;
  1521. }();
  1522. /*
  1523. * jQuery API
  1524. * ====================================================
  1525. */
  1526. $.fn[NAME] = Table._jQueryInterface;
  1527. $.fn[NAME].Constructor = Table;
  1528. $.fn[NAME].noConflict = function () {
  1529. $.fn[NAME] = JQUERY_NO_CONFLICT;
  1530. return Table._jQueryInterface;
  1531. };
  1532. return Table;
  1533. }((jQuery));
  1534. let VbModal = function ($) {
  1535. const NAME = 'VbModal';
  1536. const DATA_KEY = 'vb.modal';
  1537. const EVENT_KEY = "." + DATA_KEY;
  1538. const ClassName = {
  1539. CREATE_BOX: "modal-container",
  1540. MODAL: 'modal',
  1541. MODAL_LG: 'modal-lg',
  1542. MODAL_DIALOG: 'modal-dialog',
  1543. MODAL_CONTENT: 'modal-content',
  1544. MODAL_HEADER: 'modal-header',
  1545. MODAL_BODY: 'modal-body',
  1546. MODAL_FOOTER: 'modal-footer',
  1547. BODY: 'body',
  1548. SAVE_BUTTON: 'save-btn',
  1549. CLEAN: 'error valid not-clean invalid valid',
  1550. NOT_CLEAN_TAG: 'not-clear-tag',
  1551. DEFAULT_VALUE: 'default-value',
  1552. AJAX_SELECT: 'ajax-select',
  1553. AJAX_SELECT_SET_VALUE: 'set-value',
  1554. AJAX_SELECT_CODE: 'code-key',
  1555. DRAG_SELECT: "drag-select",
  1556. INVALID_FEEDBACK: "invalid-feedback",
  1557. INVALID_FEEDBACK_SHOW: "invalid-feedback-show"
  1558. }
  1559. const Selector = {
  1560. CREATE_BOX: ".modal-container",
  1561. MODAL_DIALOG: '.modal-dialog',
  1562. MODAL_CONTENT: '.modal-content',
  1563. MODAL_HEADER: '.modal-header',
  1564. MODAL_TITLE: '.modal-title',
  1565. MODAL_TITLE_PRE: '.modal-title .pre',
  1566. MODAL_BODY: '.modal-body',
  1567. MODAL_FOOTER: '.modal-footer',
  1568. MODAL_TAB_LINK: '.tab-auto .nav-item .nav-link',
  1569. SAVE_BUTTON: `.${ClassName.SAVE_BUTTON}`,
  1570. CLEAN: 'input,select,textarea',
  1571. DISABLED: 'input:not(.disabled),select:not(.disabled),textarea:not(.disabled)',
  1572. READONLY: 'input:not(.readonly),select:not(.readonly),textarea:not(.readonly)',
  1573. 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})`,
  1574. NOT_CLEAN_TAG: `.${ClassName.NOT_CLEAN_TAG}`,
  1575. FORM_FIRST: 'input:not(:disabled,[type="hidden"],[readonly="readonly"]):first',
  1576. select2: '.select',
  1577. select2tree: 'select[data-select-tree="true"]',
  1578. AJAX_SELECT: `.${ClassName.AJAX_SELECT}`,
  1579. WANG_EDITOR: 'div.vb-wang-editor',
  1580. INPUT_FILE: 'input[type="file"]',
  1581. SUBMIT_INPUT: '.modal-body input,.modal-body textarea',
  1582. INVALID_FEEDBACK: `.${ClassName.INVALID_FEEDBACK}`
  1583. }
  1584. const JQUERY_NO_CONFLICT = $.fn[NAME];
  1585. const ALLOW_METHOD = [
  1586. 'open',
  1587. 'show',
  1588. 'hide',
  1589. 'create'
  1590. ];
  1591. const WangEditor_DATA_KEY = "WangEditor_DATA_KEY";
  1592. const Default = {
  1593. modal: undefined,
  1594. title: '',
  1595. opTitle: '',
  1596. data: null,
  1597. dataFun: undefined,
  1598. form: null,
  1599. table: undefined,
  1600. rules: {},
  1601. readonly: '',
  1602. disabled: '',
  1603. notClear: '',
  1604. select2: undefined,
  1605. select2tree: undefined,
  1606. url: '',
  1607. type: 'post',
  1608. saveBtn: null,
  1609. save: null,
  1610. success: null,
  1611. showBefore: null,
  1612. showAfter: null,
  1613. isRefresh: true,
  1614. draggable: true,
  1615. backdrop: 'static',
  1616. keyboard: true,
  1617. //kindeditorOption: {},
  1618. content: undefined,
  1619. ajaxSelect: true,
  1620. needForm: true,
  1621. isInit: true,
  1622. }
  1623. let Modal = function () {
  1624. function Modal(element, config, isCreate) {
  1625. this._element = element;
  1626. this._config = config;
  1627. if (!isCreate) {
  1628. this._getModal(config);
  1629. }
  1630. }
  1631. let _proto = Modal.prototype;
  1632. _proto._getModal = function (opts, modal) {
  1633. let _this = this;
  1634. _this._config = $.extend({}, _this._config, opts || {});
  1635. let $modal;
  1636. if (modal) {
  1637. $modal = typeof (modal) === 'string'
  1638. ? $('#' + modal)
  1639. : $(modal);
  1640. } else {
  1641. $modal = _this._config.modalId
  1642. ? $('#' + _this._config.modalId)
  1643. : typeof (_this._config.modal) === 'string'
  1644. ? $('#' + _this._config.modal)
  1645. : $(_this._config.modal);
  1646. }
  1647. if ($(_this._element).hasClass(ClassName.MODAL)) {
  1648. if ($modal.length) {
  1649. _this._element = $modal[0];
  1650. } else {
  1651. $modal = $(_this._element);
  1652. }
  1653. } else {
  1654. if (!$modal.length) {
  1655. throw new Error("未发现模态框!");
  1656. }
  1657. if (!_this._config.modal && !_this._config.modalId) {
  1658. throw new Error("未配置模态框!");
  1659. }
  1660. _this._element = $modal[0];
  1661. }
  1662. return $modal;
  1663. };
  1664. _proto._init = function () {
  1665. let _this = this, _config = _this._config, $modal = $(_this._element);
  1666. _this._clearOldVal();
  1667. $modal.find(Selector.INVALID_FEEDBACK).html("").removeClass(ClassName.INVALID_FEEDBACK_SHOW);
  1668. $modal.find(Selector.CLEAN).removeClass(ClassName.CLEAN);
  1669. $modal.find(Selector.INVALID_FEEDBACK).removeClass(ClassName.INVALID_FEEDBACK_SHOW);
  1670. $modal.find(Selector.DISABLED).prop('disabled', false);
  1671. $modal.find(Selector.READONLY).prop('readonly', false);
  1672. $modal.find(Selector.MODAL_TITLE_PRE).html(_config.opTitle);
  1673. $modal.find(Selector.MODAL_TAB_LINK).eq(0).tab("show");
  1674. _this._setReadonly();
  1675. _this._setDisabled();
  1676. _this._cleanFile();
  1677. $modal.find(Selector.FORM_FIRST).focus();
  1678. };
  1679. _proto._setReadonly = function () {
  1680. let _this = this, _config = _this._config, $modal = $(_this._element);
  1681. if (_config.readonly) {
  1682. let readonly = _config.readonly.split(',');
  1683. for (let i = 0; i < readonly.length; i++) {
  1684. if (readonly[i]) {
  1685. $modal.find(`[name="${readonly[i]}"]`).prop('readonly', true);
  1686. }
  1687. }
  1688. }
  1689. if (_config.no_readonly) {
  1690. let no_readonly = _config.no_readonly.split(',');
  1691. for (let j = 0; j < no_readonly.length; j++) {
  1692. if (no_readonly[j]) {
  1693. $modal.find(`[name="${no_readonly[j]}"]`).prop('readonly', false);
  1694. }
  1695. }
  1696. }
  1697. };
  1698. _proto._setDisabled = function () {
  1699. let _this = this, _config = _this._config, $modal = $(_this._element);
  1700. if (_config.disabled) {
  1701. let disabled = _config.disabled.split(',');
  1702. for (let i = 0; i < disabled.length; i++) {
  1703. if (disabled[i]) {
  1704. $modal.find(`[name="${disabled[i]}"]`).prop('disabled', true);
  1705. }
  1706. }
  1707. }
  1708. if (_config.no_disabled) {
  1709. let no_disabled = _config.no_disabled.split(',');
  1710. for (let j = 0; j < no_disabled.length; j++) {
  1711. if (no_disabled[j]) {
  1712. $modal.find(`[name="${no_disabled[j]}"]`).prop('disabled', true);
  1713. }
  1714. }
  1715. }
  1716. };
  1717. _proto._setSelect2 = function () {
  1718. let _this = this, _config = _this._config, $modal = $(_this._element);
  1719. if (_config.select2) {
  1720. let select2 = _config.select2.split(',');
  1721. for (let i = 0; i < select2.length; i++) {
  1722. $modal.find(`[name="${select2[i]}"]`).select2tree();
  1723. }
  1724. }
  1725. if (_config.select2tree) {
  1726. let tree = _config.select2tree.split(',');
  1727. for (let j = 0; j < tree.length; j++) {
  1728. $modal.find(`[name="${tree[j]}"]`).select2tree();
  1729. }
  1730. }
  1731. $modal.find('select').trigger("change");
  1732. $modal.find('select').off("change.ff").on("change.ff", function () {
  1733. $(this).focus();
  1734. $(this).removeClass(ClassName.CLEAN).parent().find(Selector.INVALID_FEEDBACK).removeClass(ClassName.INVALID_FEEDBACK_SHOW);
  1735. $(this).blur();
  1736. });
  1737. };
  1738. _proto._setData = function () {
  1739. let _this = this, _config = _this._config, $modal = $(_this._element);
  1740. let $form = $modal.find('form');
  1741. $(Selector.AJAX_SELECT).addClass(ClassName.AJAX_SELECT_SET_VALUE);
  1742. $.formDeserialize($form, _config.data);
  1743. };
  1744. _proto._clearOldVal = function () {
  1745. let _this = this, _config = _this._config, $modal = $(_this._element);
  1746. if (_config.notClear) {
  1747. let notClear = _config.notClear.split(',');
  1748. for (let i = 0; i < notClear.length; i++) {
  1749. if (notClear[i]) {
  1750. $modal.find(`[name="${notClear[i]}"]`).addClass(ClassName.NOT_CLEAN_TAG);
  1751. }
  1752. }
  1753. }
  1754. $modal.find(Selector.CLEAN_VALUE).val('');
  1755. $modal.find(Selector.NOT_CLEAN_TAG).removeClass(ClassName.NOT_CLEAN_TAG);
  1756. };
  1757. _proto._initWangEditor = function () {
  1758. let _this = this, $modal = $(_this._element);
  1759. $modal.find(Selector.WANG_EDITOR).each(function () {
  1760. if ($.fn.VbWangEditor) {
  1761. if (!$(this).data('vb.wang_editor')) {
  1762. let config = _this._config.wangEditorOption || {};
  1763. $(this).VbWangEditor(config);
  1764. $(this).data(WangEditor_DATA_KEY, true);
  1765. }
  1766. }
  1767. });
  1768. };
  1769. _proto._setWangEditorData = function () {
  1770. let _this = this, $modal = $(_this._element);
  1771. $modal.find(Selector.WANG_EDITOR).each(function () {
  1772. if ($.fn.VbWangEditor) {
  1773. if ($(this).data('vb.wang_editor')) {
  1774. let val = $modal.find(`[name="${$(this).data('editor-name')}"]`).val();
  1775. $(this).VbWangEditor('setContent', val);
  1776. }
  1777. }
  1778. });
  1779. };
  1780. _proto._cleanFile = function () {
  1781. let _this = this, $modal = $(_this._element);
  1782. $modal.find(Selector.INPUT_FILE).each(function () {
  1783. //TODO
  1784. //$(this).parent().VbFile('cleanFile');
  1785. });
  1786. };
  1787. _proto._draggable = function () {
  1788. let _this = this, _config = _this._config, $modal = $(_this._element);
  1789. if (_config.draggable) {
  1790. /** 拖拽模态框*/
  1791. let dragModal = {
  1792. mouseStartPoint: { 'left': 0, 'top': 0 },
  1793. mouseEndPoint: { 'left': 0, 'top': 0 },
  1794. mouseDragDown: false,
  1795. basePoint: { 'left': 0, 'top': 0 },
  1796. moveTarget: null,
  1797. topLeng: 0
  1798. };
  1799. $modal.off('mousedown.drag' + EVENT_KEY, Selector.MODAL_HEADER).on('mousedown.drag' + EVENT_KEY,
  1800. Selector.MODAL_HEADER,
  1801. function (e) {
  1802. $modal.find(Selector.MODAL_HEADER).css('cursor', 'move');
  1803. //webkit内核和火狐禁止文字被选中
  1804. $('body').addClass(ClassName.DRAG_SELECT);
  1805. //ie浏览器禁止文字选中
  1806. document.body.onselectstart = document.body.ondrag = function () {
  1807. return false;
  1808. };
  1809. if ($(e.target).hasClass('close')) //点关闭按钮不能移动对话框
  1810. return;
  1811. dragModal.mouseDragDown = true;
  1812. dragModal.moveTargetHeader = $(this);
  1813. dragModal.moveTarget = $(this).closest(Selector.MODAL_CONTENT);
  1814. dragModal.mouseStartPoint = { 'left': e.clientX, 'top': e.pageY };
  1815. dragModal.basePoint = dragModal.moveTarget.offset();
  1816. dragModal.topLeng = e.pageY - e.clientY;
  1817. });
  1818. $modal.off(`mouseup.drag${EVENT_KEY}`).on(`mouseup.drag${EVENT_KEY}`,
  1819. function () {
  1820. $modal.find(Selector.MODAL_HEADER).css('cursor', 'default');
  1821. dragModal.mouseDragDown = false;
  1822. dragModal.moveTarget = undefined;
  1823. dragModal.mouseStartPoint = { 'left': 0, 'top': 0 };
  1824. dragModal.basePoint = { 'left': 0, 'top': 0 };
  1825. });
  1826. $modal.off(`mousemove.drag${EVENT_KEY}`).on(`mousemove.drag${EVENT_KEY}`,
  1827. function (e) {
  1828. if (!dragModal.mouseDragDown || dragModal.moveTarget === undefined) return;
  1829. $modal.find(Selector.MODAL_HEADER).css('cursor', 'move');
  1830. let mouseX = e.clientX;
  1831. let mouseY = e.pageY;
  1832. if (mouseX < 0) mouseX = 0;
  1833. if (mouseY < 0) mouseY = 25;
  1834. dragModal.mouseEndPoint = { 'left': mouseX, 'top': mouseY };
  1835. let width = dragModal.moveTarget.width();
  1836. let height = dragModal.moveTargetHeader.height();
  1837. let clientWidth = document.body.clientWidth;
  1838. let clientHeight = document.body.clientHeight;
  1839. if (dragModal.mouseEndPoint.left < dragModal.mouseStartPoint.left - dragModal.basePoint.left) {
  1840. dragModal.mouseEndPoint.left = 0;
  1841. } else if (dragModal.mouseEndPoint.left >=
  1842. clientWidth - width + dragModal.mouseStartPoint.left - dragModal.basePoint.left) {
  1843. dragModal.mouseEndPoint.left = clientWidth - width - 2;
  1844. } else {
  1845. dragModal.mouseEndPoint.left =
  1846. dragModal.mouseEndPoint.left -
  1847. (dragModal.mouseStartPoint.left - dragModal.basePoint.left); //移动修正,更平滑
  1848. }
  1849. if (dragModal.mouseEndPoint.top - (dragModal.mouseStartPoint.top - dragModal.basePoint.top) <
  1850. dragModal.topLeng) {
  1851. dragModal.mouseEndPoint.top = dragModal.topLeng;
  1852. } else if (dragModal.mouseEndPoint.top - dragModal.topLeng >
  1853. clientHeight - height + dragModal.mouseStartPoint.top - dragModal.basePoint.top) {
  1854. dragModal.mouseEndPoint.top = clientHeight - height - 38 + dragModal.topLeng;
  1855. } else {
  1856. dragModal.mouseEndPoint.top = dragModal.mouseEndPoint.top -
  1857. (dragModal.mouseStartPoint.top - dragModal.basePoint.top);
  1858. }
  1859. dragModal.moveTarget.offset(dragModal.mouseEndPoint);
  1860. });
  1861. $modal.off(`hidden.bs.modal${EVENT_KEY}.drag`).on(`hidden.bs.modal${EVENT_KEY}.drag`, function () {
  1862. $modal.find(Selector.MODAL_HEADER).css('cursor', 'default');
  1863. $modal.find(Selector.MODAL_CONTENT).css({ 'top': 0, 'left': 0 });
  1864. $('body').removeClass(ClassName.DRAG_SELECT);
  1865. document.body.onselectstart = document.body.ondrag = null;
  1866. });
  1867. } else {
  1868. $modal.find(Selector.MODAL_HEADER).css('cursor', 'default');
  1869. }
  1870. };
  1871. _proto._showBefore = function () {
  1872. let _this = this, _config = _this._config, $modal = $(_this._element);
  1873. if (_config.showBefore && typeof (_config.showBefore) === 'function') {
  1874. _config.showBefore.call(_this, $modal);
  1875. }
  1876. };
  1877. _proto._showAfter = function () {
  1878. let _this = this, _config = _this._config, $modal = $(_this._element);
  1879. if (_config.showAfter && typeof (_config.showAfter) === 'function') {
  1880. _config.showAfter.call(_this, $modal);
  1881. }
  1882. };
  1883. _proto._shown = function () {
  1884. let _this = this, _config = _this._config, $modal = $(_this._element);
  1885. if (_config.shown && typeof (_config.shown) === 'function') {
  1886. _config.shown.call(_this, $modal);
  1887. }
  1888. };
  1889. _proto._bindEvent = function () {
  1890. let _this = this, _config = _this._config, $modal = $(_this._element);
  1891. $modal.off(`show.bs.modal${EVENT_KEY}`).on(`show.bs.modal${EVENT_KEY}`,
  1892. function () {
  1893. _this._draggable();
  1894. _this._showBefore();
  1895. if (_config.isInit) {
  1896. _this._init();
  1897. }
  1898. _this._initWangEditor();
  1899. _this._setData();
  1900. _this._setSelect2();
  1901. _this._setWangEditorData();
  1902. _this._bindSave();
  1903. $.formValidate($modal.find('form'), { noValid: true });
  1904. _this._showAfter();
  1905. });
  1906. $modal.off(`shown.bs.modal${EVENT_KEY}`).on(`shown.bs.modal${EVENT_KEY}`,
  1907. function () {
  1908. _this._shown();
  1909. });
  1910. };
  1911. _proto._bindSave = function () {
  1912. let _this = this, _config = _this._config, $modal = $(_this._element);
  1913. let $saveBtn = _config.saveBtn
  1914. ? $(_config.saveBtn)
  1915. : $modal.find(Selector.SAVE_BUTTON);
  1916. if (!$saveBtn.length) {
  1917. //throw new Error("未发现保存按钮");
  1918. debug_log("未发现保存按钮");
  1919. return;
  1920. }
  1921. let opt = _this._getSaveOptions(), ajaxSelectFun;
  1922. if (_config.ajaxSelect) {
  1923. ajaxSelectFun = function () {
  1924. $modal.find('select' + Selector.AJAX_SELECT).each(function () {
  1925. let $this = $(this);
  1926. let cKey = $this.data(ClassName.AJAX_SELECT_CODE),
  1927. val = $this.val(),
  1928. name = $this.find("option[value='" + val + "']").text(), ran = Math.floor(Math.random() * 9999);
  1929. debug_log('AjaxSelect[{3}]:{0}-{1}-{2}'.format(cKey, val, name, ran));
  1930. $.vbAjax41({
  1931. url: abp.appUrl + "Query/AddAcInfo",
  1932. data: {
  1933. CodeKey: cKey,
  1934. ValueKey: val,
  1935. NameKey: name
  1936. },
  1937. success: function () {
  1938. debug_log('AjaxSelect[{0}]:Success'.format(ran));
  1939. }
  1940. });
  1941. });
  1942. }
  1943. }
  1944. let save = null;
  1945. if (_config.save && typeof (_config.save) === "function") {
  1946. save = function () { _config.save(opt); };
  1947. } else if (_config.url) {
  1948. save = function () { $.vbAjax(_config.url, opt); };
  1949. }
  1950. let saveFun =
  1951. function () {
  1952. if (save && $.isFunction(save)) {
  1953. save();
  1954. }
  1955. if (ajaxSelectFun && $.isFunction(ajaxSelectFun)) {
  1956. ajaxSelectFun();
  1957. }
  1958. }
  1959. $saveBtn.off('click.save').on('click.save', saveFun);
  1960. $modal.find('.modal-body input').keydown(function (e) {
  1961. if (e.which === 13) {
  1962. if (e.target.tagName.toLocaleLowerCase() === "textarea") {
  1963. e.stopPropagation();
  1964. } else {
  1965. e.preventDefault();
  1966. saveFun.call(_this);
  1967. }
  1968. }
  1969. });
  1970. };
  1971. _proto._getSaveOptions = function () {
  1972. let _this = this, _config = _this._config, $modal = $(_this._element);
  1973. let $form = $modal.find('form');
  1974. if (!$form.length && _config.needForm) {
  1975. throw new Error("未发现表单");
  1976. }
  1977. return {
  1978. url: _config.url,
  1979. type: _config.type,
  1980. table: _config.table,
  1981. success: _config.success,
  1982. form: $form,
  1983. data: null,
  1984. dataFun: _config.dataFun,
  1985. isValidate: _config.fromValidate,
  1986. modal: _config.modal,
  1987. blockUI: true,
  1988. isRefresh: _config.isRefresh,
  1989. isAlert: _config.isAlert
  1990. };
  1991. };
  1992. _proto._show = function ($modal) {
  1993. let _this = this, _config = _this._config;
  1994. $modal.modal({ backdrop: _config.backdrop, keyboard: _config.keyboard });
  1995. $modal.modal('show');
  1996. };
  1997. _proto.open = function (opts, modal) {
  1998. let _this = this;
  1999. let $modal = _this._getModal(opts, modal);
  2000. _this._bindEvent();
  2001. _this._show($modal);
  2002. }
  2003. _proto.show = function (opts, modal) {
  2004. let _this = this;
  2005. let $modal = _this._getModal(opts, modal);
  2006. _this._bindEvent();
  2007. _this._config.isInit = false;
  2008. _this._show($modal);
  2009. };
  2010. _proto.hide = function () {
  2011. let _this = this, $modal = $(_this._element);
  2012. return $modal.modal('hide');
  2013. };
  2014. _proto.create = function (opts) {
  2015. let _this = this, _config = _this._config = $.extend({}, _this._config, opts);
  2016. if (!_config.modalId) {
  2017. if (_config.modal) {
  2018. _config.modalId = typeof (_config.modal) === 'string' ? _config.modal : $(_config.modal).attr('id');
  2019. } else {
  2020. _config.modalId = `modal_${Math.floor(Math.random() * 10000000)}`;
  2021. }
  2022. }
  2023. let dialogClass = _config.modalSize === null ?
  2024. _config.modalSize = "" :
  2025. _config.modalSize ?
  2026. _config.modalSize :
  2027. ClassName.MODAL_LG;
  2028. if (_config.dialogClass) {
  2029. dialogClass += _config.dialogClass;
  2030. }
  2031. let dialogStyle = _config.width ? `max-width:${_config.width}px;` : "";
  2032. if (_config.dialogStyle) {
  2033. dialogStyle += _config.dialogStyle;
  2034. }
  2035. let containerId = `modal-container_${_config.modalId}`;
  2036. if ($('#' + containerId).length) {
  2037. $('#' + containerId).remove();
  2038. }
  2039. let $container = $(`
  2040. <div id="${containerId}" class="${ClassName.CREATE_BOX}">
  2041. <div id="${_config.modalId}" class="modal fade ${_config.modalClass}">
  2042. <div class="${ClassName.MODAL_DIALOG} modal-dialog-centered modal-dialog-scrollable ${dialogClass}" style="${dialogStyle}">
  2043. <div class="${ClassName.MODAL_CONTENT}"></div>
  2044. </div>
  2045. </div>
  2046. </div>`);
  2047. let $modalContent = $container.find(Selector.MODAL_CONTENT);
  2048. if (_config.content) {
  2049. $modalContent.append(_config.content);
  2050. } else if (_config.modalBody) {
  2051. let modalHeader = _config.modalHeader != undefined
  2052. ? _config.modalHeader
  2053. : `<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">
  2054. <!--Svg Icon | path: icons/duotone/Navigation/Close.svg-->
  2055. <span class="svg-icon svg-icon-2x">
  2056. <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">
  2057. <g transform="translate(12.000000, 12.000000) rotate(-45.000000) translate(-12.000000, -12.000000) translate(4.000000, 4.000000)" fill="#000000">
  2058. <rect fill="#000000" x="0" y="7" width="16" height="2" rx="1"></rect>
  2059. <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>
  2060. </g>
  2061. </svg>
  2062. </span>
  2063. </div></div>`;
  2064. let modalBody = `<div class="${ClassName.MODAL_BODY} ${_config.modalBodyClass}">${_config.modalBody}</div>`;
  2065. let modalFooter = _config.modalFooter != undefined
  2066. ? _config.modalFooter
  2067. : `<div class="${ClassName.MODAL_FOOTER} py-2 ${_config.modalFooterClass ? _config.modalFooterClass : ""}" style="text-align: center;"><button
  2068. <button type="button" class="btn btn-sm btn-light me-5" data-bs-dismiss="modal">取消</button>
  2069. <button type="submit" class="btn btn-sm btn-primary ${ClassName.SAVE_BUTTON}">保存</button>
  2070. </div>`;
  2071. $modalContent.append(modalHeader);
  2072. $modalContent.append(modalBody);
  2073. $modalContent.append(modalFooter);
  2074. }
  2075. $('body').append($container);
  2076. if (!$(_this._element).hasClass(ClassName.MODAL)) {
  2077. _this._element = $('#' + _config.modalId)[0];
  2078. }
  2079. _this.show();
  2080. }
  2081. Modal._jQueryInterface = function _jQueryInterface(option) {
  2082. let value;
  2083. let data = $(this).data(DATA_KEY);
  2084. let args = Array.prototype.slice.call(arguments, 1);
  2085. let _options = $.extend(true, {}, Default, (typeof option == "string" ? {} : option) || {});
  2086. if (typeof option === 'string') {
  2087. if ($.inArray(option, ALLOW_METHOD) < 0) {
  2088. throw new Error("Unknown method: " + option);
  2089. }
  2090. if (!data) {
  2091. data = new Modal($(this), _options, option == "create");
  2092. }
  2093. value = data[option].apply(data, args);
  2094. } else {
  2095. if (!data) {
  2096. data = new Modal($(this), _options);
  2097. $(this).data(DATA_KEY, data);
  2098. }
  2099. data.open(_options);
  2100. }
  2101. return typeof value === 'undefined' ? this : value;
  2102. };
  2103. return Modal;
  2104. }();
  2105. /*
  2106. * jQuery API
  2107. * ====================================================
  2108. */
  2109. $.fn[NAME] = Modal._jQueryInterface;
  2110. $.fn[NAME].Constructor = Modal;
  2111. $.fn[NAME].noConflict = function () {
  2112. $.fn[NAME] = JQUERY_NO_CONFLICT;
  2113. return Modal._jQueryInterface;
  2114. };
  2115. }((jQuery));
  2116. let VbFile = function ($) {
  2117. const NAME = 'VbFile';
  2118. const DATA_KEY = 'vb.File';
  2119. const EVENT_KEY = "." + DATA_KEY;
  2120. const ClassName = {
  2121. FILE_URL: "vb-file-url",
  2122. FILE_TYPE: "vb-file-type",
  2123. MODAL_IMAGE: 'vb-image-modal',
  2124. MODAL_FILE: 'vb-file-modal',
  2125. IMAGE_URL_NAME: 'data-vb-image-url',
  2126. DOWNLOAD: 'download',
  2127. TEMPLINK: 'tempLink-fd',
  2128. TARGET_INFO: "vb-file-target-info",
  2129. TARGET_NAME: "vb-file-target-name",
  2130. TARGET_EXT: "vb-file-target-ext",
  2131. IS_IMAGE: "vb-file-image",
  2132. MAX_SIZE: "vb-file-max-size",
  2133. FILE_BOX: 'vb-file-box',
  2134. FILE_CLEAN_BTN: 'vb-file-btn="clean"',
  2135. VALID_CLASS: "valid",
  2136. INVALID_CLASS: "invalid",
  2137. INVALID_FEEDBACK: "invalid-feedback",
  2138. INVALID_FEEDBACK_SHOW: "invalid-feedback-show"
  2139. }
  2140. const Selector = {
  2141. FILE_UPLOAD: `[data-vb-file="upload"]`,
  2142. FILE_SHOW: `[data-vb-file="show"]`,
  2143. MODAL_IMAGE: `#${ClassName.MODAL_IMAGE}`,
  2144. MODAL_FILE: `#${ClassName.MODAL_FILE}`,
  2145. DOWNLOAD: `#${ClassName.DOWNLOAD}`,
  2146. TEMPLINK: `#${ClassName.TEMPLINK}`,
  2147. FILE_INPUT: 'input[type="file"]',
  2148. FILE_BOX: `[data-${ClassName.FILE_BOX}]`,
  2149. FILE_CLEAN_BTN: `[data-${ClassName.FILE_CLEAN_BTN}]`,
  2150. INVALID_FEEDBACK: `.${ClassName.INVALID_FEEDBACK}`
  2151. }
  2152. const JQUERY_NO_CONFLICT = $.fn[NAME];
  2153. const ALLOW_METHOD = [
  2154. 'show',
  2155. 'showImage',
  2156. 'showOffice',
  2157. 'showFile',
  2158. 'download',
  2159. 'upload',
  2160. 'cleanFile'
  2161. ];
  2162. const Default = {
  2163. url: undefined,
  2164. type: 'img',
  2165. maxSize: 2,
  2166. isImage: false,
  2167. targetInfo: undefined,
  2168. targetName: "fileName",
  2169. targetExt: "fileExt",
  2170. callback: undefined
  2171. }
  2172. let File = function () {
  2173. function File(element, config) {
  2174. this._element = element;
  2175. this._config = config;
  2176. }
  2177. let _proto = File.prototype;
  2178. _proto.show = function () {
  2179. let _this = this, _config = _this._config, _el = _this._element;
  2180. let config = {
  2181. url: _config.url ? _config.url : $(_el).data(ClassName.FILE_URL),
  2182. type: _config.type ? _config.type : $(_el).data(ClassName.FILE_TYPE)
  2183. };
  2184. if (!url) {
  2185. throw new Error("Need URL");
  2186. return;
  2187. }
  2188. switch (config.type.toLowerCase()) {
  2189. case 'img':
  2190. case 'image':
  2191. this.showImage(config.url);
  2192. break;
  2193. case 'office':
  2194. case 'doc':
  2195. case 'docx':
  2196. this.showOffice(config.url);
  2197. break;
  2198. default:
  2199. this.showFile(config.url);
  2200. return;
  2201. }
  2202. };
  2203. _proto.showImage = function (url, config) {
  2204. if (!url) {
  2205. return;
  2206. }
  2207. let _this = this;
  2208. $.metPageCss('/Libs/viewerjs/dist/viewer.min.css', "dy-css-viewer");
  2209. $.metPageJs('/Libs/viewerjs/dist/viewer.min.js', "dy-js-viewer");
  2210. let Viewer = window.Viewer;
  2211. if ($(Selector.MODAL_IMAGE).length > 0) {
  2212. $(Selector.MODAL_IMAGE).remove();
  2213. }
  2214. let urls = url.split(",");
  2215. let $ul = $(`<ul id="${ClassName.MODAL_IMAGE}" style="display:none"></ul>`);
  2216. for (let i = 0; i < urls.length; i++) {
  2217. $ul.append(`<li><img src="${urls[i]}" ${ClassName.IMAGE_URL_NAME}="{urls[i]}" /></li>`);
  2218. }
  2219. $ul.appendTo($('body'));
  2220. let $image = $(Selector.MODAL_IMAGE), imageView;
  2221. let options = $.extend({}, {
  2222. // inline: true,
  2223. url: ClassName.IMAGE_URL_NAME,
  2224. button: true,
  2225. navbar: urls.length > 1,
  2226. title: false,
  2227. toolbar: true,
  2228. ready: function (e) {
  2229. console.log(e.type);
  2230. },
  2231. show: function (e) {
  2232. console.log(e.type);
  2233. },
  2234. shown: function (e) {
  2235. console.log(e.type);
  2236. },
  2237. hide: function (e) {
  2238. console.log(e.type);
  2239. },
  2240. view: function (e) {
  2241. console.log(e.type);
  2242. },
  2243. viewed: function (e) {
  2244. console.log(e.type);
  2245. },
  2246. move: function (e) {
  2247. console.log(e.type);
  2248. },
  2249. moved: function (e) {
  2250. console.log(e.type);
  2251. },
  2252. hidden: function () {
  2253. imageView.destroy();
  2254. $image.remove();
  2255. }
  2256. }, _this._config, config || {}, { url: ClassName.IMAGE_URL_NAME });
  2257. imageView = new Viewer($image[0], options);
  2258. imageView.show();
  2259. //$image.viewer("show");
  2260. $image.css("display", "none");
  2261. };
  2262. _proto.showOffice = function (url, office_url) {
  2263. let _this = this;
  2264. url = (office_url || OFFICEURL) + window.location.host + url;
  2265. _this.showFile(url);
  2266. };
  2267. _proto.showFile = function (url) {
  2268. let _this = this;
  2269. $(document).VbModal('create',
  2270. {
  2271. modal: ClassName.MODAL_FILE,
  2272. title: '文件预览',
  2273. dialogStyle: "min-width: calc(100% - 600px);",
  2274. modalBody: `<div class="modal-body"><iframe src="${url}" width="100%"; style="min-height: calc(100vh - 300px);" frameborder="0"></iframe></div>`,
  2275. 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
  2276. " style="min-width: 100px;">下载文件</button></div>`,
  2277. showAfter: function () {
  2278. $(Selector.MODAL_FILE + " " + Selector.DOWNLOAD).off('click.download' + EVENT_KEY).on('click.download' + EVENT_KEY, function () { _this.download(url) });
  2279. }
  2280. });
  2281. };
  2282. _proto.download = function (url) {
  2283. let _this = this;
  2284. url = url || _this.config.url;
  2285. if ($(Selector.TEMPLINK).length > 0) {
  2286. $(Selector.TEMPLINK).remove();
  2287. }
  2288. $('body').append(`<a id="${ClassName.TEMPLINK}" href="${url}" target="_blank" style="display:none"></a>`);
  2289. $(Selector.TEMPLINK)[0].click();
  2290. $(Selector.TEMPLINK).remove();
  2291. };
  2292. _proto.upload = function () {
  2293. let _this = this, $this = $(_this._element), _config = _this._config, $file = _this._getFile();
  2294. 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);
  2295. if (targetInfo) {
  2296. _config.targetInfo = targetInfo;
  2297. }
  2298. if (targetName) {
  2299. _config.targetName = targetName;
  2300. }
  2301. if (targetExt) {
  2302. _config.targetExt = targetExt;
  2303. }
  2304. if (isImage === "true" || isImage === "1" || isImage === "y" || isImage === "Y" || isImage === "True") {
  2305. _config.isImage = true;
  2306. }
  2307. if (maxSize) {
  2308. _config.maxSize = maxSize;
  2309. }
  2310. $file.off('change' + EVENT_KEY).on('change' + EVENT_KEY, function () {
  2311. _this._fileCheck();
  2312. });
  2313. $file.removeClass(ClassName.INVALID_CLASS).removeClass(ClassName.VALID_CLASS);
  2314. $this.closest(Selector.FILE_BOX).parent().find(Selector.INVALID_FEEDBACK).empty().removeClass(ClassName.INVALID_FEEDBACK_SHOW);
  2315. $this.closest(Selector.FILE_BOX).find(Selector.FILE_CLEAN_BTN).off('click' + EVENT_KEY).on('click' + EVENT_KEY, () => { _this.cleanFile(); });
  2316. };
  2317. _proto.cleanFile = function () {
  2318. let _this = this, $this = $(_this._element);
  2319. let $file = _this._getFile();
  2320. let $fileBox = $this.closest(Selector.FILE_BOX);
  2321. $file.removeClass(ClassName.INVALID_CLASS).removeClass(ClassName.VALID_CLASS);
  2322. $this.closest(Selector.FILE_BOX).parent().find(Selector.INVALID_FEEDBACK).empty().removeClass(ClassName.INVALID_FEEDBACK_SHOW);
  2323. $fileBox.find('input').val('');
  2324. $file.after($file.clone().val(""));
  2325. $file.remove();
  2326. $fileBox.find(Selector.FILE_INPUT).off('change' + EVENT_KEY).on('change' + EVENT_KEY, () => { _this._fileCheck(); });
  2327. };
  2328. _proto._fileCheck = function () {
  2329. let _this = this, _config = _this._config;
  2330. let $file = _this._getFile();
  2331. if (_this._checkSize()) {
  2332. let fileName = $file.val().split("\\").pop();
  2333. //$this.closest(Selector.FILE_BOX).addClass(ClassName.FILE_SUCCESS).find("label").text(fileName);
  2334. let file = $file[0].files[0];
  2335. _this._readFile(file);
  2336. if (_config.targetName && _config.targetName !== undefined) {
  2337. let name = fileName.substring(0, fileName.lastIndexOf("."));
  2338. if (!_config.targetName)
  2339. return;
  2340. let targetName = _config.targetName.split(',');
  2341. for (let i = 0; i < targetName.length; i++) {
  2342. $(`[name="${targetName[i]}"]`).val(name);
  2343. }
  2344. }
  2345. if (_config.targetExt && _config.targetExt !== undefined) {
  2346. let ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
  2347. if (!_config.targetExt)
  2348. return;
  2349. let targetExt = _config.targetExt.split(',');
  2350. for (let j = 0; j < targetExt.length; j++) {
  2351. $(`[name="${targetExt[j]}"]`).val(ext);
  2352. }
  2353. }
  2354. let callback = _config.callback;
  2355. if (callback && typeof (callback) === "function") {
  2356. callback(fileName, file);
  2357. }
  2358. } else {
  2359. //let target = _config.targetInfo ? _config.targetInfo : $file.attr('id').replace('_file', '');
  2360. //$file.addClass(ClassName.INVALID_CLASS);
  2361. //$(`[name="${_config.targetInfo}"]`).closest(Selector.FILE_BOX).parent().find(Selector.INVALID_FEEDBACK).html(abp.localization.VberZero('SelectFile')).addClass(ClassName.INVALID_FEEDBACK_SHOW);
  2362. }
  2363. };
  2364. _proto._checkSize = function () {
  2365. let _this = this, _config = _this._config;
  2366. let $file = _this._getFile();
  2367. let maxsize = _config.maxSize * 1024 * 1024;
  2368. //let errMsg = "上传的附件文件不能超过" + _config.maxSize + "M。";
  2369. //let tipMsg = "您的浏览器暂不支持计算上传文件的大小,确保上传文件不要超过" + _config.maxSize + "M,建议使用IE、FireFox、Chrome浏览器。";
  2370. let errMsg = abp.localization.VberZero('FileUploadErrorMsg', _config.maxSize);
  2371. let tipMsg = abp.localization.VberZero('FileUploadTipMsg', _config.maxSize);
  2372. let browserCfg = {};
  2373. let ua = window.navigator.userAgent;
  2374. if (ua.indexOf("MSIE") >= 1) {
  2375. browserCfg.ie = true;
  2376. } else if (ua.indexOf("Firefox") >= 1) {
  2377. browserCfg.firefox = true;
  2378. } else if (ua.indexOf("Chrome") >= 1) {
  2379. browserCfg.chrome = true;
  2380. }
  2381. try {
  2382. let objFile = $file[0];
  2383. if (objFile.value === "") {
  2384. //layer.alert("请先选择上传文件", { icon: 7, title: "提示信息" });
  2385. return false;
  2386. }
  2387. let filesize;
  2388. if (browserCfg.firefox || browserCfg.chrome) {
  2389. filesize = objFile.files[0].size;
  2390. } else if (browserCfg.ie) {
  2391. let objImg = document.createElement("img");
  2392. objImg.id = "tempImg";
  2393. objImg.style.display = "none";
  2394. document.body.appendChild(objImg);
  2395. objImg.dynsrc = objFile.value;
  2396. filesize = objImg.fileSize;
  2397. } else {
  2398. _this.cleanFile();
  2399. abp.message.warn(tipMsg);
  2400. return false;
  2401. }
  2402. if (filesize === -1) {
  2403. _this.cleanFile();
  2404. abp.message.warn(tipMsg);
  2405. return false;
  2406. } else if (filesize > maxsize) {
  2407. _this.cleanFile();
  2408. abp.message.warn(errMsg);
  2409. return false;
  2410. } else {
  2411. return true;
  2412. }
  2413. } catch (e) {
  2414. _this.cleanFile();
  2415. abp.message.error(e);
  2416. return false;
  2417. }
  2418. };
  2419. _proto._readFile = function (file) {
  2420. let _this = this, _config = _this._config;
  2421. let $file = _this._getFile();
  2422. file = file || $file[0].files[0];
  2423. if (!file) {
  2424. return;
  2425. }
  2426. if (_config.isImage && !/image\/\w+/.test(file.type)) {
  2427. abp.message.warn(abp.localization.VberZero('FileUploadOnlyImage'));
  2428. _this.cleanFile();
  2429. return;
  2430. }
  2431. let reader = new FileReader();
  2432. reader.readAsDataURL(file);
  2433. reader.onload = function () {
  2434. let fileinfo = this.result.substring(this.result.indexOf(',') + 1);
  2435. //let target = _config.targetInfo ? _config.targetInfo : $file.attr('id').replace('_file', '');
  2436. $(`[name="${_config.targetInfo}"]`).val(fileinfo);
  2437. };
  2438. };
  2439. _proto._getFile = function () {
  2440. let _this = this, $this = $(_this._element);
  2441. let $file = $this.closest(Selector.FILE_BOX).find(Selector.FILE_INPUT);
  2442. return $file;
  2443. };
  2444. File._jQueryInterface = function _jQueryInterface(option) {
  2445. let value, args = Array.prototype.slice.call(arguments, 1);
  2446. this.each(function () {
  2447. let data = $(this).data(DATA_KEY);
  2448. let _options = $.extend({}, Default, $(this).data(), typeof option === 'object' && option || {});
  2449. if (!data) {
  2450. data = new File(this, _options);
  2451. $(this).data(DATA_KEY, data);
  2452. }
  2453. if (!option) {
  2454. value = data.show();
  2455. } else if (typeof option === 'string') {
  2456. if ($.inArray(option, ALLOW_METHOD) < 0) {
  2457. throw new Error("Unknown method: " + option);
  2458. }
  2459. value = data[option].apply(data, args);
  2460. }
  2461. });
  2462. return typeof value === 'undefined' ? this : value;
  2463. };
  2464. return File;
  2465. }();
  2466. $(window).on("load" + EVENT_KEY, function () {
  2467. $(Selector.FILE_UPLOAD).each(function () {
  2468. File._jQueryInterface.call($(this), "upload");
  2469. });
  2470. $(Selector.FILE_SHOW).each(function () {
  2471. File._jQueryInterface.call($(this), "show");
  2472. });
  2473. });
  2474. /*
  2475. * jQuery API
  2476. * ====================================================
  2477. */
  2478. $.fn[NAME] = File._jQueryInterface;
  2479. $.fn[NAME].Constructor = File;
  2480. $.fn[NAME].noConflict = function () {
  2481. $.fn[NAME] = JQUERY_NO_CONFLICT;
  2482. return File._jQueryInterface;
  2483. };
  2484. }((jQuery));
  2485. let VbDate = function ($) {
  2486. const NAME = 'VbDate';
  2487. const DATA_KEY = 'vb.date';
  2488. const EVENT_KEY = "." + DATA_KEY;
  2489. const ClassName = {
  2490. }
  2491. const Selector = {
  2492. DATE: `[data-vb-date="date"]`,
  2493. DATETIME: `[data-vb-date="date-time"]`,
  2494. RANGEDATE: `[data-vb-date="r_date"]`,
  2495. RANGEDATETIME: `[data-vb-date="r_date-time"]`,
  2496. }
  2497. const JQUERY_NO_CONFLICT = $.fn[NAME];
  2498. const ALLOW_METHOD = [
  2499. "load",
  2500. "date",
  2501. "dateTime",
  2502. "dateRange",
  2503. "dateTimeRange",
  2504. "setValue",
  2505. ];
  2506. const Default = {
  2507. //altInput: true,
  2508. //altFormat: "Y-m-d",
  2509. //allowInput: true,
  2510. time_24hr: true,
  2511. //wrap: true,//外部元素
  2512. //minDate: undefined,
  2513. //maxDate: undefined,
  2514. //minTime: undefined,
  2515. //maxTime: undefined,
  2516. //showMonths: 1,//显示的月份数
  2517. //mode: undefined,//single,multiple,range
  2518. //noCalendar: true,
  2519. //weekNumbers: false,//显示第多少周
  2520. //enableTime: false,
  2521. //hourIncrement: 1, //调整小时输入的步进(包括滚动)
  2522. //minuteIncrement: 5,//
  2523. //enableSeconds: false,
  2524. //defaultDate: undefined,// ["2025-01-05", "2025-01-10"]
  2525. //defaultHour: undefined,
  2526. //defaultMinute: undefined,
  2527. //dateFormat: "Y-m-d H:i",
  2528. //disable: undefined,//(disable 禁用日期, enable 禁用其余日期) ["2025-01-10", "22025-01-11"] [ { from: "2025-01-05", to: "2025-01-25" },{...}]
  2529. //inline: false,//始终打开状态显示日历
  2530. //position: "auto",
  2531. //preletrow: "<",//箭头图标的HTML,用于切换月份
  2532. //nextArrow: ">"
  2533. }
  2534. let Date = function () {
  2535. function Date(element, config) {
  2536. this._element = element;
  2537. this._config = config;
  2538. }
  2539. let _proto = Date.prototype;
  2540. _proto._getHtmlOption = function () {
  2541. let _this = this, data = $(_this._element).data();
  2542. let htmlOption = {};
  2543. //htmlOption.mode = data.mode;
  2544. htmlOption.defaultDate = data.dateDefaultDate;
  2545. htmlOption.defaultHour = data.dateDefaultHour;
  2546. htmlOption.defaultMinute = data.dateDefaultMinute;
  2547. htmlOption.minDate = data.dateMinDate;
  2548. htmlOption.maxDate = data.dateMaxDate;
  2549. htmlOption.minTime = data.dateMinTime;
  2550. htmlOption.maxTime = data.dateMaxTime;
  2551. //htmlOption.enableTime = data.dateEnableTime;
  2552. htmlOption.dateFormat = data.dateFormat;
  2553. htmlOption.disable = data.dateDisable;
  2554. htmlOption.noCalendar = data.dateNoCalendar;
  2555. htmlOption.inline = data.dateInline;
  2556. htmlOption.showMonths = data.dateShowMonths;
  2557. htmlOption.hourIncrement = data.dateHourIncrement;
  2558. htmlOption.minuteIncrement = data.dateMinuteIncrement;
  2559. htmlOption.enableSeconds = data.dateEnableSeconds;
  2560. return htmlOption;
  2561. };
  2562. _proto._extendOption = function (options) {
  2563. let _this = this, _config = _this._config;
  2564. let opt = $.extend(true, {}, _config, options || {});
  2565. if (opt.noCalendar) {
  2566. opt.enableTime = true;
  2567. opt.dateFormat = "H:i";
  2568. }
  2569. if (!opt.dateFormat) {
  2570. opt.dateFormat = opt.noCalendar ? "" : "Y-m-d";
  2571. if (opt.enableTime) {
  2572. opt.dateFormat = opt.dateFormat ? `${opt.dateFormat} H:i` : "H:i";
  2573. }
  2574. }
  2575. opt.locale = window.lang == "zh-CN" ? "zh" : window.lang;
  2576. _config = opt;
  2577. return opt;
  2578. };
  2579. _proto.date = function (options) {
  2580. let _this = this;
  2581. let opt = $.extend(true, {}, _this._getHtmlOption(), options || {});
  2582. opt.mode = "single";
  2583. opt.enableTime = false;
  2584. opt.dateFormat = "Y-m-d";
  2585. _this.load(opt);
  2586. };
  2587. _proto.dateRange = function (options) {
  2588. let _this = this;
  2589. let opt = $.extend(true, {}, _this._getHtmlOption(), options || {});
  2590. opt.enableTime = false;
  2591. opt.dateFormat = "Y-m-d";
  2592. opt.mode = "range";
  2593. _this.load(opt);
  2594. };
  2595. _proto.dateTime = function (options) {
  2596. let _this = this;
  2597. let opt = $.extend(true, {}, _this._getHtmlOption(), options || {});
  2598. opt.enableTime = true;
  2599. opt.dateFormat = "Y-m-d H:i";
  2600. opt.mode = "single";
  2601. _this.load(opt);
  2602. };
  2603. _proto.dateTimeRange = function (options) {
  2604. let _this = this;
  2605. let opt = $.extend(true, {}, _this._getHtmlOption(), options || {});
  2606. opt.enableTime = true;
  2607. opt.dateFormat = "Y-m-d H:i";
  2608. opt.mode = "range";
  2609. _this.load(opt);
  2610. };
  2611. _proto.load = function (options) {
  2612. let _this = this, _config = _this._config, _el = _this._element;
  2613. let opt = options || _this._getHtmlOption();
  2614. let option = _this._extendOption(opt)
  2615. debug_log("DateTime:", $(_el).attr('name'), option);
  2616. _config.vbDate = $(_el).flatpickr(option);
  2617. }
  2618. _proto.setValue = function (value) {
  2619. let _this = this, _config = _this._config;
  2620. let format = _config.noCalendar ? "Y-m-d H:i" : _config.dateFormat;
  2621. _config.vbDate.setDate(value, true, format);
  2622. debug_log("date_setValue", value, format, $(_this._el).val());
  2623. }
  2624. Date._jQueryInterface = function _jQueryInterface(option) {
  2625. let value, args = Array.prototype.slice.call(arguments, 1);
  2626. this.each(function () {
  2627. let data = $(this).data(DATA_KEY);
  2628. let _options = $.extend({}, Default, $(this).data(), typeof option === 'object' && option || {});
  2629. if (!data) {
  2630. data = new Date(this, _options);
  2631. $(this).data(DATA_KEY, data);
  2632. }
  2633. if (!option) {
  2634. value = data.load();
  2635. } else if (typeof option === 'string') {
  2636. if ($.inArray(option, ALLOW_METHOD) < 0) {
  2637. throw new Error("Unknown method: " + option);
  2638. }
  2639. value = data[option].apply(data, args);
  2640. }
  2641. });
  2642. return typeof value === 'undefined' ? this : value;
  2643. };
  2644. return Date;
  2645. }();
  2646. $(window).on("load" + EVENT_KEY, function () {
  2647. $(Selector.DATE).each(function () {
  2648. Date._jQueryInterface.call($(this), "date");
  2649. });
  2650. $(Selector.DATETIME).each(function () {
  2651. Date._jQueryInterface.call($(this), "dateTime");
  2652. });
  2653. $(Selector.RANGEDATE).each(function () {
  2654. Date._jQueryInterface.call($(this), "dateRange");
  2655. });
  2656. $(Selector.RANGEDATETIME).each(function () {
  2657. Date._jQueryInterface.call($(this), "dateTimeRange");
  2658. });
  2659. });
  2660. /*
  2661. * jQuery API
  2662. * ====================================================
  2663. */
  2664. $.fn[NAME] = Date._jQueryInterface;
  2665. $.fn[NAME].Constructor = Date;
  2666. $.fn[NAME].noConflict = function () {
  2667. $.fn[NAME] = JQUERY_NO_CONFLICT;
  2668. return Date._jQueryInterface;
  2669. };
  2670. }((jQuery));
  2671. let VbTreeView = function ($) {
  2672. let NAME = 'VbTreeView';
  2673. let DATA_KEY = 'vb.tree_view';
  2674. //let EVENT_KEY = "." + DATA_KEY;
  2675. //let Selector = {
  2676. //}
  2677. //let ClassName = {
  2678. //}
  2679. let JQUERY_NO_CONFLICT = $.fn[NAME];
  2680. let Default = {
  2681. url: undefined,
  2682. data: undefined,
  2683. levels: 2,
  2684. showCheckbox: false,
  2685. checkedIcon: 'far fa-check-square',
  2686. uncheckedIcon: 'far fa-square',
  2687. emptyIcon: 'fas fa-square',
  2688. collapseIcon: 'fas fa-minus-square',
  2689. expandIcon: 'fas fa-plus-square',
  2690. color: '',
  2691. selectedBackColor: '',
  2692. selectedColor: '',
  2693. table: 'table',
  2694. selectFiledName: 'id',
  2695. selectFiledInput: 'keyWords'
  2696. }
  2697. let ALLOW_METHOD = [
  2698. 'init'
  2699. ];
  2700. //[
  2701. // {
  2702. // id: "1",
  2703. // text: "Parent 1",
  2704. // nodes: [
  2705. // {
  2706. // id: "1-1",
  2707. // text: "Child 1",
  2708. // nodes: [
  2709. // {
  2710. // id: "1-1-1",
  2711. // text: "Grandchild 1"
  2712. // },
  2713. // {
  2714. // id: "1-1-2",
  2715. // text: "Grandchild 2"
  2716. // }
  2717. // ]
  2718. // },
  2719. // {
  2720. // id: "1-2",
  2721. // text: "Child 2"
  2722. // }
  2723. // ]
  2724. // },
  2725. // {
  2726. // id: "2",
  2727. // text: "Parent 2"
  2728. // }
  2729. //];
  2730. let TreeView = function () {
  2731. function TreeView(element, config) {
  2732. this._element = element;
  2733. this._config = config;
  2734. this.init();
  2735. }
  2736. // Public
  2737. let _proto = TreeView.prototype;
  2738. _proto.init = function () {
  2739. let _this = this, _config = _this._config;
  2740. $.metPageCss('/Libs/bootstrap-treeview/dist/bootstrap-treeview.min.css', "dy-css-treeview");
  2741. $.metPageJs('/Libs/bootstrap-treeview/dist/bootstrap-treeview.min.js', "dy-js-treeview");
  2742. _config.onNodeSelected = _config.onNodeSelected && typeof _config.onNodeSelected == 'function' ?
  2743. function (e, data) { _config.onNodeSelected.call(_this, e, data); } : _this._onNodeSelected;
  2744. _config.onNodeUnselected = _config.onNodeUnselected && typeof _config.onNodeUnselected == 'function' ?
  2745. function (e, data) { _config.onNodeUnselected.call(_this, e, data); } : _this._onNodeUnselected;
  2746. if (_config.data) {
  2747. _this.loadTree();
  2748. } else if (_config.url) {
  2749. _this.postData();
  2750. }
  2751. };
  2752. _proto._onNodeSelected = function (e, data) {
  2753. let _this = this, _config = _this._config;
  2754. if (!data || !data[_config.selectFiledName]) {
  2755. return;
  2756. }
  2757. let $input = (typeof (_config.selectFiledInput) === 'string' ? $('#' + _config.selectFiledInput) : $(_config.selectFiledInput));
  2758. let tempId = data[_config.selectFiledName];
  2759. $input.val(tempId);
  2760. let $table = (typeof (_config.table) === 'string' ? $('#' + _config.table) : $(_config.table));
  2761. $table.VbTable('refresh', true);
  2762. };
  2763. _proto._onNodeUnselected = function () {
  2764. let _this = this, _config = _this._config;
  2765. let $input = (typeof (_config.selectFiledInput) === 'string' ? $('#' + _config.selectFiledInput) : $(_config.selectFiledInput));
  2766. $input.val('');
  2767. let $table = (typeof (_config.table) === 'string' ? $('#' + _config.table) : $(_config.table));
  2768. $table.VbTable('refresh', true);
  2769. };
  2770. _proto.loadTree = function (data) {
  2771. let _this = this;
  2772. let option = $.extend({}, _this._config);
  2773. if (data) {
  2774. option.data = data;
  2775. }
  2776. $(_this._element).treeview(option);
  2777. };
  2778. _proto.postData = function (url) {
  2779. let _this = this;
  2780. url = url || _this._config.url;
  2781. $.vbAjax({
  2782. url: window.appUrl + url,
  2783. isAlert: false,
  2784. isValidate: false,
  2785. isRefresh: false,
  2786. success: function (res) {
  2787. if (res) {
  2788. _this.loadTree(res);
  2789. }
  2790. }
  2791. });
  2792. };
  2793. TreeView._jQueryInterface = function _jQueryInterface(option) {
  2794. let value, args = Array.prototype.slice.call(arguments, 1);
  2795. this.each(function () {
  2796. let data = $(this).data(DATA_KEY);
  2797. let _options = $.extend({}, Default, $(this).data(), typeof option === 'object' && option);
  2798. if (!data) {
  2799. data = new TreeView(this, _options);
  2800. $(this).data(DATA_KEY, data);
  2801. }
  2802. if (typeof option === 'string') {
  2803. if ($.inArray(option, ALLOW_METHOD) < 0) {
  2804. throw new Error("Unknown method: " + option);
  2805. }
  2806. value = data[option].apply(data, args);
  2807. }
  2808. });
  2809. return typeof value === 'undefined' ? this : value;
  2810. };
  2811. return TreeView;
  2812. }();
  2813. /**
  2814. * jQuery API
  2815. * ====================================================
  2816. */
  2817. $.fn[NAME] = TreeView._jQueryInterface;
  2818. $.fn[NAME].Constructor = TreeView;
  2819. $.fn[NAME].noConflict = function () {
  2820. $.fn[NAME] = JQUERY_NO_CONFLICT;
  2821. return TreeView._jQueryInterface;
  2822. };
  2823. return TreeView;
  2824. }(jQuery);
  2825. let VbWangEditor = function ($) {
  2826. const NAME = 'VbWangEditor';
  2827. const DATA_KEY = 'vb.wang_editor';
  2828. const EVENT_KEY = "." + DATA_KEY;
  2829. const Selector = {
  2830. WANG_EDITOR: '[data-vb-editor="wang"]',
  2831. INPUT: '<input class="vb-wang-editor" name="{0}" type="hidden" />'
  2832. }
  2833. const Event = {
  2834. CHANGE: "change" + EVENT_KEY,
  2835. LOAD_DATA_API: "load" + EVENT_KEY
  2836. };
  2837. const JQUERY_NO_CONFLICT = $.fn[NAME];
  2838. const Default = {
  2839. name: undefined,
  2840. showFullScreen: true,
  2841. menus: undefined, excludeMenus: undefined,
  2842. colors: undefined,
  2843. /*[
  2844. '#000000',
  2845. '#eeece0',
  2846. '#1c487f',
  2847. '#4d80bf'
  2848. ],*/
  2849. fontNames: undefined,
  2850. /*[
  2851. '黑体',
  2852. '仿宋',
  2853. '楷体',
  2854. '标楷体',
  2855. '华文仿宋',
  2856. '华文楷体',
  2857. '宋体',
  2858. '微软雅黑',
  2859. 'Arial',
  2860. 'Tahoma',
  2861. 'Verdana',
  2862. 'Times New Roman',
  2863. 'Courier New',
  2864. ],*/
  2865. lineHeights: undefined,
  2866. //['1', '1.15', '1.6', '2', '2.5', '3'],
  2867. pasteFilterStyle: false, //粘贴样式的过滤
  2868. pasteIgnoreImg: true, //来忽略粘贴的图片
  2869. pasteTextHandle: undefined, // 对粘贴的文本进行处理,然后返回处理后的结果
  2870. onchange: undefined,
  2871. onblur: function () {
  2872. },
  2873. onfocus: function () {
  2874. //debug_log(ss);
  2875. },
  2876. linkImgCallback: undefined, // 插入网络图片的回调
  2877. onlineVideoCallback: undefined, // 自定义检查插入视频的回调
  2878. uploadImgServer: "", // 配置 server 接口地址
  2879. uploadImgMaxSize: 2 * 1024 * 1024, //限制大小 2M
  2880. uploadImgAccept: ['jpg', 'jpeg', 'png', 'gif', 'bmp'], //限制类型
  2881. uploadFileName: undefined, //自定义 fileName
  2882. uploadImgHeaders: undefined, //自定义 header
  2883. withCredentials: false, //跨域传递 cookie
  2884. customUploadImg: undefined, //自己实现上传图片
  2885. /*
  2886. function (resultFiles, insertImgFn) {
  2887. // resultFiles 是 input 中选中的文件列表
  2888. // insertImgFn 是获取图片 url 后,插入到编辑器的方法
  2889. // 上传图片,返回结果,将图片插入到编辑器中
  2890. insertImgFn(imgUrl)
  2891. }
  2892. */
  2893. uploadImgTimeout: 5 * 1000, //自定义 timeout 时间
  2894. uploadImgParams: undefined, //自定义上传参数
  2895. uploadImgHooks: undefined, //回调函数
  2896. /*
  2897. {
  2898. // 上传图片之前
  2899. before: function(xhr) {
  2900. console.log(xhr)
  2901. // 可阻止图片上传
  2902. return {
  2903. prevent: true,
  2904. msg: '需要提示给用户的错误信息'
  2905. }
  2906. },
  2907. // 图片上传并返回了结果,图片插入已成功
  2908. success: function(xhr) {
  2909. console.log('success', xhr)
  2910. },
  2911. // 图片上传并返回了结果,但图片插入时出错了
  2912. fail: function(xhr, editor, resData) {
  2913. console.log('fail', resData)
  2914. },
  2915. // 上传图片出错,一般为 http 请求的错误
  2916. error: function(xhr, editor, resData) {
  2917. console.log('error', xhr, resData)
  2918. },
  2919. // 上传图片超时
  2920. timeout: function(xhr) {
  2921. console.log('timeout')
  2922. },
  2923. // 图片上传并返回了结果,想要自己把图片插入到编辑器中
  2924. // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式,可使用 customInsert
  2925. customInsert: function(insertImgFn, result) {
  2926. // result 即服务端返回的接口
  2927. console.log('customInsert', result)
  2928. // insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可
  2929. insertImgFn(result.data[0])
  2930. }
  2931. }
  2932. */
  2933. uploadImgMaxLength: 5, // 一次最多上传 5 个图片,
  2934. uploadImgShowBase64: true, // 可使用 base64 格式保存图片
  2935. showLinkImg: false
  2936. }
  2937. window.editor_W = {};
  2938. let E, editor = undefined;
  2939. let WangEditor = function () {
  2940. function WangEditor(element, config) {
  2941. this._element = element;
  2942. this._config = config;
  2943. $.metPageJs('/libs/wangEditor/dist/wangEditor.min.js', "dy-js-wangEditor");
  2944. E = window.wangEditor;
  2945. //this._init();
  2946. }
  2947. // Public
  2948. let _proto = WangEditor.prototype;
  2949. _proto._init = function (options) {
  2950. let _this = this, $this = $(_this._element);
  2951. options = options || {};
  2952. editor = new E(_this._element);
  2953. $this.form = $this.closest('form');
  2954. _this.createEditor(options);
  2955. }
  2956. _proto.createEditor = function (options) {
  2957. let _this = this;
  2958. let $this = $(_this._element);
  2959. options = options || {};
  2960. let _config = $.extend(true, {}, _this._config, options);
  2961. let name = _config.name || $this.data('editorName');
  2962. if (!name) {
  2963. throw new Error("请配置【name】");
  2964. }
  2965. let $Input = $this.parent().find($('#' + name));
  2966. $Input = $Input.length > 0 ? $Input : $(Selector.INPUT.format(name));
  2967. $Input.off(Event.CHANGE).on(Event.CHANGE, function () {
  2968. $this.setContent($Input.val());
  2969. });
  2970. $this.before($Input.val(""));
  2971. _config.onchange = function (html) {
  2972. // 监控变化,同步更新到 input
  2973. $Input.val(html);
  2974. }
  2975. if (!_config.excludeMenus) {
  2976. let menuStr = $this.data('editorMenu');
  2977. let menu = menuStr ? menuStr.split(',') : undefined;
  2978. if (menu) {
  2979. editor.config.menus = menu;
  2980. }
  2981. }
  2982. let opt = $this.data('editorOption');
  2983. if (!(typeof (opt) === "object" && Object.prototype.toString.call(opt).toLowerCase() === "[object object]")) {
  2984. try {
  2985. opt = opt ? JSON.parse(opt) : {};
  2986. } catch (e) {
  2987. console.log(e);
  2988. opt = {};
  2989. }
  2990. }
  2991. editor.config = $.extend({}, editor.config, _config, opt || {});
  2992. if (editor.config.excludeMenus) {
  2993. editor.config.excludeMenus = _config.excludeMenus;
  2994. }
  2995. if (!editor.config.excludeMenus && _config.menus && $.isArray(_config.menus)) {
  2996. editor.config.menus = _config.menus;
  2997. }
  2998. if (_config.colors && $.isArray(_config.colors)) {
  2999. editor.config.colors = _config.colors;
  3000. }
  3001. if (_config.fontNames && $.isArray(_config.fontNames)) {
  3002. editor.config.fontNames = _config.fontNames;
  3003. }
  3004. if (_config.lineHeights && $.isArray(_config.lineHeights)) {
  3005. editor.config.lineHeights = _config.lineHeights;
  3006. }
  3007. debug_log("WangEditor_option:", editor.config);
  3008. editor.create();
  3009. }
  3010. _proto.setContent = function (txt) {
  3011. editor.txt.html(txt);
  3012. }
  3013. WangEditor._jQueryInterface = function _jQueryInterface(option) {
  3014. let value, args = Array.prototype.slice.call(arguments, 1);
  3015. this.each(function () {
  3016. let data = $(this).data(DATA_KEY);
  3017. let _options = $.extend({}, Default, $(this).data(), typeof option === 'object' && option);
  3018. if (!data) {
  3019. data = new WangEditor(this, _options);
  3020. $(this).data(DATA_KEY, data);
  3021. }
  3022. if (typeof option === 'string') {
  3023. if (data[option] === 'undefined') {
  3024. throw new Error("Unknown method: " + option);
  3025. }
  3026. value = data[option].apply(data, args);
  3027. } else {
  3028. data['_init'].apply(data, args);
  3029. }
  3030. });
  3031. return typeof value === 'undefined' ? this : value;
  3032. };
  3033. return WangEditor;
  3034. }();
  3035. $(window).on("load" + EVENT_KEY, function () {
  3036. $("div" + Selector.WANG_EDITOR).each(function () {
  3037. WangEditor._jQueryInterface.call($(this));
  3038. });
  3039. });
  3040. /**
  3041. * jQuery API
  3042. * ====================================================
  3043. */
  3044. $.fn[NAME] = WangEditor._jQueryInterface;
  3045. $.fn[NAME].Constructor = WangEditor;
  3046. $.fn[NAME].noConflict = function () {
  3047. $.fn[NAME] = JQUERY_NO_CONFLICT;
  3048. return WangEditor._jQueryInterface;
  3049. };
  3050. return WangEditor;
  3051. }(jQuery);
  3052. exports.vbTable = VbTable;
  3053. exports.vbModal = VbModal;
  3054. exports.vbFile = VbFile;
  3055. exports.vbDate = VbDate;
  3056. exports.vbTreeView = VbTreeView;
  3057. exports.vbWangEditor = VbWangEditor;
  3058. Object.defineProperty(exports, '__esModule', { value: true });
  3059. })));
  3060. String.prototype.format = function (args) {
  3061. let result = this;
  3062. if (arguments.length > 0) {
  3063. let reg;
  3064. if (arguments.length === 1 && typeof args === "object") {
  3065. for (let key in args) {
  3066. if (args.hasOwnProperty(key)) {
  3067. if (args[key] !== undefined) {
  3068. reg = new RegExp("({" + key + "})", "g");
  3069. result = result.replace(reg, args[key]);
  3070. }
  3071. }
  3072. }
  3073. } else {
  3074. for (let i = 0; i < arguments.length; i++) {
  3075. if (arguments[i] !== undefined) {
  3076. reg = new RegExp("({[" + i + "]})", "g");
  3077. result = result.replace(reg, arguments[i]);
  3078. }
  3079. }
  3080. }
  3081. }
  3082. return result;
  3083. };
  3084. Date.prototype.format = function (fmt) {
  3085. let o = {
  3086. "M+": this.getMonth() + 1, //月份
  3087. "d+": this.getDate(), //日
  3088. "h+": this.getHours(), //小时
  3089. "m+": this.getMinutes(), //分
  3090. "s+": this.getSeconds(), //秒
  3091. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  3092. "S": this.getMilliseconds() //毫秒
  3093. };
  3094. if (/(y+)/.test(fmt))
  3095. fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  3096. for (let k in o) {
  3097. if (o.hasOwnProperty(k))
  3098. if (new RegExp("(" + k + ")").test(fmt))
  3099. fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  3100. }
  3101. return fmt;
  3102. };
  3103. Date.prototype.diff = function (diffType, endTime, startTime) {
  3104. diffType = diffType.toLowerCase();
  3105. let sTime = startTime ? (typeof startTime === 'string' ? new Date(startTime) : startTime) : this; //开始时间
  3106. let eTime = typeof endTime === 'string' ? new Date(endTime) : endTime; //结束时间
  3107. //作为除数的数字
  3108. let divNum = 1;
  3109. switch (diffType) {
  3110. case "second":
  3111. case "s":
  3112. divNum = 1000;
  3113. break;
  3114. case "minute":
  3115. case "m":
  3116. divNum = 1000 * 60;
  3117. break;
  3118. case "hour":
  3119. case "h":
  3120. divNum = 1000 * 3600;
  3121. break;
  3122. case "day":
  3123. case "d":
  3124. divNum = 1000 * 3600 * 24;
  3125. break;
  3126. default:
  3127. break;
  3128. }
  3129. return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
  3130. };
  3131. var funs;
  3132. function LoadTable(option, backFuns) {
  3133. if (!option) {
  3134. option = { table: "table" };
  3135. }
  3136. option.table = option.table ? option.table : "table";
  3137. let $table = typeof option.table === 'string' ? $('#' + option.table) : $(option.table);
  3138. if ($table.length < 1) {
  3139. throw new Error("没有发现表格" + option.table);
  3140. }
  3141. $table.VbTable(option);
  3142. backFuns = backFuns == undefined ? true : backFuns;
  3143. if (backFuns) {
  3144. return GetTableFuns($table);
  3145. }
  3146. window.funs = GetTableFuns($table);
  3147. return $table;
  3148. }
  3149. function GetTableFuns(table) {
  3150. let $table = typeof table === 'string' ? $('#' + table) : $(table);
  3151. return $table.VbTable('getToolFunctions');
  3152. }
  3153. function GetSelections(table) {
  3154. let $table = typeof table === 'string' ? $('#' + table) : $(table);
  3155. return $table.VbTable("getSelections");
  3156. }
  3157. function RefreshTable(table, isForce) {
  3158. table = table || "table";
  3159. isForce = isForce === undefined;
  3160. let $table = typeof table === 'string' ? $('#' + table) : $(table);
  3161. if ($table.length < 1) {
  3162. console.log('没有发现表格:', table);
  3163. }
  3164. try {
  3165. $table.VbTable('refresh', isForce);
  3166. } catch (e) {
  3167. debug_log("RefreshTable", e);
  3168. }
  3169. }
  3170. function BtnCreate(option) {
  3171. option = option || {};
  3172. option.table = option.table ? option.table : "table";
  3173. let $table = typeof option.table === 'string' ? $('#' + option.table) : $(option.table);
  3174. 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');
  3175. option.type = 'post';
  3176. $table.VbTable('create', url, option);
  3177. }
  3178. function BtnUpdate(option, row) {
  3179. option = option || {};
  3180. option.table = option.table ? option.table : "table";
  3181. let $table = typeof option.table === 'string' ? $('#' + option.table) : $(option.table);
  3182. let url = option.url || $table.closest('.table-box').find('[data-vb-tool-menu-type="btnUpdate"]').data('vb-tool-menu-url');
  3183. row = row || option.row || $table.VbTable("getSelection");
  3184. option.data = option.data || row;
  3185. option.type = 'post';
  3186. $table.VbTable('update', url, option, row);
  3187. }
  3188. function BtnDelete(option, row) {
  3189. option = option || {};
  3190. option.table = option.table ? option.table : "table";
  3191. let $table = typeof option.table === 'string' ? $('#' + option.table) : $(option.table);
  3192. let url = option.url || $table.closest('.table-box').find('[data-vb-tool-menu-type="btnDelete"]').data('vb-tool-menu-url');
  3193. row = row || option.row || $table.VbTable("getSelection");
  3194. option.type = 'post';
  3195. $table.VbTable('delete', url, option, row);
  3196. }
  3197. function BtnConfirm(message, title, url, rowOrTableId, data) {
  3198. let row, $table;
  3199. if (!data) {
  3200. if (rowOrTableId) {
  3201. if (typeof rowOrTableId === 'object' && !(rowOrTableId instanceof jQuery)) {
  3202. row = rowOrTableId;
  3203. } else {
  3204. $table = typeof rowOrTableId === 'string' ? $('#' + rowOrTableId) : $(rowOrTableId);
  3205. row = $table.bootstrapTable("getSelections")[0];
  3206. }
  3207. } else {
  3208. row = $("#table").bootstrapTable("getSelections")[0];
  3209. }
  3210. if (row) {
  3211. data = { Id: row.id };
  3212. }
  3213. } else {
  3214. $table = typeof rowOrTableId === 'string' ? $('#' + rowOrTableId) : $(rowOrTableId);
  3215. }
  3216. if (data) {
  3217. MsgConfirm(message, title, function () {
  3218. $.vbAjax1({ url: url, data: data, table: $table });
  3219. });
  3220. } else
  3221. abp.message.warn(abp.localization.iwbZero('SelectRecordOperation'));
  3222. }
  3223. function MsgConfirm(message, title, callback, opt) {
  3224. abp.message.confirm(message, title, function (isConfirmed) {
  3225. if (isConfirmed && callback) {
  3226. callback(opt);
  3227. }
  3228. });
  3229. }
  3230. function OpenModal(opt) {
  3231. opt = opt || {};
  3232. let ele = opt.modal ? opt.modal : "modal";
  3233. let $modal = typeof ele === 'string' ? $('#' + ele) : $(ele);
  3234. if ($modal.length < 1) {
  3235. console.log('没有发现模态框:', ele);
  3236. }
  3237. try {
  3238. $modal.VbModal(opt);
  3239. } catch (e) {
  3240. debug_log("OpenModal", e);
  3241. }
  3242. }
  3243. function ShowModal(ele) {
  3244. ele = ele || "modal";
  3245. let $modal = typeof ele === 'string' ? $('#' + ele) : $(ele);
  3246. if ($modal.length < 1) {
  3247. console.log('没有发现模态框:', ele);
  3248. }
  3249. try {
  3250. $modal.VbModal('show');
  3251. } catch (e) {
  3252. debug_log("ShowModal", e);
  3253. }
  3254. }
  3255. let queryModalTarget = '';
  3256. function ShowQueryModal(ele, target) {
  3257. ele = ele || "modal";
  3258. queryModalTarget = !target ? '' : target.indexOf('.') === 0 ? target : target.indexOf('#') === 0 ? target : '#' + target;
  3259. let $modal = typeof ele === 'string' ? $('#' + ele) : $(ele);
  3260. if ($modal.length < 1) {
  3261. console.log('没有发现模态框:', ele);
  3262. }
  3263. try {
  3264. let modalId = $modal.attr("id");//, treeField = $modal.data('search-tree-field'), searchBindFunc = `SearchList_${modalId}` //$modal.data('search-bind-func');
  3265. let _shown = function () {
  3266. let show = `${modalId}Search`;
  3267. if (show && window[show] && typeof window[show] == "function") {
  3268. window[show].call();
  3269. }
  3270. }
  3271. $modal.VbModal('show', {
  3272. shown: _shown,
  3273. needForm: false
  3274. });
  3275. } catch (e) {
  3276. debug_log("ShowModal", e);
  3277. }
  3278. }
  3279. function ClearSearchValue(target, clear, that) {
  3280. let $target = $(!target ? $(that) : target.indexOf('.') === 0 ? target : target.indexOf('#') === 0 ? target : '#' + target);
  3281. let arr = clear.split(",");
  3282. arr.forEach(function (v) {
  3283. if (v) {
  3284. let vStr = v.indexOf('.') === 0 ? v : v.indexOf('#') === 0 ? v : '#' + v;
  3285. let $t = $target.find(vStr);
  3286. $t.val('');
  3287. if ($t.is("select")) {
  3288. $t.trigger('change');
  3289. }
  3290. }
  3291. });
  3292. }
  3293. function ChangAjaxSelectValue($this, val, name) {
  3294. if (name && val) {
  3295. let option = new Option(name, val);
  3296. $this.html(option).trigger('change');
  3297. } else if (val) {
  3298. let key = $this.data('param-key');
  3299. $.vbAjax41({
  3300. url: abp.appUrl + "Query/AcInfo",
  3301. data: {
  3302. CodeKey: key,
  3303. ValueKey: val
  3304. },
  3305. success: function (res) {
  3306. if (res) {
  3307. let option = new Option(res.nameKey, res.valueKey);
  3308. $this.html(option).trigger('change');
  3309. }
  3310. }
  3311. });
  3312. }
  3313. }
  3314. function AddDynamicBox(that) {
  3315. let $that = $(that).closest('.vb-dynamic-box'), html = $that.clone().prop("outerHTML");
  3316. html = html.replace('btn-add', 'btn-delete');
  3317. html = html.replace('AddDynamicBox()', `$(this).closest('.vb-dynamic-box').remove();`);
  3318. html = html.replace('>增加</button', '>删除</button');
  3319. html = html.replace(new RegExp('data-select2-id="*"', "g"), '');
  3320. let $html = $(html).addClass('vb-dynamic-box-delete').removeAttr('data-select2-id');
  3321. $html.find('.select2').remove();
  3322. $html.find('select').removeAttr("id").val('');
  3323. $html.find('select:not(.tree)').select2();
  3324. $html.find('select.tree').select2tree();
  3325. $html.find('input').val('');
  3326. $that.parent().append($html);
  3327. return $html;
  3328. }
  3329. function DateFormatter(v) {
  3330. if (!v) {
  3331. return "";
  3332. }
  3333. let date = new Date(v);
  3334. let str = date.format('yyyy-MM-dd');
  3335. return str;
  3336. }
  3337. function DateTimeFormatter(v) {
  3338. if (!v) {
  3339. return "";
  3340. }
  3341. let date = new Date(v);
  3342. let str = date.format('yyyy-MM-dd hh:mm:ss');
  3343. return str;
  3344. }
  3345. //Hex-- > RGB
  3346. function HexToRgb(str) {
  3347. //replace替换查找的到的字符串
  3348. str = str.replace("#", "");
  3349. if (str.length === 3) {
  3350. str = str + str;
  3351. }
  3352. //match得到查询数组
  3353. let hxs = str.match(/../g);
  3354. for (let i = 0; i < 3; i++) hxs[i] = parseInt(hxs[i], 16);
  3355. return hxs;
  3356. }
  3357. //Hex-- > RGB
  3358. function HexToRgbStr(str) {
  3359. let hxs = HexToRgb(str);
  3360. return 'rgb(' + hxs[0] + ', ' + hxs[1] + ', ' + hxs[2] + ')';
  3361. }
  3362. //RGB-- > Hex
  3363. function RgbToHex(a, b, c) {
  3364. let hexs = [a.toString(16), b.toString(16), c.toString(16)];
  3365. for (let i = 0; i < 3; i++)
  3366. if (hexs[i].length == 1)
  3367. hexs[i] = "0" + hexs[i];
  3368. return "#" + hexs.join("");
  3369. }
  3370. $(function () {
  3371. $('select[data-select-tree="true"]').select2tree();
  3372. $('select[data-select-ajax="true"]').each(function () {
  3373. let $this = $(this);
  3374. let cKey = function () { return $this.data('param-key') },
  3375. take = function () { return $this.data('param-count') },
  3376. funResultTemplate = function () { return $this.data('result-template-function') };
  3377. debug_log("ajax-select", cKey(), take(), funResultTemplate());
  3378. $this.select2({
  3379. language: window.lang,
  3380. ajax: {
  3381. url: abp.appUrl + "Query/AcInfos",
  3382. type: "post",
  3383. dataType: 'json',
  3384. delay: 250,
  3385. data: function (params) {
  3386. let page = params.page || 1;
  3387. let queryParam = {
  3388. CodeKey: cKey(),
  3389. NameKey: params.term, // search term
  3390. Skip: (page - 1) * take(),
  3391. Take: take()
  3392. };
  3393. return queryParam;
  3394. },
  3395. processResults: function (data, params) {
  3396. debug_log("ajax-select_processResults", data, params);
  3397. params.page = params.page || 1;
  3398. let result = {
  3399. results: data.items.map(function (v) {
  3400. v.id = v.valueKey;
  3401. v.text = v.nameKey;
  3402. return v;
  3403. }),
  3404. pagination: {
  3405. more: (params.page * take()) < data.totalCount
  3406. }
  3407. };
  3408. return result;
  3409. },
  3410. transport: function (params, success, failure) {
  3411. params = params || {};
  3412. params.success = success;
  3413. params.error = failure;
  3414. let $request = $.vbAjax41(params);
  3415. return $request;
  3416. },
  3417. cache: true
  3418. },
  3419. cache: true,
  3420. minimumInputLength: 0,
  3421. templateResult: function (res) {
  3422. if (res.loading) {
  3423. return res.text;
  3424. }
  3425. let funTemplate = window[funResultTemplate()];
  3426. if (funTemplate && $.isFunction(funTemplate)) {
  3427. return funTemplate(res);
  3428. } else {
  3429. return '{0}'.format(res.text);
  3430. }
  3431. },
  3432. templateSelection: function (res) {
  3433. return res.text;
  3434. }
  3435. });
  3436. });
  3437. //Configure blockUI
  3438. if ($.blockUI) {
  3439. $.blockUI.defaults.baseZ = 2000;
  3440. }
  3441. //Configure validator
  3442. $.validator.setDefaults({
  3443. highlight: (el) => {
  3444. $(el).addClass('invalid');
  3445. $(el).removeClass('valid');
  3446. },
  3447. unhighlight: (el) => {
  3448. $(el).removeClass('invalid');
  3449. $(el).addClass('valid');
  3450. },
  3451. errorPlacement: (error, element) => {
  3452. let $el = element.closest('.d-flex').find('.invalid-feedback')
  3453. if ($el.length) {
  3454. $el.html(error).addClass('invalid-feedback-show');
  3455. }
  3456. let $tab = element.closest('.form-auto-tab');
  3457. if ($tab && $tab.length) {
  3458. $("#" + $tab.data("tab-name")).tab("show");
  3459. }
  3460. element.focus();
  3461. }
  3462. });
  3463. //serializeFormToObject plugin for jQuery
  3464. $.fn.serializeFormToObject = function (camelCased = false) {
  3465. //serialize to array
  3466. let data = $(this).serializeArray();
  3467. //add also disabled items
  3468. $(':disabled[name]', this).each(function () {
  3469. data.push({ name: this.name, value: $(this).val() });
  3470. });
  3471. //map to object
  3472. let obj = {};
  3473. data.map(function (x) { obj[x.name] = x.value; });
  3474. if (camelCased && camelCased === true) {
  3475. return convertToCamelCasedObject(obj);
  3476. }
  3477. function convertToCamelCasedObject(obj) {
  3478. let newObj, origKey, newKey, value;
  3479. if (obj instanceof Array) {
  3480. return obj.map(value => {
  3481. if (typeof value === 'object') {
  3482. value = convertToCamelCasedObject(value);
  3483. }
  3484. return value;
  3485. });
  3486. } else {
  3487. newObj = {};
  3488. for (origKey in obj) {
  3489. if (obj.hasOwnProperty(origKey)) {
  3490. newKey = (
  3491. origKey.charAt(0).toLowerCase() + origKey.slice(1) || origKey
  3492. ).toString();
  3493. value = obj[origKey];
  3494. if (
  3495. value instanceof Array || (value && value.constructor === Object)
  3496. ) {
  3497. value = convertToCamelCasedObject(value);
  3498. }
  3499. newObj[newKey] = value;
  3500. }
  3501. }
  3502. }
  3503. return newObj;
  3504. }
  3505. return obj;
  3506. };
  3507. })