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.

2829 lines
108 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. toLeave = function () {
  1604. parent.top.openPageTab(cando.QueryPrgId);
  1605. parent.top.msgs.server.removeEditPrg(cando.ProgramId);
  1606. };
  1607. //當被lock住,不儲存任何資料,直接離開。
  1608. if (parent.bLockDataForm0430 !== undefined)
  1609. toLeave();
  1610. if (w.bRequestStorage) {
  1611. layer.confirm(i18next.t('message.HasDataTosave'), {//╠message.HasDataTosave⇒尚有資料未儲存,是否要儲存?╣
  1612. icon: 3,
  1613. title: i18next.t('common.Tips'),// ╠message.Tips⇒提示╣
  1614. btn: [i18next.t('common.Yes'), i18next.t('common.No')] // ╠message.Yes⇒是╣ ╠common.No⇒否╣
  1615. }, function (index) {
  1616. layer.close(index);
  1617. w.bLeavePage = true;
  1618. $('#Toolbar_Save').click();
  1619. }, function () {
  1620. toLeave();
  1621. });
  1622. return false;
  1623. }
  1624. toLeave();
  1625. },
  1626. /**
  1627. * 緩存查詢條件
  1628. * @param {HTMLElement}form 表單物件
  1629. */
  1630. _cacheQueryCondition: function (form) {
  1631. var cando = this,
  1632. _form = form || cando.form,
  1633. prgid = cando.ProgramId || cando._getProgramId() || '',
  1634. qrParam = {};
  1635. cando.options.toFirstPage = false;
  1636. if (prgid) {
  1637. if (!parent[prgid + '_query']) {
  1638. parent[prgid + '_query'] = {};
  1639. }
  1640. if (typeof _form === 'number') {
  1641. parent[prgid + '_query'].pageidx = _form;
  1642. }
  1643. else {
  1644. var oQueryPm_Old = clone(parent[prgid + '_query']), key;
  1645. qrParam = cando._getFormSerialize();
  1646. for (key in qrParam) {
  1647. parent[prgid + '_query'][key] = qrParam[key];
  1648. }
  1649. for (key in oQueryPm_Old) {
  1650. if (key !== 'pageidx' && parent[prgid + '_query'][key] !== oQueryPm_Old[key]) {
  1651. cando.options.toFirstPage = true;
  1652. break;
  1653. }
  1654. }
  1655. }
  1656. }
  1657. },
  1658. /**
  1659. * 獲取當前服務器地址
  1660. * @return {String} 當前服務器地址
  1661. */
  1662. _getServerUrl: function () {
  1663. return w.location.origin || this._getHost();
  1664. },
  1665. /**
  1666. * 獲取當前服務器地址
  1667. * @return {String} 當前服務器地址
  1668. */
  1669. _getHost: function () {
  1670. var serverUrl = location.origin + '/';
  1671. if (!w.location.origin) {
  1672. serverUrl = w.location.protocol + "//" + w.location.hostname + (w.location.port ? ':' + w.location.port : '');
  1673. }
  1674. return serverUrl;
  1675. },
  1676. /**
  1677. * Toolbar物件
  1678. * @return {HTMLElement} New 一個Toolbar標籤
  1679. */
  1680. _getToolBar: function () {
  1681. return $('#Toolbar');
  1682. },
  1683. /**
  1684. * 獲取當前動作
  1685. * @return {String} add or upd
  1686. */
  1687. _getAction: function () {
  1688. var cando = this;
  1689. return cando._getUrlParam('Action') === null ? 'add' : cando._getUrlParam('Action').toLowerCase();
  1690. },
  1691. /**
  1692. * 下載文件
  1693. * @param {String} path 文件路徑相對路勁
  1694. * @param {String} filename 文件名稱
  1695. */
  1696. _downLoadFile: function (path, filename) {
  1697. var cando = this,
  1698. serverUrl = cando._getServerUrl(),
  1699. url = serverUrl + "/Controller.ashx";
  1700. url += '?action=downfile&path=' + path;
  1701. if (filename) {
  1702. url += '&filename=' + filename;
  1703. }
  1704. w.location.href = url;
  1705. cando._closeWaiting();
  1706. },
  1707. /**
  1708. * 開啟Waiting視窗
  1709. * @param {String} msg 提示文字
  1710. */
  1711. _showWaiting: function (msg) {
  1712. $.blockUI({
  1713. message: $('<div id="Divshowwaiting"><img src="/images/ajax-loader.gif">' + (msg || 'Waiting...') + '</div>'),
  1714. css: {
  1715. 'font-size': '36px',
  1716. border: '0px',
  1717. 'border-radius': '10px',
  1718. 'background-color': '#FFF',
  1719. padding: '15px 15px',
  1720. opacity: .5,
  1721. color: 'orange',
  1722. cursor: 'wait',
  1723. 'z-index': 1000000001
  1724. },
  1725. baseZ: 1000000000
  1726. });
  1727. w.setTimeout($.unblockUI, 60000);//預設開啟60秒後關閉
  1728. },
  1729. /**
  1730. * 關閉Waiting視窗
  1731. * @param {Number} sleep 延遲時間單位為毫秒
  1732. */
  1733. _closeWaiting: function (sleep) {
  1734. $(function () {
  1735. if (sleep === undefined) {
  1736. sleep = 100;
  1737. }
  1738. setTimeout($.unblockUI, sleep);
  1739. });
  1740. },
  1741. /**
  1742. * select2特殊化處理
  1743. * @param {Object} el select2控制項
  1744. */
  1745. _select2Init: function (el) {
  1746. var select2 = el === undefined ? $('select[data-type=select2]') : el.find('select[data-type=select2]');
  1747. //註冊客制化選單
  1748. if (select2.length > 0) {
  1749. select2.each(function () {
  1750. if ($(this).find('option').length > 0 && !$(this).attr('data-hasselect2')) {
  1751. $(this).select2().attr('data-hasselect2', true);
  1752. $(this).next().after($(this));
  1753. }
  1754. });
  1755. }
  1756. },
  1757. /**
  1758. * 目的異動模式點擊資料行彈出編輯按鈕
  1759. * @param {String} prgid 程式id
  1760. * @param {String} params 參數
  1761. */
  1762. _goToEdit: function (prgid, params) {
  1763. var cando = this;
  1764. parent.top.layer.open({
  1765. type: 1,
  1766. title: false,
  1767. area: ['100px', '70px'],//寬度
  1768. shade: 0.75,//遮罩
  1769. shadeClose: true,//╠common.Edit⇒編輯╣
  1770. content: '<div class="pop-box">\
  1771. <button type="button" data-i18n="common.Edit" id="RowEdit" class="btn-custom green">編輯</button>\
  1772. </div>',
  1773. success: function (layero, idx) {
  1774. layero.find('#RowEdit').click(function () {
  1775. parent.top.openPageTab(prgid, params);
  1776. parent.top.layer.close(idx);
  1777. });
  1778. cando._transLang(layero);
  1779. }
  1780. });
  1781. },
  1782. /**
  1783. * radio特殊化處理
  1784. * @param {Object} el 表單控制項
  1785. */
  1786. _uniformInit: function (el) {
  1787. var radio = $("input[type=radio]:not(.no-uniform)");
  1788. if (el) {
  1789. radio = el.find("input[type=radio]:not(.no-uniform)");
  1790. }
  1791. if (radio.length > 0) {
  1792. radio.each(function () {
  1793. $(this).uniform();
  1794. });
  1795. }
  1796. },
  1797. /**
  1798. * 目的:input文本處理
  1799. */
  1800. _keyInput: function () {
  1801. //只能輸入數字
  1802. if ($('[data-keyint]').length > 0) {
  1803. $('[data-keyint]').on('keyup blur', function (e) {
  1804. this.value = this.value.replace(/\D/g, '');
  1805. });
  1806. }
  1807. //只能输入英文
  1808. if ($('[data-keyeng]').length > 0) {
  1809. $('[data-keyeng]').on('keyup blur', function (e) {
  1810. this.value = this.value.replace(/[^a-zA-Z]/g, '');
  1811. });
  1812. }
  1813. //只能输入中文
  1814. if ($('[data-keyeng]').length > 0) {
  1815. $('[data-keyeng]').on('keyup blur', function (e) {
  1816. this.value = this.value.replace(/[^\u4E00-\u9FA5]/g, '');
  1817. });
  1818. }
  1819. //只能輸入數字和“-”,(手機/電話)
  1820. if ($('[data-keytelno]').length > 0) {
  1821. $('[data-keytelno]').on('keyup blur', function (e) {
  1822. if (e.keyCode !== 8 && e.keyCode !== 37 && e.keyCode !== 39 && e.keyCode !== 46) {
  1823. this.value = this.value.replace(/[^0-9\-\+\#\ ]/g, '');
  1824. }
  1825. });
  1826. }
  1827. //只能輸入數字和“-,+,#”
  1828. if ($('[data-keyintg]').length > 0) {
  1829. $('[data-keyintg]').on('keyup blur', function (e) {
  1830. this.value = this.value.replace(/[^0-9\-\+\#]/g, '');
  1831. });
  1832. }
  1833. //只允许输入英文
  1834. if ($('[data-keyeng]').length > 0) {
  1835. $('[data-keyeng]').on('keyup blur', function (e) {
  1836. this.value = this.value.replace(/[^\a-\z\A-\Z]/g, '');
  1837. });
  1838. }
  1839. //只能输入英文字母和数字,不能输入中文
  1840. if ($('[data-keyinteng]').length > 0) {
  1841. $('[data-keyinteng]').on('keyup blur', function (e) {
  1842. this.value = this.value.replace(/[^0-9\a-\z\A-\Z\_]/g, '');
  1843. });
  1844. }
  1845. //只能输入字母和汉字
  1846. if ($('[data-keycneng]').length > 0) {
  1847. $('[data-keycneng]').on('keyup blur', function (e) {
  1848. this.value = this.value.replace(/[/d]/g, '');
  1849. });
  1850. }
  1851. //帳號輸入規則
  1852. if ($('[data-keymemberid]').length > 0) {
  1853. $('[data-keymemberid]').on('keyup blur', function (e) {
  1854. this.value = this.value.replace(/[^\w\.\/]/ig, '');
  1855. });
  1856. }
  1857. //限制inout輸入長度
  1858. if ($('[_maxlength]').length > 0) {
  1859. $('[_maxlength]').each(function () {
  1860. var iPromiseLen = $(this).attr('_maxlength');
  1861. if (iPromiseLen) {
  1862. $(this).on('input propertychange', function () {
  1863. var sVal = this.value,
  1864. sVal_New = '',
  1865. iLen = 0,
  1866. i = 0;
  1867. for (; i < sVal.length; i++) {
  1868. if ((sVal.charCodeAt(i) & 0xff00) !== 0) {
  1869. iLen++;
  1870. }
  1871. iLen++;
  1872. if (iLen > iPromiseLen * 1) {
  1873. this.value = sVal_New;
  1874. break;
  1875. }
  1876. sVal_New += sVal[i];
  1877. }
  1878. });
  1879. }
  1880. });
  1881. }
  1882. },
  1883. /**
  1884. * 設定多於系
  1885. * @param {String} lng 語種
  1886. * @param {HTMLElement} el 要翻譯的html標籤
  1887. * @param {Function} callback 回調函數
  1888. */
  1889. _setLang: function (lng, el, callback) {
  1890. if (!lng) return;
  1891. g_ul.SetLang(lng);
  1892. i18next = "undefined" === typeof i18next ? parent.top.i18next : i18next;
  1893. var cando = this,
  1894. serverUrl = cando._getServerUrl();
  1895. $.getJSON(serverUrl + "/Scripts/lang/" + (parent.top.OrgID || 'TE') + "/" + lng + ".json?v=" + new Date().getTime().toString(), function (json) {
  1896. var resources = {};
  1897. resources[lng] = {
  1898. translation: json
  1899. };
  1900. i18next.init({
  1901. lng: lng,
  1902. resources: resources,
  1903. useLocalStorage: false, //是否将语言包存储在localstorage
  1904. //ns: { namespaces: ['trans'], defaultNs: 'trans' }, //加载的语言包
  1905. localStorageExpirationTime: 86400000 // 有效周期,单位ms。默认1
  1906. }, function (err, t) {
  1907. cando._transLang(el);
  1908. if (typeof callback === 'function') {
  1909. callback(t);
  1910. }
  1911. });
  1912. });
  1913. },
  1914. /**
  1915. * 翻譯語系
  1916. * @param {HTMLElement} dom 翻譯回調函數
  1917. */
  1918. _transLang: function (dom) {
  1919. i18next = "undefined" === typeof i18next ? parent.top.i18next : i18next;
  1920. var i18nHandle = dom === undefined ? $('[data-i18n]') : dom.find('[data-i18n]'),
  1921. i18nHandlePlaceholder = dom === undefined ? $('[placeholderid]') : dom.find('[placeholderid]');
  1922. i18nHandle.each(function (idx, el) {
  1923. var i18key = $(el).attr('data-i18n');
  1924. if (i18key) {
  1925. var sLan = i18next.t(i18key);
  1926. if (el.nodeName === 'INPUT' && el.type === 'button') {
  1927. $(el).val(sLan);
  1928. }
  1929. else {
  1930. $(el).html(sLan);
  1931. }
  1932. }
  1933. });
  1934. i18nHandlePlaceholder.each(function (idx, el) {
  1935. var i18key = $(el).attr("placeholderid");
  1936. if (i18key) {
  1937. var sLan = i18next.t(i18key);
  1938. if (sLan !== i18key) {
  1939. $(el).attr("placeholder", sLan);
  1940. }
  1941. }
  1942. });
  1943. },
  1944. /**
  1945. * 獲取UEEditor
  1946. * @param {Object} data 當前表單資料
  1947. * @return {Object} data 當前表單資料(含UE控件)
  1948. */
  1949. _getUEValues: function (data) {
  1950. var cando = this;
  1951. if (!$.isEmptyObject(cando.UE_Editor)) {
  1952. for (var key in cando.UE_Editor) {
  1953. data[key] = cando.UE_Editor[key].getContent();
  1954. }
  1955. }
  1956. return data;
  1957. },
  1958. /**
  1959. * 設置UEEditor
  1960. * @param {Object} data 當前編輯資料
  1961. */
  1962. _setUEValues: function (data) {
  1963. var cando = this,
  1964. readyToSet = function (_key) {
  1965. cando.UE_Editor[_key].ready(function () {
  1966. cando.UE_Editor[_key].setContent(data[_key] || '');
  1967. });
  1968. };
  1969. if (!$.isEmptyObject(cando.UE_Editor)) {
  1970. for (var key in cando.UE_Editor) {
  1971. readyToSet(key);
  1972. }
  1973. }
  1974. }
  1975. };
  1976. /**
  1977. * 產生guid
  1978. * @param {Number} len 指定长度,比如guid(8, 16) // "098F4D35"
  1979. * @param {Number} radix 基数
  1980. * @return {String} guid
  1981. */
  1982. w.guid = function (len, radix) {
  1983. var buf = new Uint16Array(8),
  1984. cryptObj = w.crypto || w.msCrypto, // For IE11
  1985. s4 = function (num) {
  1986. var ret = num.toString(16);
  1987. while (ret.length < 4) {
  1988. ret = '0' + ret;
  1989. }
  1990. return ret;
  1991. };
  1992. cryptObj.getRandomValues(buf);
  1993. return s4(buf[0]) + s4(buf[1]) + '-' + s4(buf[2]) + '-' + s4(buf[3]) + '-' +
  1994. s4(buf[4]) + '-' + s4(buf[5]) + s4(buf[6]) + s4(buf[7]);
  1995. };
  1996. /**
  1997. * 產生下拉選單公用
  1998. * @param {Object} list datalist
  1999. * @param {String} id 顯示的id名稱
  2000. * @param {String} name 顯示的name名稱
  2001. * @param {Boolean} showid 是否顯示id
  2002. * @param {String} cusattr 客制化添加屬性
  2003. * @param {Boolean} isreapet 是否允許重複
  2004. * @return {String} option html
  2005. */
  2006. w.createOptions = function (list, id, name, showid, cusattr, isreapet) {
  2007. isreapet = isreapet || true;
  2008. list = list || [];
  2009. var Options = [],
  2010. originAry = [];
  2011. if (typeof list === 'number') {
  2012. var intNum = list;
  2013. while (list > 0) {
  2014. var svalue = intNum - list + 1;
  2015. svalue = $.trim(svalue);
  2016. Options.push($('<option />', {
  2017. value: svalue,
  2018. title: svalue,
  2019. html: svalue
  2020. }));
  2021. list--;
  2022. }
  2023. } else {
  2024. Options = [$('<option />', { value: '', html: '請選擇...' })];
  2025. var intCount = list.length;
  2026. if (intCount > 0) {
  2027. $.each(list, function (idx, obj) {
  2028. if (isreapet !== false || originAry.indexOf($.trim(obj[id]) < 0 && isreapet === false)) {
  2029. var option = $('<option />', {
  2030. value: $.trim(obj[id]),
  2031. title: $.trim(obj[name]),
  2032. html: (showid ? $.trim(obj[id]) + '-' : '') + $.trim(obj[name])
  2033. });
  2034. if (cusattr) {
  2035. option.attr(cusattr, obj[cusattr]);
  2036. }
  2037. Options.push(option);
  2038. }
  2039. originAry.push($.trim(obj[id]));
  2040. });
  2041. }
  2042. }
  2043. return $('<div />').append(Options).html();
  2044. };
  2045. /**
  2046. * Radios公用
  2047. * @param {Object} list datalist
  2048. * @param {String} id 顯示的id名稱
  2049. * @param {String} name 顯示的name名稱
  2050. * @param {String} feilid 欄位ID
  2051. * @param {String} _id 客制化添加屬性
  2052. * @param {Boolean} showid 是否顯示id
  2053. * @param {Boolean} triggerattr 頁面加載後觸發change事件是否觸發提醒
  2054. * @return {String} sHtml Radios HTML
  2055. */
  2056. w.createRadios = function (list, id, name, feilid, _id, showid, triggerattr) {
  2057. list = list || [];
  2058. _id = _id || '';
  2059. triggerattr = triggerattr === false ? true : undefined;
  2060. var sHtml = '',
  2061. intCount = list.length;
  2062. if (intCount > 0) {
  2063. $.each(list, function (idx, obj) {
  2064. var sId = feilid + '_' + _id + '_' + idx,
  2065. inputradio = $('<input />', {
  2066. type: 'radio',
  2067. id: sId,
  2068. name: feilid,
  2069. 'data-trigger': triggerattr,
  2070. value: $.trim(obj[id])
  2071. }).attr('val', $.trim(obj[id]));
  2072. sHtml += '<label for="' + sId + '">' + inputradio[0].outerHTML + ((showid ? $.trim(obj[id]) + '-' : '') + $.trim(obj[name])) + "</label>";
  2073. });
  2074. }
  2075. return sHtml;
  2076. };
  2077. /**
  2078. * 產生CheckList公用
  2079. * @param {Object} list datalist
  2080. * @param {String} id 顯示的id名稱
  2081. * @param {String} name 顯示的name名稱
  2082. * @param {String} pmid 屬性id
  2083. * @param {String} _id id後邊擴展
  2084. * @return {String} sHtml CheckList HTML
  2085. */
  2086. w.createCheckList = function (list, id, name, pmid, _id) {
  2087. list = list || [];
  2088. var sHtml = '',
  2089. intCount = list.length;
  2090. if (intCount > 0) {
  2091. $.each(list, function (idx, obj) {
  2092. var inputradio = $('<input />', {
  2093. type: 'checkbox',
  2094. 'id': id + (_id === undefined ? '' : _id) + '_' + idx,
  2095. name: pmid + '[]',
  2096. value: $.trim(obj[id]),
  2097. 'class': 'input-mini'
  2098. });
  2099. sHtml += "<label for='" + id + (_id === undefined ? '' : _id) + '_' + idx + "' style='" + (intCount === idx + 1 ? '' : 'float:left;') + "padding-left: 10px'>" + inputradio[0].outerHTML + $.trim(obj[name]) + "</label>";
  2100. });
  2101. }
  2102. return sHtml;
  2103. };
  2104. /**
  2105. * 自適應
  2106. */
  2107. w.onresize = function () {
  2108. var sHeight = $('body').height();
  2109. if ($('#main-wrapper').length) {
  2110. $('#main-wrapper').css('min-height', sHeight - 88 + 'px');
  2111. }
  2112. setContentHeight();
  2113. };
  2114. w.fnframesize = function (down) {
  2115. var pTar = null;
  2116. if (d.getElementById) {
  2117. pTar = d.getElementById(down);
  2118. }
  2119. else {
  2120. eval('pTar = ' + down + ';');
  2121. }
  2122. if (pTar && !w.opera) {
  2123. pTar.style.display = "block";
  2124. if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight) {
  2125. //ns6 syntax
  2126. var iBody = $(d.body).outerHeight(true);
  2127. pTar.height = iBody - 125;
  2128. pTar.width = pTar.contentDocument.body.scrollWidth + 20;
  2129. }
  2130. else if (pTar.Document && pTar.Document.body.scrollHeight) {
  2131. pTar.height = pTar.Document.body.scrollHeight;
  2132. pTar.width = pTar.Document.body.scrollWidth;
  2133. }
  2134. }
  2135. };
  2136. w.setContentHeight = function () {
  2137. var fnIframeResize = function (h) {
  2138. var aryIframe = d.getElementsByTagName("iframe");
  2139. if (aryIframe === null) return;
  2140. for (var i = 0; i < aryIframe.length; i++) {
  2141. var Iframe = aryIframe[i];
  2142. if (Iframe.id.indexOf('ueditor_') === -1) {
  2143. Iframe.height = h;
  2144. }
  2145. }
  2146. },
  2147. content = $('.page-inner'),
  2148. pageContentHeight = $(d.body).outerHeight(true) - 110;
  2149. fnIframeResize(pageContentHeight);
  2150. };
  2151. /**
  2152. * 翻譯語系
  2153. * @param {HTMLElement} dom 要翻譯的html標籤
  2154. * @returns {Boolean} 停止標記
  2155. */
  2156. w.refreshLang = function (dom) {
  2157. if (dom && dom.length === 0) {
  2158. return false;
  2159. }
  2160. CanDo.fn._transLang(dom);
  2161. };
  2162. /**
  2163. * 用於表單序列化去除禁用欄位
  2164. * @param {HTMLElement} dom 父層物件
  2165. */
  2166. w.reFreshInput = function (dom) {
  2167. dom.find('[disabled]').each(function () {
  2168. $(this).attr('hasdisable', 1).removeAttr('disabled');
  2169. });
  2170. };
  2171. /**
  2172. * 用於表單序列化恢復禁用欄位
  2173. * @param {HTMLElement} dom 父層物件
  2174. */
  2175. w.reSetInput = function (dom) {
  2176. dom.find('[hasdisable]').each(function () {
  2177. $(this).removeAttr('hasdisable').prop('disabled', true);
  2178. });
  2179. };
  2180. /**
  2181. * 時間格式化處理
  2182. * @param {Date} date 日期時間
  2183. * @param {Boolean} type 格式日期 || 日期+時間
  2184. * @param {Boolean} empty 是否預設空
  2185. * @return {Boolean} 是否可傳回空
  2186. */
  2187. w.newDate = function (date, type, empty) {
  2188. var r = '';
  2189. if (date) {
  2190. if (typeof date === 'string') {
  2191. r = date.replace('T', ' ').replaceAll('-', '/');
  2192. if (r.indexOf(".") > -1) {
  2193. r = r.slice(0, r.indexOf("."));
  2194. }
  2195. }
  2196. else {
  2197. r = new Date(date);
  2198. }
  2199. r = new Date(r);
  2200. }
  2201. else {
  2202. if (!empty) {
  2203. r = new Date();
  2204. }
  2205. }
  2206. return r === '' ? '' : !type ? r.formate("yyyy/MM/dd HH:mm") : r.formate("yyyy/MM/dd");
  2207. };
  2208. /**
  2209. * 克隆对象
  2210. * @param {Object} obj 被轉換對象
  2211. * @return {Object} o 新對象
  2212. */
  2213. w.clone = function (obj) {
  2214. var o, i, j, k;
  2215. if (typeof obj !== "object" || obj === null) return obj;
  2216. if (obj instanceof Array) {
  2217. o = [];
  2218. i = 0; j = obj.length;
  2219. for (; i < j; i++) {
  2220. if (typeof obj[i] === "object" && obj[i] !== null) {
  2221. o[i] = arguments.callee(obj[i]);
  2222. }
  2223. else {
  2224. o[i] = obj[i];
  2225. }
  2226. }
  2227. }
  2228. else {
  2229. o = {};
  2230. for (i in obj) {
  2231. if (typeof obj[i] === "object" && obj[i] !== null) {
  2232. o[i] = arguments.callee(obj[i]);
  2233. }
  2234. else {
  2235. o[i] = obj[i];
  2236. }
  2237. }
  2238. }
  2239. return o;
  2240. };
  2241. /**
  2242. * 用於表單序列化恢復禁用欄位
  2243. * @param {HTMLElement} dom 要禁用的物件標籤
  2244. * @param {HTMLElement} notdom 不要禁用的物件標籤
  2245. * @param {Boolean} bdisabled 狀態
  2246. */
  2247. w.disableInput = function (dom, notdom, bdisabled) {
  2248. bdisabled = bdisabled === undefined || bdisabled === null ? true : bdisabled;
  2249. dom = dom.find(':input,select-one,select,checkbox,radio,textarea');
  2250. if (notdom) {
  2251. dom = dom.not(notdom);
  2252. }
  2253. dom.each(function () {
  2254. $(this).prop('disabled', bdisabled);
  2255. });
  2256. };
  2257. /**
  2258. * 獲取html模版
  2259. * @param {String} sUrl 模版路徑
  2260. * @param {Boolean} bAsync 是否同步
  2261. * @return {Object} Ajax對象
  2262. */
  2263. w.getHtmlTmp = function (sUrl, bAsync) {
  2264. return $.ajax({
  2265. async: true,
  2266. url: sUrl,
  2267. success: function (html) {
  2268. if (typeof callback === 'function') {
  2269. callback(html);
  2270. }
  2271. }
  2272. });
  2273. };
  2274. /**
  2275. * select2特殊化處理
  2276. * @param {Object} $d 表單控制項
  2277. */
  2278. w.uniformInit = function ($d) {
  2279. //var checkBox = $("input[type=checkbox]:not(.switchery), input[type=radio]:not(.no-uniform)");
  2280. var checkBox = $("input[type=radio]:not(.no-uniform)");
  2281. if ($d) {
  2282. checkBox = $d.find("input[type=radio]:not(.no-uniform)");
  2283. }
  2284. if (checkBox.length > 0) {
  2285. checkBox.each(function () {
  2286. $(this).uniform();
  2287. });
  2288. }
  2289. };
  2290. /**
  2291. * 修改文件
  2292. * @param {Object} file 文件信息
  2293. * @param {HTMLElement} el 文件對象
  2294. */
  2295. w.EditFile = function (file, el) {
  2296. layer.open({
  2297. type: 1,
  2298. title: i18next.t("common.EditFile"),// ╠common.EditFile⇒編輯文件信息╣
  2299. shade: 0.75,
  2300. maxmin: true, //开启最大化最小化按钮
  2301. area: ['500px', '350px'],
  2302. content: '<div class="pop-box">\
  2303. <div class="input-group input-append">\
  2304. <input type="text" maxlength="30" id="FileName" name="FileName" class="form-control w100p">\
  2305. <span class="input-group-addon add-on">\
  2306. </span>\
  2307. </div><br/>\
  2308. <div class="input-group w100p">\
  2309. <input type="text" maxlength="250" id="Link" name="Link" class="form-control w100p" placeholder="URL">\
  2310. </div><br/>\
  2311. <div class="input-group">\
  2312. <textarea name="FileDescription" id="FileDescription" class="form-control w100p" rows="5" cols="500"></textarea>\
  2313. </div>\
  2314. </div>',
  2315. btn: [i18next.t('common.Confirm'), i18next.t('common.Cancel')],//╠common.Confirm⇒確定╣╠common.Cancel⇒取消╣
  2316. success: function (layero, index) {
  2317. $('.pop-box .input-group-addon').text('.' + file.subname);
  2318. $('#FileName').val(file.filename);
  2319. $('#Link').val(file.link);
  2320. uniformInit(layero);//表單美化
  2321. },
  2322. yes: function (index, layero) {
  2323. var sFileName = $('#FileName').val(),
  2324. data = {
  2325. FileName: sFileName,
  2326. Link: $('#Link').val(),
  2327. Description: $('#FileDescription').val()
  2328. };
  2329. if (!data.FileName) {
  2330. showMsg(i18next.t("message.FileName_Required")); // ╠common.message⇒文件名稱不能為空╣
  2331. return false;
  2332. }
  2333. data.FileName += '.' + file.subname;
  2334. g_api.ConnectLite(Service.com, 'EditFile', data,
  2335. function (res) {
  2336. if (res.RESULT) {
  2337. file.filename = sFileName;
  2338. file.link = data.Link;
  2339. file.description = data.Description;
  2340. var img_title = el.find('.jFiler-item-title>b'),
  2341. img_name = el.find('.file-name li:first'),
  2342. img_description = el.find('.jFiler-item-description span');
  2343. if (img_title.length > 0) {
  2344. img_title.attr('title', data.FileName).text(data.FileName);
  2345. }
  2346. if (img_name.length > 0) {
  2347. img_name.text(data.FileName);
  2348. }
  2349. if (img_description.length > 0) {
  2350. img_description.text(data.Description);
  2351. }
  2352. layer.close(index);
  2353. showMsg(i18next.t("message.Modify_Success"), 'success'); //╠message.Modify_Success⇒修改成功╣
  2354. }
  2355. else {
  2356. showMsg(i18next.t("message.Modify_Failed"), 'error'); //╠message.Modify_Failed⇒修改失敗╣
  2357. }
  2358. });
  2359. }
  2360. });
  2361. };
  2362. /**
  2363. * 刪除文件
  2364. * @param {String} fileid 文件id
  2365. * @param {String} idtype id類型
  2366. * @param {String} balert id類型
  2367. * @return {Object} Ajax對象
  2368. */
  2369. w.DelFile = function (fileid, idtype, balert) {
  2370. balert = balert === undefined || balert === null ? true : balert;
  2371. if (fileid && $.trim(fileid)) {
  2372. return g_api.ConnectLite(Service.com, 'DelFile',
  2373. {
  2374. FileID: fileid,
  2375. IDType: idtype || ''
  2376. },
  2377. function (res) {
  2378. if (res.RESULT) {
  2379. if (balert) {
  2380. if (res.DATA.rel) {
  2381. showMsg(i18next.t("message.Delete_Success"), 'success'); // ╠message.Delete_Success⇒刪除成功╣
  2382. }
  2383. else {
  2384. showMsg(i18next.t("message.Delete_Failed"), 'error'); // ╠message.Delete_Failed⇒刪除失敗╣
  2385. }
  2386. }
  2387. }
  2388. else {
  2389. showMsg(i18next.t("message.Delete_Failed"), 'error'); // ╠message.Delete_Failed⇒刪除失敗╣
  2390. }
  2391. });
  2392. }
  2393. else {
  2394. return $.Deferred().resolve().promise();
  2395. }
  2396. };
  2397. /**
  2398. * select options 排序
  2399. * @param {String} set 要排序的select
  2400. * @param {String} get 獲取的select
  2401. * @param {HTMLElement} input 正序還是倒序
  2402. */
  2403. w.optionListSearch = function (set, get, input) {
  2404. //給左邊的每一項添加title效果
  2405. $('option', set).attr('title', function () {
  2406. return this.innerHTML;
  2407. });
  2408. //給右邊的每一項添加title效果
  2409. $('option', get).attr('title', function () {
  2410. return this.innerHTML;
  2411. });
  2412. var tempValue = set.html(), //儲存初始listbox值
  2413. searchtxt = '';
  2414. $.each(set.find('option'), function () {
  2415. if ($(this).val() + $(this).text() !== 'undefined') {
  2416. searchtxt += $(this).val() + '|' + $(this).text() + ',';
  2417. }
  2418. });
  2419. //給搜尋按鈕註冊事件
  2420. input.off('keyup').on('keyup', function () {
  2421. var sWord = this.value;
  2422. set.empty();
  2423. if (sWord !== "") {
  2424. $.each(searchtxt.split(','), function (key, val) {
  2425. if (val.toLowerCase().indexOf(sWord.toLowerCase()) >= 0) {
  2426. var setValue = val.split('|')[0];
  2427. var setText = val.split('|')[1];
  2428. set.append('<option value="' + setValue + '">' + setText + '</option>');
  2429. }
  2430. });
  2431. }
  2432. else {
  2433. set.html(tempValue); //搜尋欄位為空返還初始值(全部人員)
  2434. }
  2435. //移除右邊存在的值
  2436. if (get.html() !== '') {
  2437. $.each(get.find('option'), function () {
  2438. set.find('option[value=' + $(this).val().replace(".", "\\.") + ']').remove();
  2439. });
  2440. }
  2441. });
  2442. };
  2443. /**
  2444. * 透過代號或名稱快速查詢人員
  2445. * @param {String} set 要移出数据的jquery對象
  2446. * @param {String} get 要移入数据的jquery對象
  2447. */
  2448. w.optionListMove = function (set, get) {
  2449. var size = set.find("option").size();
  2450. var selsize = set.find("option:selected").size();
  2451. if (size > 0 && selsize > 0) {
  2452. set.find("option:selected").each(function () {
  2453. $(this).prependTo(get);
  2454. });
  2455. }
  2456. };
  2457. /**
  2458. * 目的設置滾動條
  2459. * @param {Number} h 高度
  2460. * @param {Number} c 定位點
  2461. */
  2462. w.slimScroll = function (h, c) {
  2463. if ($.fn.slimScroll) {
  2464. var option = {
  2465. allowPageScroll: true,
  2466. color: '#ee7624',
  2467. opacity: 1
  2468. };
  2469. if (h) {
  2470. option.height = h;
  2471. }
  2472. if (c) {
  2473. option.reduce = c;
  2474. }
  2475. $('.slimscroll').slimscroll(option);
  2476. }
  2477. };
  2478. /**
  2479. * 參數添加修改人/時間創建人/時間
  2480. * @param {Object} data 表單資料
  2481. * @param {String} type 是否是修改
  2482. * @return {Object} data 表單資料
  2483. */
  2484. w.packParams = function (data, type) {
  2485. data.ModifyUser = parent.top.UserInfo.MemberID;
  2486. data.ModifyDate = new Date().formate('yyyy/MM/dd HH:mm');
  2487. if (!type) {
  2488. data.CreateUser = data.ModifyUser;
  2489. data.CreateDate = data.ModifyDate;
  2490. }
  2491. return data;
  2492. };
  2493. /**
  2494. * 下載文件
  2495. * @param {String} path 文件路徑相對路勁
  2496. * @param {String} filename 文件名稱
  2497. */
  2498. w.DownLoadFile = function (path, filename) {
  2499. var sUrl = gServerUrl + "/Controller.ashx";
  2500. sUrl += '?action=downfile&path=' + path;
  2501. if (filename) {
  2502. sUrl += '&filename=' + filename;
  2503. }
  2504. w.location.href = sUrl;
  2505. CanDo.fn._closeWaiting();
  2506. };
  2507. /**
  2508. * 取得host
  2509. */
  2510. w.gServerUrl = CanDo.fn._getServerUrl();
  2511. /**
  2512. * 定義系統所有公用 Service.fnction
  2513. */
  2514. w.ComFn = {
  2515. W_Com: 'comw',
  2516. GetList: 'QueryList',
  2517. GetAdd: 'Add',
  2518. GetUpd: 'Update',
  2519. GetDel: 'Delete',
  2520. GetUserList: 'GetUserList',
  2521. GetArguments: 'GetArguments'
  2522. };
  2523. w.Service = CanDo.fn._service;
  2524. w.transLang = CanDo.fn._transLang;
  2525. function onStart(e) {
  2526. CanDo.fn._showWaiting(typeof IsWaiting === 'string' ? IsWaiting : undefined);
  2527. }
  2528. function onStop(e) {
  2529. CanDo.fn._closeWaiting();
  2530. setTimeout(function () { IsWaiting = null; }, 3000);
  2531. }
  2532. $(d).ajaxStart(onStart).ajaxStop(onStop);
  2533. CanDo.fn._init.prototype = CanDo.fn;
  2534. return CanDo;
  2535. })(window, document);
  2536. /**
  2537. * 日期添加屬性
  2538. * @param {String} type y:;q:季度;m:;w:星期;d:;h:小時;n:;s:;ms:毫秒;
  2539. * @param {Number} num 添加的數值
  2540. * @return {Date} r 新的時間
  2541. */
  2542. Date.prototype.dateAdd = function (type, num) {
  2543. var r = this,
  2544. k = { y: 'FullYear', q: 'Month', m: 'Month', w: 'Date', d: 'Date', h: 'Hours', n: 'Minutes', s: 'Seconds', ms: 'MilliSeconds' },
  2545. n = { q: 3, w: 7 };
  2546. eval('r.set' + k[type] + '(r.get' + k[type] + '()+' + (n[type] || 1) * num + ')');
  2547. return r;
  2548. };
  2549. /**
  2550. * 計算兩個日期的天數
  2551. * @param {Object} date 第二個日期;
  2552. * @return {Number} 時間差
  2553. */
  2554. Date.prototype.diff = function (date) {
  2555. return (this.getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
  2556. };
  2557. /**
  2558. * 对Date的扩展 Date 转化为指定格式的String
  2559. * (M)(d)12小时(h)24小时(H)(m)(s)(E)季度(q) 可以用 1-2 个占位符
  2560. * (y)可以用 1-4 个占位符毫秒(S)只能用 1 个占位符( 1-3 位的数字)
  2561. * eg:
  2562. * (new Date()).formate("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  2563. * (new Date()).formate("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 20:09:04
  2564. * (new Date()).formate("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
  2565. * (new Date()).formate("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
  2566. * (new Date()).formate("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
  2567. * @param {String} fmt 格式字串;
  2568. * @return {Date} fmt 新的時間
  2569. */
  2570. Date.prototype.formate = function (fmt) {
  2571. var o = {
  2572. "M+": this.getMonth() + 1, //月份
  2573. "d+": this.getDate(), //日
  2574. "h+": this.getHours() % 12 === 0 ? 12 : this.getHours() % 12, //小时
  2575. "H+": this.getHours(), //小时
  2576. "m+": this.getMinutes(), //分
  2577. "s+": this.getSeconds(), //秒
  2578. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  2579. "S": this.getMilliseconds() //毫秒
  2580. };
  2581. var week = {
  2582. "0": "\u65e5",
  2583. "1": "\u4e00",
  2584. "2": "\u4e8c",
  2585. "3": "\u4e09",
  2586. "4": "\u56db",
  2587. "5": "\u4e94",
  2588. "6": "\u516d"
  2589. };
  2590. if (/(y+)/.test(fmt)) {
  2591. fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  2592. }
  2593. if (/(E+)/.test(fmt)) {
  2594. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length > 1 ? RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468" : "") + week[this.getDay() + ""]);
  2595. }
  2596. for (var k in o) {
  2597. if (new RegExp("(" + k + ")").test(fmt)) {
  2598. fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  2599. }
  2600. }
  2601. return fmt;
  2602. };
  2603. /**
  2604. * 註冊全替換
  2605. * @param {String} s1 字串1
  2606. * @param {String} s2 字串2
  2607. * @return {String} 替換後的新字串
  2608. */
  2609. String.prototype.replaceAll = function (s1, s2) {
  2610. return this.replace(new RegExp(s1, "gm"), s2);
  2611. };
  2612. /**
  2613. * 註冊金額添加三位一撇
  2614. * @return {String}三位一撇字串
  2615. */
  2616. String.prototype.toMoney = Number.prototype.toMoney = function () {
  2617. return this.toString().replace(/\d+?(?=(?:\d{3})+$)/g, function (s) {
  2618. return s + ',';
  2619. });
  2620. };
  2621. /**
  2622. * 数字四舍五入保留n位小数
  2623. * @param {Number} n 保留n位
  2624. * @return {Number} number 數值
  2625. */
  2626. String.prototype.toFloat = Number.prototype.toFloat = function (n) {
  2627. n = n ? parseInt(n) : 0;
  2628. var number = this;
  2629. if (n <= 0) return Math.round(number);
  2630. number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n);
  2631. return number;
  2632. };
  2633. /**
  2634. * 百分数转小数
  2635. * @return {Number} 百分数
  2636. */
  2637. String.prototype.toPoint = function () {
  2638. return this.replace("%", "") / 100;
  2639. };
  2640. /**
  2641. * 小数转化为分数
  2642. * @return {String} percent 百分数
  2643. */
  2644. String.prototype.toPercent = Number.prototype.toPercent = function () {
  2645. var percent = Number(this * 100).toFixed(1);
  2646. percent += "%";
  2647. return percent;
  2648. };
  2649. /**
  2650. * 刪除陣列內包含(undefined, null, 0, false, NaN and '')的資料
  2651. * @return {Array} 新陣列
  2652. */
  2653. Array.prototype.clear = function () {
  2654. var newArray = [];
  2655. for (var i = 0; i < this.length; i++) {
  2656. if (this[i]) {
  2657. newArray.push(this[i]);
  2658. }
  2659. }
  2660. return newArray;
  2661. };
  2662. /**
  2663. * 在數組指定位置添加元素
  2664. * @param {Number} index 位置
  2665. * @param {Object} item 要添加的元素
  2666. */
  2667. Array.prototype.insert = function (index, item) {
  2668. this.splice(index, 0, item);
  2669. };
  2670. /**
  2671. * 刪除陣列內指定元素
  2672. * @param {String} val 元素
  2673. */
  2674. Array.prototype.remove = function (val) {
  2675. var index = this.indexOf(val);
  2676. if (index > -1) {
  2677. this.splice(index, 1);
  2678. }
  2679. };
  2680. /**
  2681. * 方法陣列內等待
  2682. * @param {Array} array 執行方法陣列
  2683. * @return {Object} Ajax 對象
  2684. */
  2685. jQuery.whenArray = function (array) {
  2686. return jQuery.when.apply(this, array);
  2687. };