You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2846 lines
109 KiB

2 years ago
  1. /*!
  2. * PageUtil.js
  3. * Copyright (c) 2018 CreativeDream
  4. * Website: xxx
  5. * Version: 1.0.0 (03-05-2018)
  6. * Requires: jQuery v1.7.1 or later
  7. */
  8. var i18next = "undefined" === typeof i18next ? parent.top.i18next : i18next,
  9. IsWaiting = null,
  10. bLeavePage = false,
  11. g_db = {
  12. /**
  13. * Check the capability
  14. * @private
  15. * @method SupportLocalStorage
  16. * @return {Object} description
  17. */
  18. SupportLocalStorage: function () {
  19. 'use strict';
  20. return typeof localStorage !== "undefined";
  21. },
  22. /**
  23. * Insert data
  24. * @private
  25. * @method SetItem
  26. * @param {String} sKey key鍵
  27. * @param {Object} sValue Value值
  28. * @return {Object} description
  29. */
  30. SetItem: function (sKey, sValue) {
  31. 'use strict';
  32. var bRes = false;
  33. if (this.SupportLocalStorage()) {
  34. localStorage.setItem(sKey, sValue);
  35. bRes = true;
  36. }
  37. return bRes;
  38. },
  39. /**
  40. * Fetch data
  41. * @private
  42. * @method GetItem
  43. * @param {String} sKey key鍵
  44. * @return {Object} description
  45. */
  46. GetItem: function (sKey) {
  47. 'use strict';
  48. var sRes = null;
  49. if (this.SupportLocalStorage()) {
  50. sRes = localStorage.getItem(sKey);
  51. }
  52. return sRes;
  53. },
  54. /**
  55. * Remove data
  56. * @private
  57. * @method RemoveItem
  58. * @param {String} sKey key鍵
  59. * @return {Object} description
  60. */
  61. RemoveItem: function (sKey) {
  62. 'use strict';
  63. var bRes = false;
  64. if (this.SupportLocalStorage()) {
  65. localStorage.removeItem(sKey);
  66. bRes = true;
  67. }
  68. return bRes;
  69. },
  70. /**
  71. * Description for GetDic
  72. * @private
  73. * @method GetDic
  74. * @param {String} sKey key鍵
  75. * @return {Object} description
  76. */
  77. GetDic: function (sKey) {
  78. 'use strict';
  79. var dicRes = null,
  80. vTemp;
  81. if (this.SupportLocalStorage()) {
  82. vTemp = localStorage.getItem(sKey);
  83. if (null !== vTemp) {
  84. dicRes = JSON.parse(vTemp);
  85. }
  86. }
  87. return dicRes;
  88. },
  89. /**
  90. * Description for SetDic
  91. * @private
  92. * @method SetDic
  93. * @param {String} sKey key鍵
  94. * @param {Object} dicValue json對象
  95. * @return {Object} description
  96. */
  97. SetDic: function (sKey, dicValue) {
  98. 'use strict';
  99. var bRes = false;
  100. if (this.SupportLocalStorage()) {
  101. localStorage.setItem(sKey, JSON.stringify(dicValue));
  102. bRes = true;
  103. }
  104. return bRes;
  105. }
  106. },
  107. g_gd = {
  108. webapilonginurl: "/api/Service/GetLogin",
  109. webapiurl: "/api/Cmd/GetData",
  110. projectname: "Eurotran",
  111. projectver: "Origtek",
  112. relpath: "",
  113. debugmode: window.location.host === '192.168.1.105',
  114. debugcolor: "#732C6B",
  115. IsEDU: g_db.GetItem("isedu") === "true"
  116. },
  117. g_ul = {
  118. /**
  119. * Get token from db
  120. * @returns {String} Token in localStorage
  121. */
  122. GetToken: function () {
  123. 'use strict';
  124. return g_db.GetItem("token");
  125. },
  126. /**
  127. * Set token to db
  128. * @param {String} sTokenValue api token
  129. */
  130. SetToken: function (sTokenValue) {
  131. 'use strict';
  132. g_db.SetItem("token", sTokenValue);
  133. },
  134. /**
  135. * Set signature to db
  136. * @return {Object} 簽名
  137. */
  138. GetSignature: function () {
  139. 'use strict';
  140. return g_db.GetItem("signature");
  141. },
  142. /**
  143. * Set signature to db
  144. * @param {String} sSignatureValue api signature
  145. */
  146. SetSignature: function (sSignatureValue) {
  147. 'use strict';
  148. g_db.SetItem("signature", sSignatureValue);
  149. },
  150. /**
  151. * Set language
  152. * @param {String} sLang 多語系值
  153. */
  154. SetLang: function (sLang) {
  155. 'use strict';
  156. g_db.SetItem("lang", sLang);
  157. },
  158. /**
  159. * Get language
  160. * @returns {String} language in localStorage
  161. */
  162. GetLang: function () {
  163. 'use strict';
  164. return g_db.GetItem("lang");
  165. },
  166. /**
  167. * Set login method
  168. * @param {String} sLoginMethod method
  169. */
  170. SetLoginMethod: function (sLoginMethod) {
  171. 'use strict';
  172. g_db.SetItem("LoginMethod", sLoginMethod);
  173. },
  174. /**
  175. * Get login method
  176. * @returns {String} login method in localStorage
  177. */
  178. GetLoginMethod: function () {
  179. 'use strict';
  180. return g_db.GetItem("LoginMethod");
  181. },
  182. /**
  183. * Check is edu environment
  184. * @returns {String} login method in localStorage
  185. */
  186. IsEDU: function () {
  187. 'use strict';
  188. return g_db.GetItem("isedu");
  189. },
  190. /**
  191. * 產生隨機數
  192. * @param {Number} len 指定长度,比如random(8)
  193. * @return {String} rnd 亂數碼
  194. */
  195. RndNum: function (len) {
  196. var rnd = "";
  197. len = len || 10;
  198. for (var i = 0; i < len; i++)
  199. rnd += Math.floor(Math.random() * 10);
  200. return rnd;
  201. }
  202. },
  203. g_api = {
  204. ConnectLite: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn, i_sShwd) {
  205. window.IsWaiting = i_sShwd;
  206. return this.ConnectLiteWithoutToken(i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn);
  207. },
  208. ConnectLiteWithoutToken: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn) {
  209. var dicData = {},
  210. dicParameters = {},
  211. token = g_ul.GetToken(),
  212. lang = g_ul.GetLang(),
  213. signature = g_ul.GetSignature();
  214. dicParameters.ORIGID = g_db.GetItem('orgid');
  215. dicParameters.USERID = g_db.GetItem('userid');
  216. dicParameters.MODULE = i_sModuleName;
  217. dicParameters.TYPE = i_sFuncName;
  218. dicParameters.PROJECT = g_gd.projectname;
  219. dicParameters.PROJECTVER = g_gd.projectver;
  220. dicParameters.TRACEDUMP = null; //
  221. i_dicData = i_dicData || {};
  222. if (g_db.GetItem('dblockDict') !== null) {
  223. i_dicData.dblockDict = g_db.GetItem('dblockDict');
  224. }
  225. dicParameters.DATA = i_dicData;
  226. if (lang !== null) {
  227. dicParameters.LANG = lang;
  228. }
  229. if (token !== null) {
  230. dicParameters.TOKEN = token;
  231. }
  232. if (signature !== null) {
  233. dicParameters.SIGNATURE = signature;
  234. }
  235. dicParameters.CUSTOMDATA = {};
  236. if (window.sProgramId) {
  237. dicParameters.CUSTOMDATA.program_id = sProgramId;
  238. }
  239. dicParameters.CUSTOMDATA.module_id = "webapp";
  240. dicData.url = i_dicData.hasOwnProperty("url") ? i_dicData.url : g_gd.webapiurl;
  241. dicData.successfunc = i_sSuccessFunc;
  242. dicData.dicparameters = dicParameters;
  243. dicData.failfunc = "function" === typeof i_FailFunc ? i_FailFunc : function (jqXHR, textStatus, errorThrown) {
  244. alert("ConnectLite Fail jqXHR:" + jqXHR + " textStatus:" + textStatus + " errorThrown:" + errorThrown);
  245. };
  246. dicData.useasync = "boolean" === typeof i_bAsyn ? i_bAsyn : true;
  247. return this.AjaxPost(dicData);
  248. },
  249. AjaxPost: function (i_dicData) {
  250. 'use strict';
  251. var defaultOption = {
  252. useasync: true,
  253. successfunc: null,
  254. failfunc: null,
  255. alwaysfunc: null,
  256. url: null,
  257. dicparameters: null
  258. },
  259. runOption = $.extend(defaultOption, i_dicData),
  260. runSuccess = function (res) {
  261. if (res.RESULT === -1) { // ╠message.TokenVerifyFailed⇒您的身份認證已經過期,請重新登入╣ ╠common.Tips⇒提示╣
  262. layer.alert(i18next.t("message.TokenVerifyFailed"), { icon: 0, title: i18next.t("common.Tips") }, function (index) {
  263. window.top.location.href = '/Page/login.html';
  264. });
  265. }
  266. else {
  267. if (runOption.successfunc) {
  268. runOption.successfunc(res);
  269. }
  270. }
  271. };
  272. return $.ajax({
  273. type: 'POST',
  274. url: runOption.url,
  275. data: "=" + btoa2(encodeURIComponent(JSON.stringify(runOption.dicparameters))),
  276. success: runSuccess,
  277. error: runOption.failfunc,
  278. beforeSend: function (xhr) {
  279. var token = g_ul.GetToken(),
  280. timestamp = $.now(),
  281. nonce = g_ul.RndNum();
  282. xhr.setRequestHeader("orgid", runOption.dicparameters.ORIGID);
  283. xhr.setRequestHeader("userid", runOption.dicparameters.USERID);
  284. xhr.setRequestHeader("token", token);
  285. xhr.setRequestHeader("timestamp", timestamp);
  286. xhr.setRequestHeader("nonce", nonce);
  287. },
  288. async: true !== runOption.useasync ? false : true
  289. }).always(runOption.alwaysfunc);
  290. }
  291. };
  292. var CanDo = (function (w, d) {
  293. 'use strict';
  294. var CanDo = function (config) {
  295. return new CanDo.fn._init(config);
  296. };
  297. CanDo.fn = CanDo.prototype = {
  298. constructor: CanDo,
  299. _init: function (config) {
  300. var cando = this,
  301. dfoptions = {
  302. cusBtns: [],//客製化按鈕
  303. goTop: true,//置頂圖標
  304. searchBar: true,//是否有搜尋區塊
  305. goBack: true,//是否返回查詢頁面
  306. insertGo: true,//新增完后是否跳轉
  307. updateGo: true,//修改完后是否跳轉
  308. deleteGo: true,//刪除完后是否跳轉
  309. pageSize: parent.top.SysSet.GridRecords || 0,//Grid顯示筆數
  310. gridPages: parent.top.SysSet.GridPages || 15,//Grid按鈕顯示數量
  311. queryPageidx: 1,//當前頁面索引
  312. toFirstPage: false
  313. };
  314. $.extend(dfoptions, config);
  315. for (var key in cando._pageParam) {
  316. var val = dfoptions[key];
  317. if (val) {
  318. cando._pageParam[key] = val;
  319. }
  320. }
  321. cando.options = dfoptions;
  322. cando.ids = {};
  323. cando.params = {};
  324. cando.UE_Editor = {};
  325. cando.currentPageValue = [];
  326. cando.validator = null;
  327. cando.CheckId = '';
  328. cando.action = cando._getAction();
  329. cando.ProgramId = cando._getProgramId();
  330. cando.QueryPrgId = cando._getQueryPrgId();
  331. cando.EditPrgId = cando._getEditPrgId();
  332. w.sProgramId = cando.ProgramId;
  333. cando.data = cando._data;
  334. cando.pageParam = cando._pageParam;
  335. cando.setGrid = function (grid) {
  336. cando.Grid = grid;
  337. };
  338. if (typeof cando.options.cusBtns === 'function') {
  339. cando.options.cusBtns = cando.options.cusBtns(cando);
  340. }
  341. var idKeys = cando.options.idKeys,
  342. paramKeys = cando.options.paramKeys,
  343. index,
  344. _key;
  345. if (idKeys && $.isArray(idKeys)) {
  346. for (index in idKeys) {
  347. if ('clear,insert,remove'.indexOf(index) === -1) {
  348. _key = idKeys[index];
  349. cando.ids[_key] = cando._getUrlParam(_key);
  350. cando.CheckId += cando.ids[_key] || '';
  351. }
  352. }
  353. }
  354. if (paramKeys && $.isArray(paramKeys)) {
  355. for (index in paramKeys) {
  356. if ('clear,insert,remove'.indexOf(index) === -1) {
  357. _key = paramKeys[index];
  358. cando.params[_key] = cando._getUrlParam(_key);
  359. }
  360. }
  361. }
  362. //ToolBar(功能函數)
  363. cando.initButtonHandler = function (inst, e) {
  364. return cando._buttonHandler.call(cando, inst, e);
  365. };
  366. //查詢(分頁)
  367. cando.getPage = function (args) {
  368. return cando._getPage(args);
  369. };
  370. //查詢(單筆)
  371. cando.getOne = function (args) {
  372. return cando._getOne(args);
  373. };
  374. //新增
  375. cando.getInsert = function (p, args) {
  376. return cando._getInsert(args);
  377. };
  378. //修改
  379. cando.getUpdate = function (args) {
  380. return cando._getUpdate(args);
  381. };
  382. //刪除
  383. cando.getDelete = function (args) {
  384. return cando._getDelete(args);
  385. };
  386. //匯出
  387. cando.getExcel = function (args) {
  388. if (args) {
  389. return cando._getPage(args);
  390. }
  391. };
  392. //Grid新增
  393. cando.gridInsert = function (args) {
  394. if (args) {
  395. return cando._gridInsert(args);
  396. }
  397. };
  398. //Grid新增
  399. cando.gridUpdate = function (args) {
  400. if (args) {
  401. return cando._gridUpdate(args);
  402. }
  403. };
  404. //Grid新增
  405. cando.gridDelete = function (args) {
  406. if (args) {
  407. return cando._gridDelete(args);
  408. }
  409. };
  410. for (_key in cando) {
  411. var _key_ = _key.replace('_', ''),
  412. _val = dfoptions[_key_];
  413. if (_val && _key !== 'constructor') {
  414. cando[_key_] = _val;
  415. }
  416. }
  417. if (!cando.form) {
  418. cando.form = cando._form;
  419. }
  420. if (!cando.jsGrid) {
  421. cando.jsGrid = cando._jsGrid;
  422. }
  423. //pageInit(功能初始化)
  424. cando._pageInit().done(function () {
  425. var editorIds = cando.options.ueEditorIds;
  426. if ($.isArray(editorIds)) {
  427. for (var index in editorIds) {
  428. if ('clear,insert,remove'.indexOf(index) === -1) {
  429. var key = editorIds[index];
  430. if ($('#UE_' + key).length > 0) {
  431. cando.UE_Editor[key] = UE.getEditor('UE_' + key);
  432. }
  433. }
  434. }
  435. }
  436. if (typeof cando.pageInit === 'function') {
  437. cando.pageInit.call(cando, cando);
  438. }
  439. if (typeof cando.options.validRulesCus === 'function') {
  440. cando.options.validRulesCus(cando);
  441. }
  442. if (typeof cando.options.validRules === 'function') {
  443. cando.options.validRules = cando.options.validRules(cando);
  444. }
  445. cando.validator = cando.form.validate(cando.options.validRules || {});
  446. });
  447. },
  448. _service: {
  449. cotrl: '/Controller.ashx',
  450. com: 'Common',
  451. opm: 'OpmCom',
  452. eip: 'EipCom',
  453. sys: 'SysCom',
  454. auth: 'Authorize'
  455. },
  456. _api: {
  457. getpage: 'QueryPage',
  458. getlist: 'QueryList',
  459. getone: 'QueryOne',
  460. getcout: 'QueryCout',
  461. insert: 'Insert',
  462. update: 'Update',
  463. delete: 'Delete',
  464. ginsert: 'GridInsert',
  465. gupdate: 'GridUpdate',
  466. gdelete: 'GridDelete',
  467. order: 'UpdateOrderByValue'
  468. },
  469. _data: {},
  470. _form: $('#form_main'),
  471. _jsGrid: $("#jsGrid"),
  472. _pageParam: {
  473. pageIndex: 1,
  474. pageSize: 10,
  475. sortField: 'OrderByValue',
  476. sortOrder: 'asc'
  477. },
  478. /**
  479. * 通過url獲取程式id
  480. * @param {String} path 文件路徑
  481. * @return {String} 程式ID
  482. */
  483. _getProgramId: function (path) {
  484. var herf = path || d.location.href,
  485. herfs = herf.split('/');
  486. herfs = herfs[herfs.length - 1].split('.');
  487. return herfs[0] || '';
  488. },
  489. /**
  490. * 通過查詢程式ID獲取編輯頁面程式ID
  491. * @return {String} 編輯頁面程式ID
  492. */
  493. _getEditPrgId: function () {
  494. var prgid = this._getProgramId();
  495. return prgid.replace('_Qry', '_Upd');
  496. },
  497. /**
  498. * 通過編輯程式ID獲取查詢程式ID
  499. * @return {String} 編輯頁面程式ID
  500. */
  501. _getQueryPrgId: function () {
  502. var prgid = this._getProgramId();
  503. return prgid.replace('_Upd', '_Qry');
  504. },
  505. /**
  506. * ToolBar 按鈕事件 function
  507. * @param {Object} inst 按鈕物件對象
  508. * @param {Object} e 事件對象
  509. * @return {Boolean} 停止標記
  510. */
  511. _buttonHandler: function (inst, e) {
  512. var cando = this,
  513. id = inst.id;
  514. if (!$.isEmptyObject(cando.UE_Editor)) {
  515. for (var key in cando.UE_Editor) {
  516. if ($('#' + key).length > 0) {
  517. $('#' + key).val(cando.UE_Editor[key].getContentTxt());
  518. }
  519. }
  520. }
  521. switch (id) {
  522. case "Toolbar_Qry":
  523. if (!cando.form.valid()) {
  524. cando.validator.focusInvalid();
  525. return false;
  526. }
  527. var iNum = $('#PerPageNum').val();
  528. cando.Grid && (cando.Grid.pageSize = iNum === '' ? cando.options.pageSize || 10 : iNum);
  529. cando._cacheQueryCondition();
  530. cando.Grid && cando.Grid.openPage(cando.options.toFirstPage ? 1 : cando.pageParam.pageIndex);
  531. if (typeof cando.options.afterQuery === 'function') {
  532. cando.options.afterQuery(cando);
  533. }
  534. break;
  535. case "Toolbar_Save":
  536. if (!cando.form.valid()) {
  537. cando.validator.focusInvalid();
  538. return false;
  539. }
  540. if (cando.action === 'add') {
  541. cando.getInsert.call(cando, cando, cando.action);
  542. }
  543. else {
  544. cando.getUpdate.call(cando, cando);
  545. }
  546. break;
  547. case "Toolbar_ReAdd":
  548. if (!cando.form.valid()) {
  549. cando.validator.focusInvalid();
  550. return false;
  551. }
  552. cando.getInsert.call(cando, cando, 'readd');
  553. break;
  554. case "Toolbar_Clear":
  555. cando._clearPageVal();
  556. break;
  557. case "Toolbar_Leave":
  558. cando._pageLeave();
  559. break;
  560. case "Toolbar_Add":
  561. parent.openPageTab(cando.EditPrgId, '?Action=Add');
  562. break;
  563. case "Toolbar_Upd":
  564. break;
  565. case "Toolbar_Copy":
  566. break;
  567. case "Toolbar_Del": // ╠message.ConfirmToDelete⇒確定要刪除嗎 ?╣ ╠common.Tips⇒提示╣
  568. layer.confirm(i18next.t("message.ConfirmToDelete"), { icon: 3, title: i18next.t('common.Tips') }, function (index) {
  569. cando.getDelete.call(cando);
  570. layer.close(index);
  571. });
  572. break;
  573. case "Toolbar_Exp":
  574. if (cando.Grid.data.length === 0) {
  575. showMsg(i18next.t("message.NoDataExport"));// ╠message.NoDataExport⇒沒有資料匯出╣
  576. return false;
  577. }
  578. cando.getExcel({ Excel: true });
  579. break;
  580. default:
  581. {
  582. var actions = cando.options.cusBtns.filter(function (item) { return item.id === id; });
  583. if (actions.length > 0 && typeof actions[0].action === 'function') {
  584. actions[0].action(cando);
  585. }
  586. else {
  587. alert("No handle '" + id + "'");
  588. }
  589. }
  590. break;
  591. }
  592. },
  593. /**
  594. * 通過編輯程式ID獲取查詢程式ID
  595. */
  596. _initGrid: function () {
  597. var cando = this,
  598. iheight = $('body').height() - $('.page-title').height() - $('#searchbar').height() - 87;
  599. if (typeof cando.options.gridFields === 'function') {
  600. cando.options.gridFields = cando.options.gridFields(cando);
  601. }
  602. cando.jsGrid.jsGrid({
  603. width: "100%",
  604. height: iheight + "px",
  605. autoload: true,
  606. pageLoading: true,
  607. inserting: cando.options.inserting || false,
  608. editing: true,
  609. sorting: true,
  610. paging: true,
  611. pageIndex: cando.options.toFirstPage ? 1 : cando.options.queryPageidx,
  612. pageSize: cando.options.pageSize,
  613. pageButtonCount: cando.options.gridPages,
  614. invalidMessage: i18next.t('common.InvalidData'),
  615. confirmDeleting: true,
  616. deleteConfirm: i18next.t('message.ConfirmToDelete'),
  617. pagePrevText: "<",
  618. pageNextText: ">",
  619. pageFirstText: "<<",
  620. pageLastText: ">>",
  621. fields: cando.options.gridFields,
  622. onItemEditing: function (args) {
  623. if (typeof cando.options.onItemEditing === 'function') {
  624. cando.options.onItemEditing(args);
  625. }
  626. },
  627. onPageChanged: function (args) {
  628. if (typeof cando.options.onPageChanged === 'function') {
  629. cando.options.onPageChanged(cando, args);
  630. }
  631. else {
  632. cando._cacheQueryCondition(args.pageIndex);
  633. }
  634. },
  635. rowClick: function (args) {
  636. if (typeof cando.options.rowClick === 'function') {
  637. cando.options.rowClick(cando, args);
  638. }
  639. else {
  640. if (navigator.userAgent.match(/mobile/i)) {
  641. var _param = cando._getParamsStr(cando.ids, args.item);
  642. cando._goToEdit(cando.EditPrgId, '?Action=Upd' + _param);
  643. }
  644. }
  645. },
  646. rowDoubleClick: function (args) {
  647. if (typeof cando.options.rowDoubleClick === 'function') {
  648. cando.options.rowDoubleClick(cando, args);
  649. }
  650. else {
  651. var _param = cando._getParamsStr(cando.ids, args.item);
  652. parent.top.openPageTab(cando.EditPrgId, '?Action=Upd' + _param);
  653. }
  654. },
  655. controller: {
  656. loadData: function (args) {
  657. return cando.getPage(args);
  658. },
  659. insertItem: function (args) {
  660. return cando.gridInsert(args);
  661. },
  662. updateItem: function (args) {
  663. return cando.gridUpdate(args);
  664. },
  665. deleteItem: function (args) {
  666. return cando.gridDelete(args);
  667. }
  668. },
  669. onInit: function (args) {
  670. cando.setGrid(args.grid);
  671. }
  672. });
  673. },
  674. /**
  675. * 基本查詢分頁
  676. * @param {String} args 參數
  677. * @return {Object} Ajax對象
  678. */
  679. _getPage: function (args) {
  680. var cando = this,
  681. qrParam = cando._getFormSerialize();
  682. $.extend(qrParam, cando.pageParam, args);
  683. cando.pageParam.pageIndex = qrParam.pageIndex;
  684. return g_api.ConnectLite(cando.ProgramId, cando._api.getpage, qrParam, function (res) {
  685. if (res.RESULT) {
  686. var oRes = res.DATA.rel;
  687. if (args.Excel) {//匯出
  688. cando._downLoadFile.call(cando, oRes);
  689. if (layer && args.Index) {
  690. layer.close(args.Index);
  691. }
  692. }
  693. }
  694. });
  695. },
  696. /**
  697. * 基本查詢單筆
  698. * @return {Object} Ajax對象
  699. */
  700. _getOne: function () {
  701. var cando = this,
  702. data = clone(cando.ids);
  703. if (typeof cando.options.getOneParams === 'function') {
  704. data = cando.options.getOneParams(cando);
  705. }
  706. return g_api.ConnectLite(cando.ProgramId, cando._api.getone, data,
  707. function (res) {
  708. if (res.RESULT) {
  709. cando.data = res.DATA.rel;
  710. var jsonStrKeys = cando.options.jsonStrKeys;
  711. if (jsonStrKeys && $.isArray(jsonStrKeys)) {
  712. for (var index in jsonStrKeys) {
  713. if ('clear,insert,remove'.indexOf(index) === -1) {
  714. var key = jsonStrKeys[index],
  715. val = cando.data[key];
  716. if (typeof val === 'string' && val !== '') {
  717. cando.data[key] = JSON.parse(val);
  718. }
  719. }
  720. }
  721. }
  722. if (typeof cando.options.getOneBack === 'function') {
  723. cando.options.getOneBack(cando, cando.data);
  724. }
  725. else {
  726. cando._setFormVal(cando.data);
  727. cando._setUEValues(cando.data);
  728. }
  729. setTimeout(function () {
  730. cando._getPageVal();//緩存頁面值,用於清除
  731. }, 500);
  732. }
  733. },
  734. function () {
  735. showMsg(i18next.t("message.GetOne_Error"), 'error'); // ╠message.GetOne_Error⇒獲取當前資料異常╣
  736. });
  737. },
  738. /**
  739. * 基本新增
  740. * @param {String} flag 新增 or 儲存后新增
  741. * @return {Object} Ajax對象
  742. */
  743. _getInsert: function (flag) {
  744. var cando = this,
  745. data = cando._getFormSerialize();
  746. data = cando._getUEValues(data);
  747. if (typeof cando.options.getInsertParams === 'function') {
  748. data = cando.options.getInsertParams(cando, data);
  749. }
  750. data = $.extend(cando.data, data);
  751. return g_api.ConnectLite(cando.ProgramId, cando._api.insert, data, function (res) {
  752. if (res.RESULT) {
  753. w.bRequestStorage = false;
  754. var oRes = res.DATA.rel;
  755. if (typeof cando.options.getInsertBack === 'function') {
  756. cando.options.getInsertBack(cando, oRes, flag);
  757. }
  758. else {
  759. if (!cando.options.goBack) {
  760. var _param = cando._getParamsStr(cando.ids, oRes);
  761. showMsgAndGo(i18next.t("message.Insert_Success"), cando.ProgramId, '?Action=Upd' + _param); // ╠message.Save_Success⇒新增成功╣
  762. }
  763. else {
  764. if (flag === 'add') {
  765. if (cando.options.insertGo) {
  766. showMsgAndGo(i18next.t("message.Insert_Success"), cando.QueryPrgId); // ╠message.Insert_Success⇒新增成功╣
  767. }
  768. else {
  769. showMsg(i18next.t("message.Insert_Success"), 'success'); //╠message.Insert_Success⇒新增成功╣
  770. }
  771. }
  772. else {
  773. showMsgAndGo(i18next.t("message.Insert_Success"), cando.ProgramId, '?Action=Add'); // ╠message.Insert_Success⇒新增成功╣
  774. }
  775. }
  776. }
  777. }
  778. else {
  779. showMsg(i18next.t("message.Insert_Failed") + '<br>' + res.MSG, 'error');// ╠message.Insert_Failed⇒新增失敗╣
  780. }
  781. }, function () {
  782. showMsg(i18next.t("message.Insert_Error"), 'error');// ╠message.Insert_Error⇒新增資料異常╣
  783. });
  784. },
  785. /**
  786. * 基本修改
  787. * @return {Object} Ajax對象
  788. */
  789. _getUpdate: function () {
  790. var cando = this,
  791. data = cando._getFormSerialize();
  792. data = cando._getUEValues(data);
  793. if (typeof cando.options.getUpdateParams === 'function') {
  794. data = cando.options.getUpdateParams(cando, data);
  795. }
  796. data = $.extend(cando.data, data, cando.ids);
  797. return g_api.ConnectLite(cando.ProgramId, cando._api.update, data, function (res) {
  798. if (res.RESULT) {
  799. w.bRequestStorage = false;
  800. var oRes = res.DATA.rel;
  801. if (typeof cando.options.getUpdateBack === 'function') {
  802. cando.options.getUpdateBack(cando, oRes);
  803. }
  804. else {
  805. if (cando.options.updateGo) {
  806. showMsgAndGo(i18next.t("message.Modify_Success"), cando.QueryPrgId); //╠message.Modify_Success⇒修改成功╣
  807. }
  808. else {
  809. showMsg(i18next.t("message.Modify_Success"), 'success'); //╠message.Modify_Success⇒修改成功╣
  810. if (w.bLeavePage) {
  811. setTimeout(function () {
  812. cando._pageLeave();
  813. }, 1000);
  814. }
  815. }
  816. }
  817. }
  818. else {
  819. showMsg(i18next.t("message.Modify_Failed") + '<br>' + res.MSG, 'error');// ╠message.Modify_Failed⇒修改失敗╣
  820. }
  821. }, function () {
  822. showMsg(i18next.t("message.Modify_Error"), 'error');//╠message.Modify_Error⇒修改資料異常╣
  823. });
  824. },
  825. /**
  826. * 基本刪除
  827. * @param {String} args 參數
  828. * @return {Object} Ajax對象
  829. */
  830. _getDelete: function (args) {
  831. var cando = this,
  832. data = clone(cando.ids);
  833. if (typeof cando.options.getDeleteParams === 'function') {
  834. data = cando.options.getDeleteParams(cando);
  835. }
  836. return g_api.ConnectLite(cando.ProgramId, cando._api.delete, data, function (res) {
  837. if (res.RESULT) {
  838. var oRes = res.DATA.rel;
  839. if (typeof cando.options.getDeleteBack === 'function') {
  840. cando.options.getDeleteBack(cando, oRes);
  841. } else {
  842. if (cando.options.deleteGo) {
  843. showMsgAndGo(i18next.t("message.Delete_Success"), cando.QueryPrgId); // ╠message.Delete_Success⇒刪除成功╣
  844. }
  845. else {
  846. showMsg(i18next.t("message.Delete_Success"), 'success'); //╠message.Delete_Success⇒刪除成功╣
  847. }
  848. }
  849. }
  850. else {
  851. showMsg(i18next.t("message.Delete_Failed") + '<br>' + res.MSG, 'error');// ╠message.Delete_Failed⇒刪除失敗╣
  852. }
  853. }, function () {
  854. showMsg(i18next.t("message.Delete_Error"), 'error'); // ╠message.Delete_Error⇒刪除資料異常╣
  855. });
  856. },
  857. /**
  858. * Grid新增
  859. * @param {String} data 新增參數
  860. * @return {Object} Ajax對象
  861. */
  862. _gridInsert: function (data) {
  863. var cando = this;
  864. if (typeof cando.options.getGridInsertParams === 'function') {
  865. data = cando.options.getGridInsertParams(cando, data);
  866. }
  867. return g_api.ConnectLite(cando.ProgramId, cando._api.ginsert, data, function (res) {
  868. if (res.RESULT) {
  869. var oRes = res.DATA.rel;
  870. if (typeof cando.options.getGridInsertBack === 'function') {
  871. cando.options.getGridInsertBack(cando, oRes);
  872. }
  873. else {
  874. showMsg(i18next.t("message.Insert_Success"), 'success'); // ╠message.Insert_Success⇒新增成功╣
  875. }
  876. }
  877. else {
  878. showMsg(i18next.t("message.Insert_Failed") + '<br>' + res.MSG, 'error');// ╠message.Insert_Failed⇒新增失敗╣
  879. }
  880. }, function () {
  881. showMsg(i18next.t("message.Insert_Error"), 'error');// ╠message.Insert_Error⇒新增資料異常╣
  882. });
  883. },
  884. /**
  885. * Grid修改
  886. * @param {String} data 修改參數
  887. * @return {Object} Ajax對象
  888. */
  889. _gridUpdate: function (data) {
  890. var cando = this;
  891. if (typeof cando.options.getGridUpdateParams === 'function') {
  892. data = cando.options.getGridUpdateParams(cando, data);
  893. }
  894. return g_api.ConnectLite(cando.ProgramId, cando._api.gupdate, data, function (res) {
  895. if (res.RESULT) {
  896. var oRes = res.DATA.rel;
  897. if (typeof cando.options.getGridUpdateBack === 'function') {
  898. cando.options.getGridUpdateBack(cando, oRes);
  899. }
  900. else {
  901. showMsg(i18next.t("message.Modify_Success"), 'success'); //╠message.Modify_Success⇒修改成功╣
  902. }
  903. }
  904. else {
  905. showMsg(i18next.t("message.Modify_Failed") + '<br>' + res.MSG, 'error');// ╠message.Modify_Failed⇒修改失敗╣
  906. }
  907. }, function () {
  908. showMsg(i18next.t("message.Modify_Error"), 'error');//╠message.Modify_Error⇒修改資料異常╣
  909. });
  910. },
  911. /**
  912. * Grid刪除
  913. * @param {String} data 刪除參數
  914. * @return {Object} Ajax對象
  915. */
  916. _gridDelete: function (data) {
  917. var cando = this;
  918. if (typeof cando.options.getGridDeleteParams === 'function') {
  919. data = cando.options.getGridDeleteParams(cando);
  920. }
  921. return g_api.ConnectLite(cando.ProgramId, cando._api.gdelete, data, function (res) {
  922. if (res.RESULT) {
  923. var oRes = res.DATA.rel;
  924. if (typeof cando.options.getGridDeleteBack === 'function') {
  925. cando.options.getGridDeleteBack(cando, oRes);
  926. } else {
  927. showMsg(i18next.t("message.Delete_Success"), 'success'); // ╠message.Delete_Success⇒刪除成功╣
  928. }
  929. }
  930. else {
  931. showMsg(i18next.t("message.Delete_Failed") + '<br>' + res.MSG, 'error');// ╠message.Delete_Failed⇒刪除失敗╣
  932. }
  933. }, function () {
  934. showMsg(i18next.t("message.Delete_Error"), 'error'); // ╠message.Delete_Error⇒刪除資料異常╣
  935. });
  936. },
  937. /**
  938. * 基本匯出
  939. * @param {String} args 參數
  940. */
  941. _getExcel: function (args) {
  942. },
  943. /**
  944. * 基本查詢分頁
  945. * @param {String} args 參數
  946. * @return {Object} Ajax對象
  947. */
  948. _pageInit: function (args) {
  949. var cando = this;
  950. if (navigator.userAgent.match(/mobile/i)) {
  951. $('.ismobile').hide();
  952. }
  953. if ($("#tabs").length > 0) {
  954. $("#tabs").tabs().find('li').on('click', function () {
  955. var that = this;
  956. $('#tabs>ul>li').removeClass('active');
  957. $(this).addClass('active');
  958. if (typeof cando.options.tabAction === 'function') {
  959. cando.options.tabAction(that, cando);
  960. }
  961. });
  962. }
  963. setTimeout(function () {
  964. if ($.datepicker !== undefined) {
  965. $.datepicker.regional['zh-TW'] = {
  966. dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
  967. dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
  968. monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
  969. monthNamesShort: ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"],
  970. prevText: "上月",
  971. nextText: "次月",
  972. weekHeader: "週",
  973. showMonthAfterYear: true, // True if the year select precedes month, false for month then year//設置是否在面板的头部年份后面显示月份
  974. dateFormat: "yy/mm/dd"
  975. };
  976. $.datepicker.setDefaults($.datepicker.regional["zh-TW"]);
  977. }
  978. //註冊日曆控件(不含時間)
  979. if ($('.date-picker').length > 0) {
  980. $('.date-picker').datepicker({
  981. changeYear: true,
  982. changeMonth: true,
  983. altFormat: 'yyyy/MM/dd',
  984. onSelect: function (r, e) {
  985. if (typeof cando.options.onSelect === 'function') {
  986. cando.options.onSelect(r, e);
  987. }
  988. },
  989. afterInject: function (r, e) { }
  990. });
  991. }
  992. //註冊日曆控件(含時間)
  993. if ($('.datetime-picker').length > 0) {
  994. $('.datetime-picker').each(function () {
  995. var iHour = ($(this).attr('hour') || 9) * 1,
  996. iMinute = ($(this).attr('minute') || 0) * 1,
  997. iStepMinute = ($(this).attr('stepminute') || 15) * 1;
  998. $(this).datetimepicker({
  999. changeYear: true,
  1000. changeMonth: true,
  1001. altFormat: 'yyyy/MM/dd',
  1002. timeFormat: 'HH:mm',
  1003. //minDateTime: new Date(),
  1004. //maxDateTime: new Date().dateAdd('d', 5),
  1005. //defaultValue: newDate(null, true) + ' 08:00',
  1006. hour: iHour,
  1007. minute: iMinute,
  1008. stepMinute: iStepMinute,
  1009. hourGrid: 6,
  1010. minuteGrid: 15,
  1011. onSelect: function (r, e) {
  1012. if (typeof cando.options.onSelect === 'function') {
  1013. cando.options.onSelect(r, e);
  1014. }
  1015. },
  1016. afterInject: function (r, e) { }
  1017. });
  1018. });
  1019. }
  1020. //註冊日曆控件(時間)
  1021. if ($('.time-picker').length > 0) {
  1022. $('.time-picker').each(function () {
  1023. var iHour = ($(this).attr('hour') || 9) * 1,
  1024. iMinute = ($(this).attr('minute') || 0) * 1;
  1025. $(this).timepicker({
  1026. timeFormat: 'HH:mm',
  1027. hour: iHour,
  1028. minute: iMinute,
  1029. minuteGrid: 30,
  1030. stepMinute: 30,
  1031. onSelect: function (r, e) {
  1032. if (typeof cando.options.onSelect === 'function') {
  1033. cando.options.onSelect(r, e);
  1034. }
  1035. }
  1036. });
  1037. });
  1038. }
  1039. }, 1000);
  1040. //註冊顏色控件
  1041. if ($('.color-picker').length > 0) {
  1042. $('.color-picker').each(function () {
  1043. var that = this;
  1044. $(that).spectrum({
  1045. color: "#000000",
  1046. //flat: true,
  1047. showInput: true,
  1048. className: "full-spectrum",
  1049. showInitial: true,
  1050. showPalette: true,
  1051. showSelectionPalette: true,
  1052. maxPaletteSize: 10,
  1053. preferredFormat: "hex",
  1054. hide: function (color) {
  1055. $(that).val(color.toHexString());
  1056. },
  1057. palette: [
  1058. ["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)",
  1059. "rgb(204, 204, 204)", "rgb(217, 217, 217)", "rgb(255, 255, 255)",
  1060. "rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)"],
  1061. ["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
  1062. "rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
  1063. "rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
  1064. "rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
  1065. "rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
  1066. "rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
  1067. "rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
  1068. "rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
  1069. "rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
  1070. "rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)",
  1071. "rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"]
  1072. ]
  1073. });
  1074. });
  1075. }
  1076. cando._keyInput(); //註冊欄位管控
  1077. cando._select2Init();//初始化select2
  1078. cando._uniformInit();//表單美化
  1079. if (cando.options.goTop) {
  1080. var elTop = $('<div>', {
  1081. class: 'gotop',
  1082. html: '<img src="../../images/gotop_1.png" />', click: function () {
  1083. return $("body,html").animate({ scrollTop: 0 }, 120), !1;
  1084. }
  1085. });
  1086. $('body').append(elTop.hide());//添加置頂控件
  1087. $(d).on('scroll', function () {
  1088. var h = ($(d).height(), $(this).scrollTop()),
  1089. toolbarH = -45,
  1090. toolbarCss = {},
  1091. elToolBar = cando._getToolBar();
  1092. h > 0 ? elTop.fadeIn() : elTop.fadeOut();
  1093. if (h > 35) {
  1094. toolbarH = h - 80;
  1095. elToolBar.addClass('toolbar-float').removeClass('toolbar-fix');
  1096. }
  1097. else {
  1098. elToolBar.removeClass('toolbar-float').addClass('toolbar-fix');
  1099. }
  1100. elToolBar.css('margin-top', toolbarH + 'px');
  1101. });
  1102. }
  1103. if (cando.ProgramId) {
  1104. var lang = g_ul.GetLang() || 'zh-TW';
  1105. cando._setLang(lang);//翻譯多語系
  1106. cando._getPageVal(); //緩存頁面值,用於清除
  1107. cando._createPageTitle(); //創建Header
  1108. if (cando.options.searchBar) { //設置顯示于隱藏搜尋區塊
  1109. var iSearchBox_h = $('#searchbar').height(),
  1110. elSlideUpDown = $('<i>', {
  1111. class: 'fa fa-arrow-up slide-box',
  1112. click: function () {
  1113. if ($(this).hasClass('fa-arrow-up')) {
  1114. $(this).removeClass('fa-arrow-up').addClass('fa-arrow-down');
  1115. elSearchBox.slideUp();
  1116. !!cando.Grid && (cando.Grid.height = cando.Grid.dfheight.replace('px', '') * 1 + iSearchBox_h + 'px');
  1117. }
  1118. else {
  1119. $(this).removeClass('fa-arrow-down').addClass('fa-arrow-up');
  1120. elSearchBox.slideDown();
  1121. !!cando.Grid && (cando.Grid.height = cando.Grid.dfheight);
  1122. }
  1123. !!cando.Grid && cando.Grid.refresh();
  1124. //調整Grid slimscrollDIV高度,保證和實際高度一致
  1125. var elGridBox = $('.jsgrid-grid-body.slimscroll');
  1126. elGridBox.parent().css('height', elGridBox.css('height'));
  1127. }
  1128. }),
  1129. elSlideDiv = $('<div>', { class: 'col-sm-12 up-down-go' }).append(elSlideUpDown),
  1130. elSearchBox = $('#searchbar').after(elSlideDiv);
  1131. }
  1132. cando._reSetQueryPm(); //恢復之前查詢條件
  1133. //加載按鈕權限
  1134. return cando._getAuthority(cando).done(function () {
  1135. });
  1136. }
  1137. },
  1138. /**
  1139. * 獲取權限
  1140. * @return {Object} Ajax對象
  1141. */
  1142. _getAuthority: function (outterCando) {
  1143. var cando = this,
  1144. topmod = cando._getTopMod();
  1145. return g_api.ConnectLite('Authorize', 'GetAuthorize',
  1146. {
  1147. ProgramID: cando.ProgramId,
  1148. TopModuleID: topmod
  1149. },
  1150. function (res) {
  1151. if (res.RESULT) {
  1152. var authorize = res.DATA.rel,
  1153. btns = [],
  1154. hasBtn = {},
  1155. lastBtn = null,
  1156. elToolBar = cando._getToolBar(),
  1157. initToolbar = function () {//等待 ToolBar(wedget)初始化ok后在執行,否則會報錯
  1158. elToolBar.ToolBar({
  1159. btns: btns,
  1160. fncallback: cando.initButtonHandler
  1161. });
  1162. cando._transLang(elToolBar);
  1163. },
  1164. delayInitToolbar = function () {
  1165. if ($.fn.ToolBar) {
  1166. initToolbar();
  1167. }
  1168. else {
  1169. delayInitToolbar();
  1170. }
  1171. };
  1172. $.each(authorize, function (idx, roleright) {
  1173. if (roleright.AllowRight) {
  1174. var saRights = roleright.AllowRight.split('|');
  1175. $.each(saRights, function (e, btnright) {
  1176. var sBtn = $.trim(btnright);
  1177. if (hasBtn[sBtn.toLowerCase()] === undefined) {
  1178. hasBtn[sBtn.toLowerCase()] = sBtn;
  1179. }
  1180. });
  1181. }
  1182. });
  1183. if (!hasBtn['upd']) {
  1184. delete hasBtn.save;
  1185. delete hasBtn.readd;
  1186. }
  1187. if (cando.action === 'upd') {
  1188. delete hasBtn.readd;
  1189. }
  1190. if (cando.action === 'add') {
  1191. delete hasBtn.del;
  1192. }
  1193. delete hasBtn.upd;
  1194. delete hasBtn.view;
  1195. for (var btnkey in hasBtn) {
  1196. var oBtn = {};
  1197. oBtn.key = hasBtn[btnkey];
  1198. if (btnkey === 'leave') {
  1199. lastBtn = oBtn;
  1200. lastBtn.hotkey = 'ctrl + l';
  1201. }
  1202. else {
  1203. switch (btnkey) {
  1204. case 'qry':
  1205. oBtn.hotkey = 'enter';
  1206. break;
  1207. case 'add':
  1208. oBtn.hotkey = 'ctrl + i';
  1209. break;
  1210. case 'readd':
  1211. oBtn.hotkey = 'ctrl + r';
  1212. break;
  1213. case 'save':
  1214. oBtn.hotkey = 'ctrl + s';
  1215. break;
  1216. case 'del':
  1217. oBtn.hotkey = 'ctrl + d';
  1218. break;
  1219. case 'clear':
  1220. oBtn.hotkey = 'ctrl + q';
  1221. break;
  1222. }
  1223. btns.push(oBtn);
  1224. }
  1225. }
  1226. if (cando.options.cusBtns.length > 0) {
  1227. btns.push.apply(btns, cando.options.cusBtns);
  1228. }
  1229. if (lastBtn) {
  1230. btns.push(lastBtn);
  1231. }
  1232. delayInitToolbar();
  1233. //button Ready時候
  1234. if (outterCando.ProgramId.indexOf('_Upd') > -1) {
  1235. var action = outterCando._getAction();
  1236. if (action === 'upd') {//判斷當前頁面是否有人在操作
  1237. parent.top.msgs.server.checkEdit(outterCando.ProgramId, outterCando.CheckId);
  1238. }
  1239. outterCando.form.find(':input,select').not('[data-type=select2]').change(function () {
  1240. if (!$(this).attr('data-trigger')) {
  1241. w.bRequestStorage = true;
  1242. }
  1243. });
  1244. setTimeout(function () {
  1245. outterCando.form.find('[data-type=select2]').change(function () {
  1246. if (!$(this).attr('data-trigger')) {
  1247. w.bRequestStorage = true;
  1248. }
  1249. });
  1250. }, 3000);
  1251. }
  1252. else {
  1253. if (outterCando.ProgramId.indexOf('_Qry') > -1) {
  1254. parent.top.msgs.server.removeEditPrg(outterCando.ProgramId.replace('_Qry', '_Upd'));//防止重複點擊首頁菜單導致之前編輯資料狀態無法移除
  1255. }
  1256. var oQueryBtn = $('#Toolbar_Qry');
  1257. if (oQueryBtn.length > 0) {
  1258. $('select').on('change', function (e, arg) {
  1259. //select2下拉單改變自動查詢
  1260. setTimeout(function () {
  1261. if (arg !== 'clear') {//清除動作(賦值)不查詢
  1262. $('#Toolbar_Qry').click();
  1263. }
  1264. }, 10);
  1265. });
  1266. $(':input[type="radio"],:input[type="checkbox"]').on('click', function (e, arg) {
  1267. //radio值改變自動查詢
  1268. if (arg !== 'clear') {//清除動作(賦值)不查詢
  1269. $('#Toolbar_Qry').click();
  1270. }
  1271. });
  1272. }
  1273. }
  1274. }
  1275. });
  1276. },
  1277. /**
  1278. * 取得頂層模組
  1279. * @return {String} 頂層模組
  1280. */
  1281. _getTopMod: function () {
  1282. var cando = this,
  1283. topmod = '',
  1284. programList = g_db.GetDic('programList') || [],
  1285. program = programList.filter(function (item) { return item.ModuleID === cando.ProgramId; })[0],
  1286. getParent = function (modid) {
  1287. var oMod = cando._getParentMod(modid);
  1288. if (oMod.ParentID) {
  1289. getParent(oMod.ParentID);
  1290. }
  1291. else {
  1292. topmod = oMod.ModuleID;
  1293. }
  1294. };
  1295. getParent(program.ParentID);
  1296. return topmod;
  1297. },
  1298. /**
  1299. * 序列化form表單
  1300. * @param {HTMLElement} fm 表單form物件
  1301. * @param {String} type 傳回類型
  1302. * @return {Object} fmdata 表單資料
  1303. */
  1304. _getFormSerialize: function (fm, type) {
  1305. var cando = this,
  1306. fmdata = {};
  1307. fm = fm || cando.form;
  1308. reFreshInput(fm);
  1309. if (type) {
  1310. fmdata = fm.serializeJSON();
  1311. }
  1312. else {
  1313. fmdata = fm.serializeObject();
  1314. }
  1315. reSetInput(fm);
  1316. return fmdata;
  1317. },
  1318. /**
  1319. *取得程式所在模組的父層模組
  1320. * @param {String} modid 模組id
  1321. * @return {Object} 模組對象
  1322. */
  1323. _getParentMod: function (modid) {
  1324. var cando = this,
  1325. programList = g_db.GetDic('programList') || [],
  1326. parentProgram = programList.filter(function (item) { return item.ModuleID === modid && item.FilePath === '#'; })[0];
  1327. return parentProgram;
  1328. },
  1329. /**
  1330. * 儲存當前頁面的值
  1331. * @param {String} elId 要清除區塊的父層Id
  1332. */
  1333. _getPageVal: function (elId) {
  1334. var cando = this,
  1335. //判斷傳入的樣式是否不存在或者等於空的情況
  1336. oHandle = elId !== undefined ? $('#' + elId) : cando.form;
  1337. cando.currentPageValue = [];
  1338. //儲存畫面值
  1339. oHandle.find(':input', 'textarea', 'select').each(function () {
  1340. var ctl = {}; //實例化對象
  1341. ctl.ID = this.id;
  1342. ctl.Type = this.type;
  1343. if (ctl.ID && ctl.Type) {
  1344. switch (this.type) {
  1345. case 'text':
  1346. case 'email':
  1347. case 'url':
  1348. case 'number':
  1349. case 'range':
  1350. case 'date':
  1351. case 'search':
  1352. case 'color':
  1353. case 'password':
  1354. case 'hidden':
  1355. case 'textarea':
  1356. ctl.Value = $(this).val();
  1357. break;
  1358. case 'checkbox':
  1359. case 'radio':
  1360. ctl.Checked = this.checked;
  1361. break;
  1362. case 'select-multiple':
  1363. case 'select-one':
  1364. case 'select':
  1365. ctl.Value = $(this).val() || '';
  1366. ctl.Html = $(this).html();
  1367. break;
  1368. }
  1369. cando.currentPageValue.push(ctl);
  1370. }
  1371. });
  1372. },
  1373. /**
  1374. * 取得Url參數
  1375. * @param {String} name 取得部分的名稱 例如輸入"Action"就能取到"Add"之類參數
  1376. * @return {Object} url參數
  1377. */
  1378. _getUrlParam: function (name) {
  1379. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"), //構造一個含有目標參數的正則表達式對象
  1380. r = w.location.search.substr(1).match(reg); //匹配目標參數
  1381. if (r !== null) {
  1382. return unescape(r[2]);//返回參數值
  1383. } else {
  1384. return null;
  1385. }
  1386. },
  1387. /**
  1388. * 創建程式Title
  1389. */
  1390. _createPageTitle: function () {
  1391. var cando = this,
  1392. handle = $('.page-title'),
  1393. programList = g_db.GetItem('programList'),
  1394. modTree = '',
  1395. modTrees = [],
  1396. setProgramPath = function (modid) {
  1397. var oParent = cando._getParentMod(modid);
  1398. if (oParent.ModuleID) {
  1399. modTrees.unshift('<div class="ng-scope layout-row"> <a class="md-button" href="#"><span class="ng-binding ng-scope" data-i18n=common.' + oParent.ModuleID + '></span></a> <i class="fa fa-angle-right" aria-hidden="true"></i> </div>');
  1400. }
  1401. if (oParent.ParentID) {
  1402. setProgramPath(oParent.ParentID);
  1403. }
  1404. };
  1405. if (programList === null || programList === '') { return; }
  1406. var programLists = $.parseJSON(programList),
  1407. curProgramList = programLists.filter(function (item) { return item.ModuleID === cando.ProgramId; });
  1408. if (curProgramList.length === 0) { return; }
  1409. var program = curProgramList[0];
  1410. if (!program.ParentID) { return; }
  1411. setProgramPath(program.ParentID);
  1412. modTrees.push('<div class="ng-scope layout-row"> <a class="md-button" href="#"><span class="ng-binding ng-scope" data-i18n=common.' + program.ModuleID + '></span></a> </div>');
  1413. modTree = modTrees.join(''); //串起父層路徑名稱
  1414. $.templates({
  1415. tmpl: '<div class="bread-crumbs layout-row ismobile" layout="row">\
  1416. {{: ModTree }}\
  1417. </div >\
  1418. <div class="title ismobile">\
  1419. <h2 data-i18n="{{:ProgramName}}"></h2>\
  1420. {{if showTable=="Y"}}<h5>(Use:{{:MainTableName}})</h5>{{/if}}\
  1421. </div>' });
  1422. handle.html($.render.tmpl({ ProgramName: "common." + program.ModuleID, showTable: parent.top.SysSet.TbShowOrHide, MainTableName: program.MainTableName, ModTree: modTree }));
  1423. cando._transLang(handle);
  1424. if (navigator.userAgent.match(/mobile/i)) {
  1425. $('.ismobile').hide();
  1426. }
  1427. },
  1428. /**
  1429. * 目的:恢復查詢條件
  1430. */
  1431. _reSetQueryPm: function () {
  1432. var cando = this,
  1433. qrParam = parent[cando.ProgramId + '_query'];
  1434. if (qrParam) {
  1435. cando._setFormVal(qrParam);
  1436. if (qrParam.pageidx) {
  1437. cando.options.queryPageidx = qrParam.pageidx;
  1438. }
  1439. }
  1440. },
  1441. /**
  1442. * 設定表單值
  1443. * @param {Object} json json對象
  1444. */
  1445. _setFormVal: function (json) {
  1446. var cando = this;
  1447. cando.form.find('[name]').each(function () {
  1448. var id = this.id,
  1449. name = this.name ? this.name.replace('[]', '') : '',
  1450. type = this.type,
  1451. value = json[name] || cando._getJsonVal(json, id) || '';
  1452. if (value) {
  1453. switch (type) {
  1454. case 'text':
  1455. case 'email':
  1456. case 'url':
  1457. case 'number':
  1458. case 'range':
  1459. case 'date':
  1460. case 'search':
  1461. case 'color':
  1462. case 'textarea':
  1463. case 'select-one':
  1464. case 'select':
  1465. case 'hidden':
  1466. var dataType = $(this).attr("data-type");
  1467. if (dataType && dataType === 'pop') {
  1468. var sVal_Name = json[name + 'Name'] || value;
  1469. $(this).attr("data-value", value);
  1470. if (sVal_Name) $(this).val(sVal_Name);
  1471. }
  1472. else {
  1473. if ($(this).hasClass('date-picker')) {
  1474. value = newDate(value, 'date');
  1475. }
  1476. else if ($(this).hasClass('date-picker') || $(this).hasClass('datetime-picker') || $(this).hasClass('date')) {
  1477. value = newDate(value);
  1478. }
  1479. if (value) $(this).val(value);
  1480. $(this).data('old', value);
  1481. if (dataType && dataType === 'int' && value) {
  1482. $(this).attr('data-value', value.toString().replace(/[^\d.]/g, ''));
  1483. }
  1484. }
  1485. if (dataType === 'select2') {
  1486. $(this).trigger("change", 'setval');
  1487. }
  1488. break;
  1489. case 'checkbox':
  1490. if (typeof value === 'object') {
  1491. if (value.indexOf(this.value) > -1) {
  1492. this.checked = value;
  1493. }
  1494. }
  1495. else {
  1496. this.checked = typeof value === 'string' ? value === this.value : value;
  1497. }
  1498. $.uniform && $.uniform.update($(this).prop("checked", this.checked));
  1499. break;
  1500. case 'radio':
  1501. this.checked = this.value === value;
  1502. $.uniform && $.uniform.update($(this).prop("checked", this.checked));
  1503. break;
  1504. }
  1505. if ((id === 'ModifyUserName' || id === 'CreateUserName') && 'select-one'.indexOf(this.type) === -1) {
  1506. $(this).text(value);
  1507. }
  1508. else if (id === 'ModifyDate' || id === 'CreateDate') {
  1509. $(this).text(newDate(value));
  1510. }
  1511. }
  1512. });
  1513. },
  1514. /**
  1515. * 取得自定義json值
  1516. * @param {Object} json json對象
  1517. * @param {Object} name json鍵值
  1518. * @return {String} last 最終要獲取的對應的鍵值對的值
  1519. */
  1520. _getJsonVal: function (json, name) {
  1521. var last = json,
  1522. names = name.split('_');
  1523. for (var i = 0; i < names.length; i++) {
  1524. if (!last[names[i]]) {
  1525. last = '';
  1526. break;
  1527. }
  1528. last = last[names[i]];
  1529. }
  1530. return last;
  1531. },
  1532. /**
  1533. * 取得url參數格式字串
  1534. * @param {Object} keys key值json對象
  1535. * @param {Object} from 資料來源
  1536. * @return {String} param 最終要獲取的參數格式字串
  1537. */
  1538. _getParamsStr: function (keys, from) {
  1539. var param = '';
  1540. for (var key in keys) {
  1541. param += '&' + key + '=' + encodeURIComponent(from[key]);
  1542. }
  1543. return param;
  1544. },
  1545. /**
  1546. * 清除畫面值
  1547. * @param {String} flag 是否為查詢清空查詢頁面須全部清空不保留原值
  1548. */
  1549. _clearPageVal: function () {
  1550. var cando = this,
  1551. pageval = cando.currentPageValue,
  1552. elQryBtn = $('#Toolbar_Qry');
  1553. for (var i = 0; i < pageval.length; i++) {
  1554. var ctl = pageval[i],
  1555. curInput = $("#" + ctl.ID),
  1556. ctlParent = curInput.parent();
  1557. try {
  1558. switch (ctl.Type) {
  1559. case 'text':
  1560. case 'email':
  1561. case 'url':
  1562. case 'number':
  1563. case 'range':
  1564. case 'date':
  1565. case 'search':
  1566. case 'color':
  1567. case 'password':
  1568. case 'hidden':
  1569. case 'textarea':
  1570. curInput.val(ctl.Value);
  1571. break;
  1572. case 'checkbox':
  1573. case 'radio':
  1574. curInput[0].checked = ctl.Checked;
  1575. $.uniform && $.uniform.update(curInput.prop("checked", curInput[0].checked));
  1576. break;
  1577. case 'select-multiple':
  1578. case 'select-one':
  1579. case 'select':
  1580. if (ctl.Html) {
  1581. curInput.html(ctl.Html);
  1582. }
  1583. curInput.val(ctl.Value);
  1584. if (curInput.attr('data-type') === 'select2') {
  1585. curInput.trigger('change', 'clear');
  1586. }
  1587. break;
  1588. }
  1589. } catch (e) {
  1590. alert(e);
  1591. }
  1592. }
  1593. if (elQryBtn.length > 0) {
  1594. $('#Toolbar_Qry').click();
  1595. }
  1596. },
  1597. /**
  1598. * 離開事件
  1599. * @return {boolean} 停止標記
  1600. */
  1601. _pageLeave: function () {
  1602. var cando = this,
  1603. intLeave = 0,
  1604. toLeave = function () {
  1605. parent.top.msgs.server.removeEditPrg(cando.ProgramId).done(function() {
  1606. if (intLeave === 1) {
  1607. var pPrevLi = parent.top.thisId.closest("li").prev().find('a'),
  1608. pLiId = parent.top.thisId.closest("li").remove().attr("aria-controls");
  1609. pPrevLi.click();
  1610. } else {
  1611. parent.top.openPageTab(cando.QueryPrgId);
  1612. }
  1613. })
  1614. };
  1615. if (typeof parent.top.editClose != "undefined") {
  1616. if(parent.top.editClose){
  1617. parent.top.editClose = false;
  1618. intLeave = 1;
  1619. }
  1620. }
  1621. //當被lock住,不儲存任何資料,直接離開。
  1622. if (parent.bLockDataForm0430 !== undefined)
  1623. toLeave();
  1624. if (w.bRequestStorage) {
  1625. layer.confirm(i18next.t('message.HasDataTosave'), {//╠message.HasDataTosave⇒尚有資料未儲存,是否要儲存?╣
  1626. icon: 3,
  1627. title: i18next.t('common.Tips'),// ╠message.Tips⇒提示╣
  1628. btn: [i18next.t('common.Yes'), i18next.t('common.No')] // ╠message.Yes⇒是╣ ╠common.No⇒否╣
  1629. }, function (index) {
  1630. layer.close(index);
  1631. w.bLeavePage = true;
  1632. $('#Toolbar_Save').click();
  1633. }, function () {
  1634. toLeave();
  1635. });
  1636. return false;
  1637. } else {
  1638. toLeave();
  1639. }
  1640. },
  1641. /**
  1642. * 緩存查詢條件
  1643. * @param {HTMLElement}form 表單物件
  1644. */
  1645. _cacheQueryCondition: function (form) {
  1646. var cando = this,
  1647. _form = form || cando.form,
  1648. prgid = cando.ProgramId || cando._getProgramId() || '',
  1649. qrParam = {};
  1650. cando.options.toFirstPage = false;
  1651. if (prgid) {
  1652. if (!parent[prgid + '_query']) {
  1653. parent[prgid + '_query'] = {};
  1654. }
  1655. if (typeof _form === 'number') {
  1656. parent[prgid + '_query'].pageidx = _form;
  1657. }
  1658. else {
  1659. var oQueryPm_Old = clone(parent[prgid + '_query']), key;
  1660. qrParam = cando._getFormSerialize();
  1661. for (key in qrParam) {
  1662. parent[prgid + '_query'][key] = qrParam[key];
  1663. }
  1664. for (key in oQueryPm_Old) {
  1665. if (key !== 'pageidx' && parent[prgid + '_query'][key] !== oQueryPm_Old[key]) {
  1666. cando.options.toFirstPage = true;
  1667. break;
  1668. }
  1669. }
  1670. }
  1671. }
  1672. },
  1673. /**
  1674. * 獲取當前服務器地址
  1675. * @return {String} 當前服務器地址
  1676. */
  1677. _getServerUrl: function () {
  1678. return w.location.origin || this._getHost();
  1679. },
  1680. /**
  1681. * 獲取當前服務器地址
  1682. * @return {String} 當前服務器地址
  1683. */
  1684. _getHost: function () {
  1685. var serverUrl = location.origin + '/';
  1686. if (!w.location.origin) {
  1687. serverUrl = w.location.protocol + "//" + w.location.hostname + (w.location.port ? ':' + w.location.port : '');
  1688. }
  1689. return serverUrl;
  1690. },
  1691. /**
  1692. * Toolbar物件
  1693. * @return {HTMLElement} New 一個Toolbar標籤
  1694. */
  1695. _getToolBar: function () {
  1696. return $('#Toolbar');
  1697. },
  1698. /**
  1699. * 獲取當前動作
  1700. * @return {String} add or upd
  1701. */
  1702. _getAction: function () {
  1703. var cando = this;
  1704. return cando._getUrlParam('Action') === null ? 'add' : cando._getUrlParam('Action').toLowerCase();
  1705. },
  1706. /**
  1707. * 下載文件
  1708. * @param {String} path 文件路徑相對路勁
  1709. * @param {String} filename 文件名稱
  1710. */
  1711. _downLoadFile: function (path, filename) {
  1712. var cando = this,
  1713. serverUrl = cando._getServerUrl(),
  1714. url = serverUrl + "/Controller.ashx";
  1715. url += '?action=downfile&path=' + path;
  1716. if (filename) {
  1717. url += '&filename=' + filename;
  1718. }
  1719. w.location.href = url;
  1720. cando._closeWaiting();
  1721. },
  1722. /**
  1723. * 開啟Waiting視窗
  1724. * @param {String} msg 提示文字
  1725. */
  1726. _showWaiting: function (msg) {
  1727. $.blockUI({
  1728. message: $('<div id="Divshowwaiting"><img src="/images/ajax-loader.gif">' + (msg || 'Waiting...') + '</div>'),
  1729. css: {
  1730. 'font-size': '36px',
  1731. border: '0px',
  1732. 'border-radius': '10px',
  1733. 'background-color': '#FFF',
  1734. padding: '15px 15px',
  1735. opacity: .5,
  1736. color: 'orange',
  1737. cursor: 'wait',
  1738. 'z-index': 1000000001
  1739. },
  1740. baseZ: 1000000000
  1741. });
  1742. w.setTimeout($.unblockUI, 60000);//預設開啟60秒後關閉
  1743. },
  1744. /**
  1745. * 關閉Waiting視窗
  1746. * @param {Number} sleep 延遲時間單位為毫秒
  1747. */
  1748. _closeWaiting: function (sleep) {
  1749. $(function () {
  1750. if (sleep === undefined) {
  1751. sleep = 100;
  1752. }
  1753. setTimeout($.unblockUI, sleep);
  1754. });
  1755. },
  1756. /**
  1757. * select2特殊化處理
  1758. * @param {Object} el select2控制項
  1759. */
  1760. _select2Init: function (el) {
  1761. var select2 = el === undefined ? $('select[data-type=select2]') : el.find('select[data-type=select2]');
  1762. //註冊客制化選單
  1763. if (select2.length > 0) {
  1764. select2.each(function () {
  1765. if ($(this).find('option').length > 0 && !$(this).attr('data-hasselect2')) {
  1766. $(this).select2().attr('data-hasselect2', true);
  1767. $(this).next().after($(this));
  1768. }
  1769. });
  1770. }
  1771. },
  1772. /**
  1773. * 目的異動模式點擊資料行彈出編輯按鈕
  1774. * @param {String} prgid 程式id
  1775. * @param {String} params 參數
  1776. */
  1777. _goToEdit: function (prgid, params) {
  1778. var cando = this;
  1779. parent.top.layer.open({
  1780. type: 1,
  1781. title: false,
  1782. area: ['100px', '70px'],//寬度
  1783. shade: 0.75,//遮罩
  1784. shadeClose: true,//╠common.Edit⇒編輯╣
  1785. content: '<div class="pop-box">\
  1786. <button type="button" data-i18n="common.Edit" id="RowEdit" class="btn-custom green">編輯</button>\
  1787. </div>',
  1788. success: function (layero, idx) {
  1789. layero.find('#RowEdit').click(function () {
  1790. parent.top.openPageTab(prgid, params);
  1791. parent.top.layer.close(idx);
  1792. });
  1793. cando._transLang(layero);
  1794. }
  1795. });
  1796. },
  1797. /**
  1798. * radio特殊化處理
  1799. * @param {Object} el 表單控制項
  1800. */
  1801. _uniformInit: function (el) {
  1802. var radio = $("input[type=radio]:not(.no-uniform)");
  1803. if (el) {
  1804. radio = el.find("input[type=radio]:not(.no-uniform)");
  1805. }
  1806. if (radio.length > 0) {
  1807. radio.each(function () {
  1808. $(this).uniform();
  1809. });
  1810. }
  1811. },
  1812. /**
  1813. * 目的:input文本處理
  1814. */
  1815. _keyInput: function () {
  1816. //只能輸入數字
  1817. if ($('[data-keyint]').length > 0) {
  1818. $('[data-keyint]').on('keyup blur', function (e) {
  1819. this.value = this.value.replace(/\D/g, '');
  1820. });
  1821. }
  1822. //只能输入英文
  1823. if ($('[data-keyeng]').length > 0) {
  1824. $('[data-keyeng]').on('keyup blur', function (e) {
  1825. this.value = this.value.replace(/[^a-zA-Z]/g, '');
  1826. });
  1827. }
  1828. //只能输入中文
  1829. if ($('[data-keyeng]').length > 0) {
  1830. $('[data-keyeng]').on('keyup blur', function (e) {
  1831. this.value = this.value.replace(/[^\u4E00-\u9FA5]/g, '');
  1832. });
  1833. }
  1834. //只能輸入數字和“-”,(手機/電話)
  1835. if ($('[data-keytelno]').length > 0) {
  1836. $('[data-keytelno]').on('keyup blur', function (e) {
  1837. if (e.keyCode !== 8 && e.keyCode !== 37 && e.keyCode !== 39 && e.keyCode !== 46) {
  1838. this.value = this.value.replace(/[^0-9\-\+\#\ ]/g, '');
  1839. }
  1840. });
  1841. }
  1842. //只能輸入數字和“-,+,#”
  1843. if ($('[data-keyintg]').length > 0) {
  1844. $('[data-keyintg]').on('keyup blur', function (e) {
  1845. this.value = this.value.replace(/[^0-9\-\+\#]/g, '');
  1846. });
  1847. }
  1848. //只允许输入英文
  1849. if ($('[data-keyeng]').length > 0) {
  1850. $('[data-keyeng]').on('keyup blur', function (e) {
  1851. this.value = this.value.replace(/[^\a-\z\A-\Z]/g, '');
  1852. });
  1853. }
  1854. //只能输入英文字母和数字,不能输入中文
  1855. if ($('[data-keyinteng]').length > 0) {
  1856. $('[data-keyinteng]').on('keyup blur', function (e) {
  1857. this.value = this.value.replace(/[^0-9\a-\z\A-\Z\_]/g, '');
  1858. });
  1859. }
  1860. //只能输入字母和汉字
  1861. if ($('[data-keycneng]').length > 0) {
  1862. $('[data-keycneng]').on('keyup blur', function (e) {
  1863. this.value = this.value.replace(/[/d]/g, '');
  1864. });
  1865. }
  1866. //帳號輸入規則
  1867. if ($('[data-keymemberid]').length > 0) {
  1868. $('[data-keymemberid]').on('keyup blur', function (e) {
  1869. this.value = this.value.replace(/[^\w\.\/]/ig, '');
  1870. });
  1871. }
  1872. //限制inout輸入長度
  1873. if ($('[_maxlength]').length > 0) {
  1874. $('[_maxlength]').each(function () {
  1875. var iPromiseLen = $(this).attr('_maxlength');
  1876. if (iPromiseLen) {
  1877. $(this).on('input propertychange', function () {
  1878. var sVal = this.value,
  1879. sVal_New = '',
  1880. iLen = 0,
  1881. i = 0;
  1882. for (; i < sVal.length; i++) {
  1883. if ((sVal.charCodeAt(i) & 0xff00) !== 0) {
  1884. iLen++;
  1885. }
  1886. iLen++;
  1887. if (iLen > iPromiseLen * 1) {
  1888. this.value = sVal_New;
  1889. break;
  1890. }
  1891. sVal_New += sVal[i];
  1892. }
  1893. });
  1894. }
  1895. });
  1896. }
  1897. },
  1898. /**
  1899. * 設定多於系
  1900. * @param {String} lng 語種
  1901. * @param {HTMLElement} el 要翻譯的html標籤
  1902. * @param {Function} callback 回調函數
  1903. */
  1904. _setLang: function (lng, el, callback) {
  1905. if (!lng) return;
  1906. g_ul.SetLang(lng);
  1907. i18next = "undefined" === typeof i18next ? parent.top.i18next : i18next;
  1908. var cando = this,
  1909. serverUrl = cando._getServerUrl();
  1910. $.getJSON(serverUrl + "/Scripts/lang/" + (parent.top.OrgID || 'TE') + "/" + lng + ".json?v=" + new Date().getTime().toString(), function (json) {
  1911. var resources = {};
  1912. resources[lng] = {
  1913. translation: json
  1914. };
  1915. i18next.init({
  1916. lng: lng,
  1917. resources: resources,
  1918. useLocalStorage: false, //是否将语言包存储在localstorage
  1919. //ns: { namespaces: ['trans'], defaultNs: 'trans' }, //加载的语言包
  1920. localStorageExpirationTime: 86400000 // 有效周期,单位ms。默认1
  1921. }, function (err, t) {
  1922. cando._transLang(el);
  1923. if (typeof callback === 'function') {
  1924. callback(t);
  1925. }
  1926. });
  1927. });
  1928. },
  1929. /**
  1930. * 翻譯語系
  1931. * @param {HTMLElement} dom 翻譯回調函數
  1932. */
  1933. _transLang: function (dom) {
  1934. i18next = "undefined" === typeof i18next ? parent.top.i18next : i18next;
  1935. var i18nHandle = dom === undefined ? $('[data-i18n]') : dom.find('[data-i18n]'),
  1936. i18nHandlePlaceholder = dom === undefined ? $('[placeholderid]') : dom.find('[placeholderid]');
  1937. i18nHandle.each(function (idx, el) {
  1938. var i18key = $(el).attr('data-i18n');
  1939. if (i18key) {
  1940. var sLan = i18next.t(i18key);
  1941. if (el.nodeName === 'INPUT' && el.type === 'button') {
  1942. $(el).val(sLan);
  1943. }
  1944. else {
  1945. $(el).html(sLan);
  1946. }
  1947. }
  1948. });
  1949. i18nHandlePlaceholder.each(function (idx, el) {
  1950. var i18key = $(el).attr("placeholderid");
  1951. if (i18key) {
  1952. var sLan = i18next.t(i18key);
  1953. if (sLan !== i18key) {
  1954. $(el).attr("placeholder", sLan);
  1955. }
  1956. }
  1957. });
  1958. },
  1959. /**
  1960. * 獲取UEEditor
  1961. * @param {Object} data 當前表單資料
  1962. * @return {Object} data 當前表單資料(含UE控件)
  1963. */
  1964. _getUEValues: function (data) {
  1965. var cando = this;
  1966. if (!$.isEmptyObject(cando.UE_Editor)) {
  1967. for (var key in cando.UE_Editor) {
  1968. data[key] = cando.UE_Editor[key].getContent();
  1969. }
  1970. }
  1971. return data;
  1972. },
  1973. /**
  1974. * 設置UEEditor
  1975. * @param {Object} data 當前編輯資料
  1976. */
  1977. _setUEValues: function (data) {
  1978. var cando = this,
  1979. readyToSet = function (_key) {
  1980. cando.UE_Editor[_key].ready(function () {
  1981. cando.UE_Editor[_key].setContent(data[_key] || '');
  1982. });
  1983. };
  1984. if (!$.isEmptyObject(cando.UE_Editor)) {
  1985. for (var key in cando.UE_Editor) {
  1986. readyToSet(key);
  1987. }
  1988. }
  1989. }
  1990. };
  1991. /**
  1992. * 產生guid
  1993. * @param {Number} len 指定长度,比如guid(8, 16) // "098F4D35"
  1994. * @param {Number} radix 基数
  1995. * @return {String} guid
  1996. */
  1997. w.guid = function (len, radix) {
  1998. var buf = new Uint16Array(8),
  1999. cryptObj = w.crypto || w.msCrypto, // For IE11
  2000. s4 = function (num) {
  2001. var ret = num.toString(16);
  2002. while (ret.length < 4) {
  2003. ret = '0' + ret;
  2004. }
  2005. return ret;
  2006. };
  2007. cryptObj.getRandomValues(buf);
  2008. return s4(buf[0]) + s4(buf[1]) + '-' + s4(buf[2]) + '-' + s4(buf[3]) + '-' +
  2009. s4(buf[4]) + '-' + s4(buf[5]) + s4(buf[6]) + s4(buf[7]);
  2010. };
  2011. /**
  2012. * 產生下拉選單公用
  2013. * @param {Object} list datalist
  2014. * @param {String} id 顯示的id名稱
  2015. * @param {String} name 顯示的name名稱
  2016. * @param {Boolean} showid 是否顯示id
  2017. * @param {String} cusattr 客制化添加屬性
  2018. * @param {Boolean} isreapet 是否允許重複
  2019. * @return {String} option html
  2020. */
  2021. w.createOptions = function (list, id, name, showid, cusattr, isreapet) {
  2022. isreapet = isreapet || true;
  2023. list = list || [];
  2024. var Options = [],
  2025. originAry = [];
  2026. if (typeof list === 'number') {
  2027. var intNum = list;
  2028. while (list > 0) {
  2029. var svalue = intNum - list + 1;
  2030. svalue = $.trim(svalue);
  2031. Options.push($('<option />', {
  2032. value: svalue,
  2033. title: svalue,
  2034. html: svalue
  2035. }));
  2036. list--;
  2037. }
  2038. } else {
  2039. Options = [$('<option />', { value: '', html: '請選擇...' })];
  2040. var intCount = list.length;
  2041. if (intCount > 0) {
  2042. $.each(list, function (idx, obj) {
  2043. if (isreapet !== false || originAry.indexOf($.trim(obj[id]) < 0 && isreapet === false)) {
  2044. var option = $('<option />', {
  2045. value: $.trim(obj[id]),
  2046. title: $.trim(obj[name]),
  2047. html: (showid ? $.trim(obj[id]) + '-' : '') + $.trim(obj[name])
  2048. });
  2049. if (cusattr) {
  2050. option.attr(cusattr, obj[cusattr]);
  2051. }
  2052. Options.push(option);
  2053. }
  2054. originAry.push($.trim(obj[id]));
  2055. });
  2056. }
  2057. }
  2058. return $('<div />').append(Options).html();
  2059. };
  2060. /**
  2061. * Radios公用
  2062. * @param {Object} list datalist
  2063. * @param {String} id 顯示的id名稱
  2064. * @param {String} name 顯示的name名稱
  2065. * @param {String} feilid 欄位ID
  2066. * @param {String} _id 客制化添加屬性
  2067. * @param {Boolean} showid 是否顯示id
  2068. * @param {Boolean} triggerattr 頁面加載後觸發change事件是否觸發提醒
  2069. * @return {String} sHtml Radios HTML
  2070. */
  2071. w.createRadios = function (list, id, name, feilid, _id, showid, triggerattr) {
  2072. list = list || [];
  2073. _id = _id || '';
  2074. triggerattr = triggerattr === false ? true : undefined;
  2075. var sHtml = '',
  2076. intCount = list.length;
  2077. if (intCount > 0) {
  2078. $.each(list, function (idx, obj) {
  2079. var sId = feilid + '_' + _id + '_' + idx,
  2080. inputradio = $('<input />', {
  2081. type: 'radio',
  2082. id: sId,
  2083. name: feilid,
  2084. 'data-trigger': triggerattr,
  2085. value: $.trim(obj[id])
  2086. }).attr('val', $.trim(obj[id]));
  2087. sHtml += '<label for="' + sId + '">' + inputradio[0].outerHTML + ((showid ? $.trim(obj[id]) + '-' : '') + $.trim(obj[name])) + "</label>";
  2088. });
  2089. }
  2090. return sHtml;
  2091. };
  2092. /**
  2093. * 產生CheckList公用
  2094. * @param {Object} list datalist
  2095. * @param {String} id 顯示的id名稱
  2096. * @param {String} name 顯示的name名稱
  2097. * @param {String} pmid 屬性id
  2098. * @param {String} _id id後邊擴展
  2099. * @return {String} sHtml CheckList HTML
  2100. */
  2101. w.createCheckList = function (list, id, name, pmid, _id) {
  2102. list = list || [];
  2103. var sHtml = '',
  2104. intCount = list.length;
  2105. if (intCount > 0) {
  2106. $.each(list, function (idx, obj) {
  2107. var inputradio = $('<input />', {
  2108. type: 'checkbox',
  2109. 'id': id + (_id === undefined ? '' : _id) + '_' + idx,
  2110. name: pmid + '[]',
  2111. value: $.trim(obj[id]),
  2112. 'class': 'input-mini'
  2113. });
  2114. sHtml += "<label for='" + id + (_id === undefined ? '' : _id) + '_' + idx + "' style='" + (intCount === idx + 1 ? '' : 'float:left;') + "padding-left: 10px'>" + inputradio[0].outerHTML + $.trim(obj[name]) + "</label>";
  2115. });
  2116. }
  2117. return sHtml;
  2118. };
  2119. /**
  2120. * 自適應
  2121. */
  2122. w.onresize = function () {
  2123. var sHeight = $('body').height();
  2124. if ($('#main-wrapper').length) {
  2125. $('#main-wrapper').css('min-height', sHeight - 88 + 'px');
  2126. }
  2127. setContentHeight();
  2128. };
  2129. w.fnframesize = function (down) {
  2130. var pTar = null;
  2131. if (d.getElementById) {
  2132. pTar = d.getElementById(down);
  2133. }
  2134. else {
  2135. eval('pTar = ' + down + ';');
  2136. }
  2137. if (pTar && !w.opera) {
  2138. pTar.style.display = "block";
  2139. if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight) {
  2140. //ns6 syntax
  2141. var iBody = $(d.body).outerHeight(true);
  2142. pTar.height = iBody - 125;
  2143. pTar.width = pTar.contentDocument.body.scrollWidth + 20;
  2144. }
  2145. else if (pTar.Document && pTar.Document.body.scrollHeight) {
  2146. pTar.height = pTar.Document.body.scrollHeight;
  2147. pTar.width = pTar.Document.body.scrollWidth;
  2148. }
  2149. }
  2150. };
  2151. w.setContentHeight = function () {
  2152. var fnIframeResize = function (h) {
  2153. var aryIframe = d.getElementsByTagName("iframe");
  2154. if (aryIframe === null) return;
  2155. for (var i = 0; i < aryIframe.length; i++) {
  2156. var Iframe = aryIframe[i];
  2157. if (Iframe.id.indexOf('ueditor_') === -1) {
  2158. Iframe.height = h;
  2159. }
  2160. }
  2161. },
  2162. content = $('.page-inner'),
  2163. pageContentHeight = $(d.body).outerHeight(true) - 110;
  2164. fnIframeResize(pageContentHeight);
  2165. };
  2166. /**
  2167. * 翻譯語系
  2168. * @param {HTMLElement} dom 要翻譯的html標籤
  2169. * @returns {Boolean} 停止標記
  2170. */
  2171. w.refreshLang = function (dom) {
  2172. if (dom && dom.length === 0) {
  2173. return false;
  2174. }
  2175. CanDo.fn._transLang(dom);
  2176. };
  2177. /**
  2178. * 用於表單序列化去除禁用欄位
  2179. * @param {HTMLElement} dom 父層物件
  2180. */
  2181. w.reFreshInput = function (dom) {
  2182. dom.find('[disabled]').each(function () {
  2183. $(this).attr('hasdisable', 1).removeAttr('disabled');
  2184. });
  2185. };
  2186. /**
  2187. * 用於表單序列化恢復禁用欄位
  2188. * @param {HTMLElement} dom 父層物件
  2189. */
  2190. w.reSetInput = function (dom) {
  2191. dom.find('[hasdisable]').each(function () {
  2192. $(this).removeAttr('hasdisable').prop('disabled', true);
  2193. });
  2194. };
  2195. /**
  2196. * 時間格式化處理
  2197. * @param {Date} date 日期時間
  2198. * @param {Boolean} type 格式日期 || 日期+時間
  2199. * @param {Boolean} empty 是否預設空
  2200. * @return {Boolean} 是否可傳回空
  2201. */
  2202. w.newDate = function (date, type, empty) {
  2203. var r = '';
  2204. if (date) {
  2205. if (typeof date === 'string') {
  2206. r = date.replace('T', ' ').replaceAll('-', '/');
  2207. if (r.indexOf(".") > -1) {
  2208. r = r.slice(0, r.indexOf("."));
  2209. }
  2210. }
  2211. else {
  2212. r = new Date(date);
  2213. }
  2214. r = new Date(r);
  2215. }
  2216. else {
  2217. if (!empty) {
  2218. r = new Date();
  2219. }
  2220. }
  2221. return r === '' ? '' : !type ? r.formate("yyyy/MM/dd HH:mm") : r.formate("yyyy/MM/dd");
  2222. };
  2223. /**
  2224. * 克隆对象
  2225. * @param {Object} obj 被轉換對象
  2226. * @return {Object} o 新對象
  2227. */
  2228. w.clone = function (obj) {
  2229. var o, i, j, k;
  2230. if (typeof obj !== "object" || obj === null) return obj;
  2231. if (obj instanceof Array) {
  2232. o = [];
  2233. i = 0; j = obj.length;
  2234. for (; i < j; i++) {
  2235. if (typeof obj[i] === "object" && obj[i] !== null) {
  2236. o[i] = arguments.callee(obj[i]);
  2237. }
  2238. else {
  2239. o[i] = obj[i];
  2240. }
  2241. }
  2242. }
  2243. else {
  2244. o = {};
  2245. for (i in obj) {
  2246. if (typeof obj[i] === "object" && obj[i] !== null) {
  2247. o[i] = arguments.callee(obj[i]);
  2248. }
  2249. else {
  2250. o[i] = obj[i];
  2251. }
  2252. }
  2253. }
  2254. return o;
  2255. };
  2256. /**
  2257. * 用於表單序列化恢復禁用欄位
  2258. * @param {HTMLElement} dom 要禁用的物件標籤
  2259. * @param {HTMLElement} notdom 不要禁用的物件標籤
  2260. * @param {Boolean} bdisabled 狀態
  2261. */
  2262. w.disableInput = function (dom, notdom, bdisabled) {
  2263. bdisabled = bdisabled === undefined || bdisabled === null ? true : bdisabled;
  2264. dom = dom.find(':input,select-one,select,checkbox,radio,textarea');
  2265. if (notdom) {
  2266. dom = dom.not(notdom);
  2267. }
  2268. dom.each(function () {
  2269. $(this).prop('disabled', bdisabled);
  2270. });
  2271. };
  2272. /**
  2273. * 獲取html模版
  2274. * @param {String} sUrl 模版路徑
  2275. * @param {Boolean} bAsync 是否同步
  2276. * @return {Object} Ajax對象
  2277. */
  2278. w.getHtmlTmp = function (sUrl, bAsync) {
  2279. return $.ajax({
  2280. async: true,
  2281. url: sUrl,
  2282. success: function (html) {
  2283. if (typeof callback === 'function') {
  2284. callback(html);
  2285. }
  2286. }
  2287. });
  2288. };
  2289. /**
  2290. * select2特殊化處理
  2291. * @param {Object} $d 表單控制項
  2292. */
  2293. w.uniformInit = function ($d) {
  2294. //var checkBox = $("input[type=checkbox]:not(.switchery), input[type=radio]:not(.no-uniform)");
  2295. var checkBox = $("input[type=radio]:not(.no-uniform)");
  2296. if ($d) {
  2297. checkBox = $d.find("input[type=radio]:not(.no-uniform)");
  2298. }
  2299. if (checkBox.length > 0) {
  2300. checkBox.each(function () {
  2301. $(this).uniform();
  2302. });
  2303. }
  2304. };
  2305. /**
  2306. * 修改文件
  2307. * @param {Object} file 文件信息
  2308. * @param {HTMLElement} el 文件對象
  2309. */
  2310. w.EditFile = function (file, el) {
  2311. layer.open({
  2312. type: 1,
  2313. title: i18next.t("common.EditFile"),// ╠common.EditFile⇒編輯文件信息╣
  2314. shade: 0.75,
  2315. maxmin: true, //开启最大化最小化按钮
  2316. area: ['500px', '350px'],
  2317. content: '<div class="pop-box">\
  2318. <div class="input-group input-append">\
  2319. <input type="text" maxlength="30" id="FileName" name="FileName" class="form-control w100p">\
  2320. <span class="input-group-addon add-on">\
  2321. </span>\
  2322. </div><br/>\
  2323. <div class="input-group w100p">\
  2324. <input type="text" maxlength="250" id="Link" name="Link" class="form-control w100p" placeholder="URL">\
  2325. </div><br/>\
  2326. <div class="input-group">\
  2327. <textarea name="FileDescription" id="FileDescription" class="form-control w100p" rows="5" cols="500"></textarea>\
  2328. </div>\
  2329. </div>',
  2330. btn: [i18next.t('common.Confirm'), i18next.t('common.Cancel')],//╠common.Confirm⇒確定╣╠common.Cancel⇒取消╣
  2331. success: function (layero, index) {
  2332. $('.pop-box .input-group-addon').text('.' + file.subname);
  2333. $('#FileName').val(file.filename);
  2334. $('#Link').val(file.link);
  2335. uniformInit(layero);//表單美化
  2336. },
  2337. yes: function (index, layero) {
  2338. var sFileName = $('#FileName').val(),
  2339. data = {
  2340. FileName: sFileName,
  2341. Link: $('#Link').val(),
  2342. Description: $('#FileDescription').val()
  2343. };
  2344. if (!data.FileName) {
  2345. showMsg(i18next.t("message.FileName_Required")); // ╠common.message⇒文件名稱不能為空╣
  2346. return false;
  2347. }
  2348. data.FileName += '.' + file.subname;
  2349. g_api.ConnectLite(Service.com, 'EditFile', data,
  2350. function (res) {
  2351. if (res.RESULT) {
  2352. file.filename = sFileName;
  2353. file.link = data.Link;
  2354. file.description = data.Description;
  2355. var img_title = el.find('.jFiler-item-title>b'),
  2356. img_name = el.find('.file-name li:first'),
  2357. img_description = el.find('.jFiler-item-description span');
  2358. if (img_title.length > 0) {
  2359. img_title.attr('title', data.FileName).text(data.FileName);
  2360. }
  2361. if (img_name.length > 0) {
  2362. img_name.text(data.FileName);
  2363. }
  2364. if (img_description.length > 0) {
  2365. img_description.text(data.Description);
  2366. }
  2367. layer.close(index);
  2368. showMsg(i18next.t("message.Modify_Success"), 'success'); //╠message.Modify_Success⇒修改成功╣
  2369. }
  2370. else {
  2371. showMsg(i18next.t("message.Modify_Failed"), 'error'); //╠message.Modify_Failed⇒修改失敗╣
  2372. }
  2373. });
  2374. }
  2375. });
  2376. };
  2377. /**
  2378. * 刪除文件
  2379. * @param {String} fileid 文件id
  2380. * @param {String} idtype id類型
  2381. * @param {String} balert id類型
  2382. * @return {Object} Ajax對象
  2383. */
  2384. w.DelFile = function (fileid, idtype, balert) {
  2385. balert = balert === undefined || balert === null ? true : balert;
  2386. if (fileid && $.trim(fileid)) {
  2387. return g_api.ConnectLite(Service.com, 'DelFile',
  2388. {
  2389. FileID: fileid,
  2390. IDType: idtype || ''
  2391. },
  2392. function (res) {
  2393. if (res.RESULT) {
  2394. if (balert) {
  2395. if (res.DATA.rel) {
  2396. showMsg(i18next.t("message.Delete_Success"), 'success'); // ╠message.Delete_Success⇒刪除成功╣
  2397. }
  2398. else {
  2399. showMsg(i18next.t("message.Delete_Failed"), 'error'); // ╠message.Delete_Failed⇒刪除失敗╣
  2400. }
  2401. }
  2402. }
  2403. else {
  2404. showMsg(i18next.t("message.Delete_Failed"), 'error'); // ╠message.Delete_Failed⇒刪除失敗╣
  2405. }
  2406. });
  2407. }
  2408. else {
  2409. return $.Deferred().resolve().promise();
  2410. }
  2411. };
  2412. /**
  2413. * select options 排序
  2414. * @param {String} set 要排序的select
  2415. * @param {String} get 獲取的select
  2416. * @param {HTMLElement} input 正序還是倒序
  2417. */
  2418. w.optionListSearch = function (set, get, input) {
  2419. //給左邊的每一項添加title效果
  2420. $('option', set).attr('title', function () {
  2421. return this.innerHTML;
  2422. });
  2423. //給右邊的每一項添加title效果
  2424. $('option', get).attr('title', function () {
  2425. return this.innerHTML;
  2426. });
  2427. var tempValue = set.html(), //儲存初始listbox值
  2428. searchtxt = '';
  2429. $.each(set.find('option'), function () {
  2430. if ($(this).val() + $(this).text() !== 'undefined') {
  2431. searchtxt += $(this).val() + '|' + $(this).text() + ',';
  2432. }
  2433. });
  2434. //給搜尋按鈕註冊事件
  2435. input.off('keyup').on('keyup', function () {
  2436. var sWord = this.value;
  2437. set.empty();
  2438. if (sWord !== "") {
  2439. $.each(searchtxt.split(','), function (key, val) {
  2440. if (val.toLowerCase().indexOf(sWord.toLowerCase()) >= 0) {
  2441. var setValue = val.split('|')[0];
  2442. var setText = val.split('|')[1];
  2443. set.append('<option value="' + setValue + '">' + setText + '</option>');
  2444. }
  2445. });
  2446. }
  2447. else {
  2448. set.html(tempValue); //搜尋欄位為空返還初始值(全部人員)
  2449. }
  2450. //移除右邊存在的值
  2451. if (get.html() !== '') {
  2452. $.each(get.find('option'), function () {
  2453. set.find('option[value=' + $(this).val().replace(".", "\\.") + ']').remove();
  2454. });
  2455. }
  2456. });
  2457. };
  2458. /**
  2459. * 透過代號或名稱快速查詢人員
  2460. * @param {String} set 要移出数据的jquery對象
  2461. * @param {String} get 要移入数据的jquery對象
  2462. */
  2463. w.optionListMove = function (set, get) {
  2464. var size = set.find("option").size();
  2465. var selsize = set.find("option:selected").size();
  2466. if (size > 0 && selsize > 0) {
  2467. set.find("option:selected").each(function () {
  2468. $(this).prependTo(get);
  2469. });
  2470. }
  2471. };
  2472. /**
  2473. * 目的設置滾動條
  2474. * @param {Number} h 高度
  2475. * @param {Number} c 定位點
  2476. */
  2477. w.slimScroll = function (h, c) {
  2478. if ($.fn.slimScroll) {
  2479. var option = {
  2480. allowPageScroll: true,
  2481. color: '#ee7624',
  2482. opacity: 1
  2483. };
  2484. if (h) {
  2485. option.height = h;
  2486. }
  2487. if (c) {
  2488. option.reduce = c;
  2489. }
  2490. $('.slimscroll').slimscroll(option);
  2491. }
  2492. };
  2493. /**
  2494. * 參數添加修改人/時間創建人/時間
  2495. * @param {Object} data 表單資料
  2496. * @param {String} type 是否是修改
  2497. * @return {Object} data 表單資料
  2498. */
  2499. w.packParams = function (data, type) {
  2500. data.ModifyUser = parent.top.UserInfo.MemberID;
  2501. data.ModifyDate = new Date().formate('yyyy/MM/dd HH:mm');
  2502. if (!type) {
  2503. data.CreateUser = data.ModifyUser;
  2504. data.CreateDate = data.ModifyDate;
  2505. }
  2506. return data;
  2507. };
  2508. /**
  2509. * 下載文件
  2510. * @param {String} path 文件路徑相對路勁
  2511. * @param {String} filename 文件名稱
  2512. */
  2513. w.DownLoadFile = function (path, filename) {
  2514. var sUrl = gServerUrl + "/Controller.ashx";
  2515. sUrl += '?action=downfile&path=' + path;
  2516. if (filename) {
  2517. sUrl += '&filename=' + filename;
  2518. }
  2519. w.location.href = sUrl;
  2520. CanDo.fn._closeWaiting();
  2521. };
  2522. /**
  2523. * 取得host
  2524. */
  2525. w.gServerUrl = CanDo.fn._getServerUrl();
  2526. /**
  2527. * 定義系統所有公用 Service.fnction
  2528. */
  2529. w.ComFn = {
  2530. W_Com: 'comw',
  2531. GetList: 'QueryList',
  2532. GetAdd: 'Add',
  2533. GetUpd: 'Update',
  2534. GetDel: 'Delete',
  2535. GetUserList: 'GetUserList',
  2536. GetArguments: 'GetArguments'
  2537. };
  2538. w.Service = CanDo.fn._service;
  2539. w.transLang = CanDo.fn._transLang;
  2540. function onStart(e) {
  2541. CanDo.fn._showWaiting(typeof IsWaiting === 'string' ? IsWaiting : undefined);
  2542. }
  2543. function onStop(e) {
  2544. CanDo.fn._closeWaiting();
  2545. setTimeout(function () { IsWaiting = null; }, 3000);
  2546. }
  2547. $(d).ajaxStart(onStart).ajaxStop(onStop);
  2548. CanDo.fn._init.prototype = CanDo.fn;
  2549. return CanDo;
  2550. })(window, document);
  2551. /**
  2552. * 日期添加屬性
  2553. * @param {String} type y:;q:季度;m:;w:星期;d:;h:小時;n:;s:;ms:毫秒;
  2554. * @param {Number} num 添加的數值
  2555. * @return {Date} r 新的時間
  2556. */
  2557. Date.prototype.dateAdd = function (type, num) {
  2558. var r = this,
  2559. k = { y: 'FullYear', q: 'Month', m: 'Month', w: 'Date', d: 'Date', h: 'Hours', n: 'Minutes', s: 'Seconds', ms: 'MilliSeconds' },
  2560. n = { q: 3, w: 7 };
  2561. eval('r.set' + k[type] + '(r.get' + k[type] + '()+' + (n[type] || 1) * num + ')');
  2562. return r;
  2563. };
  2564. /**
  2565. * 計算兩個日期的天數
  2566. * @param {Object} date 第二個日期;
  2567. * @return {Number} 時間差
  2568. */
  2569. Date.prototype.diff = function (date) {
  2570. return (this.getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
  2571. };
  2572. /**
  2573. * 对Date的扩展 Date 转化为指定格式的String
  2574. * (M)(d)12小时(h)24小时(H)(m)(s)(E)季度(q) 可以用 1-2 个占位符
  2575. * (y)可以用 1-4 个占位符毫秒(S)只能用 1 个占位符( 1-3 位的数字)
  2576. * eg:
  2577. * (new Date()).formate("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  2578. * (new Date()).formate("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 20:09:04
  2579. * (new Date()).formate("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
  2580. * (new Date()).formate("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
  2581. * (new Date()).formate("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
  2582. * @param {String} fmt 格式字串;
  2583. * @return {Date} fmt 新的時間
  2584. */
  2585. Date.prototype.formate = function (fmt) {
  2586. var o = {
  2587. "M+": this.getMonth() + 1, //月份
  2588. "d+": this.getDate(), //日
  2589. "h+": this.getHours() % 12 === 0 ? 12 : this.getHours() % 12, //小时
  2590. "H+": this.getHours(), //小时
  2591. "m+": this.getMinutes(), //分
  2592. "s+": this.getSeconds(), //秒
  2593. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  2594. "S": this.getMilliseconds() //毫秒
  2595. };
  2596. var week = {
  2597. "0": "\u65e5",
  2598. "1": "\u4e00",
  2599. "2": "\u4e8c",
  2600. "3": "\u4e09",
  2601. "4": "\u56db",
  2602. "5": "\u4e94",
  2603. "6": "\u516d"
  2604. };
  2605. if (/(y+)/.test(fmt)) {
  2606. fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  2607. }
  2608. if (/(E+)/.test(fmt)) {
  2609. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length > 1 ? RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468" : "") + week[this.getDay() + ""]);
  2610. }
  2611. for (var k in o) {
  2612. if (new RegExp("(" + k + ")").test(fmt)) {
  2613. fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  2614. }
  2615. }
  2616. return fmt;
  2617. };
  2618. /**
  2619. * 註冊全替換
  2620. * @param {String} s1 字串1
  2621. * @param {String} s2 字串2
  2622. * @return {String} 替換後的新字串
  2623. */
  2624. String.prototype.replaceAll = function (s1, s2) {
  2625. return this.replace(new RegExp(s1, "gm"), s2);
  2626. };
  2627. /**
  2628. * 註冊金額添加三位一撇
  2629. * @return {String}三位一撇字串
  2630. */
  2631. String.prototype.toMoney = Number.prototype.toMoney = function () {
  2632. return this.toString().replace(/\d+?(?=(?:\d{3})+$)/g, function (s) {
  2633. return s + ',';
  2634. });
  2635. };
  2636. /**
  2637. * 数字四舍五入保留n位小数
  2638. * @param {Number} n 保留n位
  2639. * @return {Number} number 數值
  2640. */
  2641. String.prototype.toFloat = Number.prototype.toFloat = function (n) {
  2642. n = n ? parseInt(n) : 0;
  2643. var number = this;
  2644. if (n <= 0) return Math.round(number);
  2645. number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n);
  2646. return number;
  2647. };
  2648. /**
  2649. * 百分数转小数
  2650. * @return {Number} 百分数
  2651. */
  2652. String.prototype.toPoint = function () {
  2653. return this.replace("%", "") / 100;
  2654. };
  2655. /**
  2656. * 小数转化为分数
  2657. * @return {String} percent 百分数
  2658. */
  2659. String.prototype.toPercent = Number.prototype.toPercent = function () {
  2660. var percent = Number(this * 100).toFixed(1);
  2661. percent += "%";
  2662. return percent;
  2663. };
  2664. /**
  2665. * 刪除陣列內包含(undefined, null, 0, false, NaN and '')的資料
  2666. * @return {Array} 新陣列
  2667. */
  2668. Array.prototype.clear = function () {
  2669. var newArray = [];
  2670. for (var i = 0; i < this.length; i++) {
  2671. if (this[i]) {
  2672. newArray.push(this[i]);
  2673. }
  2674. }
  2675. return newArray;
  2676. };
  2677. /**
  2678. * 在數組指定位置添加元素
  2679. * @param {Number} index 位置
  2680. * @param {Object} item 要添加的元素
  2681. */
  2682. Array.prototype.insert = function (index, item) {
  2683. this.splice(index, 0, item);
  2684. };
  2685. /**
  2686. * 刪除陣列內指定元素
  2687. * @param {String} val 元素
  2688. */
  2689. Array.prototype.remove = function (val) {
  2690. var index = this.indexOf(val);
  2691. if (index > -1) {
  2692. this.splice(index, 1);
  2693. }
  2694. };
  2695. /**
  2696. * 方法陣列內等待
  2697. * @param {Array} array 執行方法陣列
  2698. * @return {Object} Ajax 對象
  2699. */
  2700. jQuery.whenArray = function (array) {
  2701. return jQuery.when.apply(this, array);
  2702. };