/*global $, alert, g_cus, g_de, g_api, g_db, g_ul, btoa, console, i18n */ var i18next = ("undefined" === typeof i18next) ? parent.top.i18next : i18next, g_db = { /** * Check the capability * @private * @method SupportLocalStorage * @return {Object} description */ SupportLocalStorage: function () { 'use strict'; return typeof (localStorage) !== "undefined"; }, /** * Insert data * @private * @method SetItem * @param {Object} sKey * @param {Object} sValue * @return {Object} description */ SetItem: function (sKey, sValue) { 'use strict'; var bRes = false; if (this.SupportLocalStorage()) { localStorage.setItem(sKey, sValue); bRes = true; } return bRes; }, /** * Fetch data * @private * @method GetItem * @param {Object} sKey * @return {Object} description */ GetItem: function (sKey) { 'use strict'; var sRes = null; if (this.SupportLocalStorage()) { sRes = localStorage.getItem(sKey); } return sRes; }, /** * Remove data * @private * @method RemoveItem * @param {Object} sKey * @return {Object} description */ RemoveItem: function (sKey) { 'use strict'; var bRes = false; if (this.SupportLocalStorage()) { localStorage.removeItem(sKey); bRes = true; } return bRes; }, /** * Description for GetDic * @private * @method GetDic * @return {Object} description */ GetDic: function (sKey) { 'use strict'; var dicRes = null, vTemp; if (this.SupportLocalStorage()) { vTemp = localStorage.getItem(sKey); if (null !== vTemp) { dicRes = JSON.parse(vTemp); } } return dicRes; }, /** * Description for SetDic * @private * @method SetDic * @return {Object} description */ SetDic: function (sKey, dicValue) { 'use strict'; var bRes = false; if (this.SupportLocalStorage()) { localStorage.setItem(sKey, JSON.stringify(dicValue)); bRes = true; } return bRes; } }; var g_gd = { webapilonginurl: "/api/Service/GetLogin", webapiurl: "/api/Cmd/GetData", projectname: "Eurotran", projectver: "Origtek", relpath: "", debugmode: window.location.host === '192.168.1.105', debugcolor: "#732C6B", IsEDU: g_db.GetItem("isedu") === "true" }; var g_ul = { /** * Get token from db * @returns {String} Token in localStorage */ GetToken: function () { 'use strict'; return g_db.GetItem("token"); }, /** * Set token to db * @param {String} sTokenValue api token */ SetToken: function (sTokenValue) { 'use strict'; g_db.SetItem("token", sTokenValue); }, /** * Set signature to db * @param {String} sSignatureValue api signature */ GetSignature: function () { 'use strict'; return g_db.GetItem("signature"); }, /** * Set signature to db * @param {String} sSignatureValue api signature */ SetSignature: function (sSignatureValue) { 'use strict'; g_db.SetItem("signature", sSignatureValue); }, /** * Set language * @param {String} language method */ SetLang: function (sLang) { 'use strict'; g_db.SetItem("lang", sLang); }, /** * Get language * @returns {String} language in localStorage */ GetLang: function () { 'use strict'; return g_db.GetItem("lang"); }, /** * Set login method * @param {String} login method */ SetLoginMethod: function (sLoginMethod) { 'use strict'; g_db.SetItem("LoginMethod", sLoginMethod); }, /** * Get login method * @returns {String} login method in localStorage */ GetLoginMethod: function () { 'use strict'; return g_db.GetItem("LoginMethod"); }, /** * Check is edu environment * @returns {String} login method in localStorage */ IsEDU: function () { 'use strict'; return g_db.GetItem("isedu"); }, /** * Get trace stack */ TraceStackDump: function () { var dicTraceStackData = {}, dicTraceStackDataLevel = {}, ldicTraceStackDataList = [], curArguments = null, iLevel = 0, iIdx = 0, iLim = 0, oPara = null, bFindButtonEvent = false; curArguments = arguments; do { dicTraceStackDataLevel = {}; dicTraceStackDataLevel.name = curArguments.callee.name; dicTraceStackDataLevel.parameters = []; iLim = curArguments.length; if (iLim > 0) { oPara = curArguments["0"]; if (typeof (oPara) === "object" && oPara.hasOwnProperty("currentTarget")) { bFindButtonEvent = true; dicTraceStackDataLevel.buttonclick = oPara.currentTarget.id; } else { for (iIdx = 0; iIdx < iLim; iIdx++) { oPara = curArguments[iIdx.toString()]; dicTraceStackDataLevel.parameters.push(curArguments[iIdx.toString()]); } } } if (iLevel > 0) { ldicTraceStackDataList.push($.extend({}, dicTraceStackDataLevel)); } if (curArguments.callee.caller === null) { break; } curArguments = curArguments.callee.caller.arguments; iLevel = iLevel + 1; } while (bFindButtonEvent === false); dicTraceStackData.stack = ldicTraceStackDataList; return dicTraceStackData; } }; var g_api = { ConnectLite: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn, i_sShwd) { window.IsWaiting = i_sShwd; return this.ConnectLiteWithoutToken(i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn); }, ConnectService: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn, i_sShwd) { window.IsWaiting = i_sShwd; return this.ConnectWebLiteWithoutToken(i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn); }, ConnectLiteWithoutToken: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn) { var dicData = {}, dicParameters = {}, token = g_ul.GetToken(), lang = g_ul.GetLang(), signature = g_ul.GetSignature(); dicParameters.ORIGID = g_db.GetItem('orgid'); dicParameters.USERID = g_db.GetItem('userid'); dicParameters.MODULE = i_sModuleName; dicParameters.TYPE = i_sFuncName; dicParameters.PROJECT = g_gd.projectname; dicParameters.PROJECTVER = g_gd.projectver; dicParameters.TRACEDUMP = null; // g_ul.TraceStackDump(); i_dicData = i_dicData || {}; if (g_db.GetItem('dblockDict') !== null) { i_dicData.dblockDict = g_db.GetItem('dblockDict'); } dicParameters.DATA = i_dicData; if (lang !== null) { dicParameters.LANG = lang; } if (token !== null) { dicParameters.TOKEN = token; } if (signature !== null) { dicParameters.SIGNATURE = signature; } dicParameters.CUSTOMDATA = {}; if (window.sProgramId) { dicParameters.CUSTOMDATA.program_id = sProgramId; } dicParameters.CUSTOMDATA.module_id = "webapp"; dicData.url = i_dicData.hasOwnProperty("url") ? i_dicData.url : g_gd.webapiurl; dicData.successfunc = i_sSuccessFunc; dicData.dicparameters = dicParameters; dicData.failfunc = ("function" === typeof (i_FailFunc)) ? i_FailFunc : function (jqXHR, textStatus, errorThrown) { alert("ConnectLite Fail jqXHR:" + jqXHR + " textStatus:" + textStatus + " errorThrown:" + errorThrown); }; dicData.useasync = ("boolean" === typeof (i_bAsyn)) ? i_bAsyn : true; return this.AjaxPost(dicData); }, //w.CallAjax = function (url, fnname, data, sucfn, failfn, wait, async, alwaysfn) { ConnectWebLiteWithoutToken: function (i_sUrl, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn) { var dicData = {}, dicParameters = {}, token = g_ul.GetToken(), lang = g_ul.GetLang(), signature = g_ul.GetSignature(); dicParameters.ORIGID = g_db.GetItem('orgid'); dicParameters.USERID = g_db.GetItem('userid'); dicParameters.MODULE = ''; dicParameters.TYPE = i_sFuncName; dicParameters.PROJECT = g_gd.projectname; dicParameters.PROJECTVER = g_gd.projectver; dicParameters.TRACEDUMP = null; // g_ul.TraceStackDump(); if (g_db.GetItem('dblockDict') !== null) { i_dicData.dblockDict = g_db.GetItem('dblockDict'); } dicParameters.DATA = i_dicData; if (lang !== null) { dicParameters.LANG = lang; } if (token !== null) { dicParameters.TOKEN = token; } if (signature !== null) { dicParameters.SIGNATURE = signature; } dicParameters.CUSTOMDATA = {}; if (window.sProgramId) { dicParameters.CUSTOMDATA.program_id = sProgramId; } dicParameters.CUSTOMDATA.module_id = "webapp"; dicData.url = getWebServiceUrl(i_sUrl, i_sFuncName); dicData.successfunc = i_sSuccessFunc; dicData.dicparameters = dicParameters; dicData.failfunc = ("function" === typeof (i_FailFunc)) ? i_FailFunc : function (jqXHR, textStatus, errorThrown) { alert("ConnectLite Fail jqXHR:" + jqXHR + " textStatus:" + textStatus + " errorThrown:" + errorThrown); }; dicData.useasync = ("boolean" === typeof (i_bAsyn)) ? i_bAsyn : true; return this.AjaxPost(dicData); }, AjaxPost: function (i_dicData) { 'use strict'; var defaultOption = { useasync: true, successfunc: null, failfunc: null, alwaysfunc: null, url: null, dicparameters: null }, runOption = $.extend(defaultOption, i_dicData), runSuccess = function (res) { if (res.RESULT === -1) { // ╠message.TokenVerifyFailed⇒您的身份認證已經過期,請重新登入╣ ╠common.Tips⇒提示╣ layer.alert(i18next.t("message.TokenVerifyFailed"), { icon: 0, title: i18next.t("common.Tips") }, function (index) { window.top.location.href = '/Page/login.html'; }); } else { if (runOption.successfunc) { runOption.successfunc(res); } } }; return $.ajax({ type: 'POST', url: runOption.url, data: "=" + btoa2(encodeURIComponent(JSON.stringify(runOption.dicparameters))), success: runSuccess, error: runOption.failfunc, beforeSend: function (xhr) { var token = g_ul.GetToken(), timestamp = $.now(), nonce = rndnum(); xhr.setRequestHeader("orgid", runOption.dicparameters.ORIGID); xhr.setRequestHeader("userid", runOption.dicparameters.USERID); xhr.setRequestHeader("token", token); xhr.setRequestHeader("timestamp", timestamp); xhr.setRequestHeader("nonce", nonce); }, async: true !== runOption.useasync ? false : true }).always(runOption.alwaysfunc); } }; (function ($, w, d) { /** * 取得host */ w.gServerUrl = w.location.origin || gethost(); /** * 定義系統所有HTML模版 */ w.ComTmp = { PageTitle: '/Page/Pop/PageTitle.html', }; /** * 定義系統所有公用 Service.fnction */ w.ComFn = { W_Com: 'comw', W_Web: 'web', GetUserList: 'GetUserList', GetArguments: 'GetArguments', GetSysSet: 'GetSysSet', GetSerial: 'GetSerialNumber', GetUpdateOrder: 'UpdateOrderByValue', SendMail: 'SendMail', GetExcel: 'CreateExcel', GetList: 'QueryList', GetOne: 'QueryOne', GetPage: 'QueryPage', GetPagePrc: 'QueryPageByPrc', GetAdd: 'Add', GetUpd: 'Update', GetDel: 'Delete', GetTran: 'UpdateTran', GetCount: 'QueryCount', CheckInvoiceNum: 'CheckInvoiceNumber' }; /** * 定義系統所有公用 Service */ w.Service = { cotrl: '/Controller.ashx', comw: 'ComWebService', web: 'WebService', com: 'Common', opm: 'OpmCom', eip: 'EipCom', sys: 'SysCom', auth: 'Authorize' }; /** * 定義頁面離開是否需要儲存 */ w.bRequestStorage = false; w.bLeavePage = false; /** * 定義查詢頁面默認顯示第幾頁 */ w.QueryPageidx = 1; /** * Ajax是否等待 */ w.IsWaiting = null; /** * For display javascript exception on UI */ w.onerror = function (message, source, lineno, colno, error) { console.log(source + " line:" + lineno + " colno:" + colno + " " + message); if (parent.top.SysSet && parent.top.SysSet.IsOpenMail === 'Y') { g_api.ConnectLite('Log', 'ErrorMessage', { ErrorSource: source, Errorlineno: lineno, Errorcolno: colno, ErrorMessage: message }, function (res) { }); } }; /** * 翻譯語系 * @param {HTMLElement} dom 翻譯回調函數 */ w.transLang = function (dom) { i18next = ("undefined" === typeof i18next) ? parent.top.i18next : i18next; var oHandleData = dom === undefined ? $('[data-i18n]') : dom.find('[data-i18n]'), oHandlePlaceholder = dom === undefined ? $('[placeholderid]') : dom.find('[placeholderid]'); oHandleData.each(function (idx, el) { var i18key = $(el).attr('data-i18n'); if (i18key) { var sLan = i18next.t(i18key); if (el.nodeName == 'INPUT' && el.type == 'button') { $(el).val(sLan); } else { $(el).html(sLan); } } }); oHandlePlaceholder.each(function (idx, el) { var i18key = $(el).attr("placeholderid"); if (i18key) { var sLan = i18next.t(i18key); if (sLan !== i18key) { $(el).attr("placeholder", sLan); } } }); }; /** * 翻譯語系 * @param {HTMLElement} dom 要翻譯的html標籤 */ w.refreshLang = function (dom) { if (dom && dom.length === 0) { return false; } transLang(dom); }; /** * 設定多於系 * @param {String} lng 語種 * @param {String} dom 要翻譯的html標籤 * @param {Function} callback 回調函數 */ w.setLang = function (lng, dom, callback) { if (!lng) return; g_ul.SetLang(lng); i18next = ("undefined" == typeof i18next) ? parent.top.i18next : i18next; $.getJSON(gServerUrl + "/Scripts/lang/" + (parent.top.OrgID || 'TE') + "/" + lng + ".json?v=20180801", function (json) { var oResources = {}; oResources[lng] = { translation: json }; i18next.init({ lng: lng, resources: oResources, useLocalStorage: false, //是否将语言包存储在localstorage //ns: { namespaces: ['trans'], defaultNs: 'trans' }, //加载的语言包 localStorageExpirationTime: 86400000 // 有效周期,单位ms。默认1 }, function (err, t) { transLang(dom); if (typeof callback === 'function') { callback(t); } }); }); }; /** * getLanguagePack */ w.getLanguagePack = function (sMsgKey) { var sLang = g_ul.GetLang() || 'en'; return i18next.getResourceBundle(sLang, 'translation').sMsgKey || sMsgKey; }; /** * 獲取WebService路勁 * @param {String} type Service類型 * @param {String} fnname function 名稱 */ w.getWebServiceUrl = function (type, fnname) { var sUrl = ''; switch (type) { case 'aspx': sUrl = fnname; break; case 'cotrl': sUrl = '/Controller.ashx?' + fnname; break; default: sUrl = '/WS/' + Service[type] + '.asmx/' + fnname; break; } return sUrl; }; /** * 呼叫Ajax * @param {String} urlaspx 地址 * @param {String} fnname 方法名稱 * @param {Object} data 參數 * @param {Function} callback 成功回調函數 * @param {Function} failfn 失敗回調函數 * @param {String} IsWait 是否waitting(默認false) * @param {Boolean} IsAsync 是否同步(默認非同步) * @return {Object} Ajax對象 */ w.CallAjax = function (url, fnname, data, sucfn, failfn, wait, async, alwaysfn) { w.IsWaiting = (wait === undefined || wait === true) ? true : (wait === false) ? null : wait; return $.ajax({ type: 'POST', async: async == undefined ? true : false, url: getWebServiceUrl(url, fnname), data: JSON.stringify(data), //傳送區域參數 contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (res) { if (res.d === '-1' || res.d === -1) {// ╠message.TokenVerifyFailed⇒您的身份認證已經過期,請重新登入╣ ╠common.Tips⇒提示╣ layer.alert(i18next.t("message.TokenVerifyFailed"), { icon: 0, title: i18next.t("common.Tips") }, function (index) { w.top.location.href = '/Page/login.html'; }); } else { if (sucfn) { sucfn(res); } } }, beforeSend: function (xhr) { var orgid = g_db.GetItem('orgid'), userid = g_db.GetItem('userid'), token = g_ul.GetToken(); xhr.setRequestHeader("orgid", orgid); xhr.setRequestHeader("userid", userid); xhr.setRequestHeader("token", token); }, error: failfn || function (e1, e2, e3) { }, global: wait === false ? false : true }).always(alwaysfn); }; /** * 呼叫Ajax * @param {String} urlaspx 地址 * @param {String} fnname 方法名稱 * @param {Object} data 參數 * @param {Function} callback 成功回調函數 * @param {Function} failfn 失敗回調函數 * @param {String} IsWait 是否waitting(默認false) * @param {Boolean} IsAsync 是否同步(默認非同步) * @return {Object} Ajax對象 */ w.CallAjaxCross = function (urlaspx, fnname, data, callback, failfn, IsWait, IsAsync) { if (IsWait) IsWaiting = IsWait; else IsWaiting = null; return $.ajax({ type: 'POST', async: IsAsync == undefined ? true : false, jsonpCallback: "Callback",//callback的function名称 url: getWebServiceUrl(urlaspx, fnname), data: data, //傳送區域參數 dataType: 'jsonp', success: callback || function () { }, beforeSend: function (xhr) { var orgid = g_db.GetItem('orgid'), userid = g_db.GetItem('userid'), token = g_ul.GetToken(); xhr.setRequestHeader("orgid", orgid); xhr.setRequestHeader("userid", userid); xhr.setRequestHeader("token", token); }, error: failfn || function (a, b, c) { console.log(c); }, global: (IsWait == undefined || IsWait == null) ? false : true }); }; /** * 開啟Waiting視窗 * @param {String} msg 提示文字 */ w.showWaiting = function (msg) { $.blockUI({ message: $('
' + (msg || 'Waiting...') + '
'), css: { 'font-size': '36px', border: '0px', 'border-radius': '10px', 'background-color': '#FFF', padding: '15px 15px', opacity: .5, color: 'orange', cursor: 'wait', 'z-index': 1000000001 }, baseZ: 1000000000 }); w.setTimeout($.unblockUI, 60000);//預設開啟60秒後關閉 }; /** * 關閉Waiting視窗 * @param {Number} iSleep 延遲時間,單位為毫秒 */ w.closeWaiting = function (iSleep) { $(function () { if (iSleep == undefined) { iSleep = 100; } setTimeout($.unblockUI, iSleep); }); }; /** * 從物件陣列中移除屬性為objPropery,值為objValue元素的物件 * @param {Array} arrPerson 陣列物件 * @param {String} objPropery 物件的屬性 * @param {String} objPropery 對象的值 * @return {Array} 過濾後陣列 */ w.Jsonremove = function (arrPerson, objPropery, objValue) { return $.grep(arrPerson, function (cur, i) { return cur[objPropery] != objValue; }); }; /** * 從物件陣列中獲取屬性為objPropery,值為objValue元素的物件 * @param {Array} arrPerson 陣列物件 * @param {String} objPropery 物件的屬性 * @param {String} objPropery 對象的值 * @return {Array} 過濾後陣列 */ w.Jsonget = function (arrPerson, objPropery, objValue) { return $.grep(arrPerson, function (cur, i) { return cur[objPropery] == objValue; }); }; /** * 將json轉換字串 * @param {Object} json json物件 * @return {String} json字串 */ w.Tostr = function (json) { return JSON.stringify(json); }; /** * 下載文件 * @param {String} path 文件路徑(相對路勁) */ w.DownLoadFile = function (path, filename) { var sUrl = gServerUrl + "/Controller.ashx"; sUrl += '?action=downfile&path=' + path; if (filename) { sUrl += '&filename=' + filename; } w.location.href = sUrl; closeWaiting(); }; /** * 修改文件 * @param {Object} file 文件信息 * @param {HTMLElement} el 文件對象 */ w.EditFile = function (file, el) { layer.open({ type: 1, title: i18next.t("common.EditFile"),// ╠common.EditFile⇒編輯文件信息╣ shade: 0.75, maxmin: true, //开启最大化最小化按钮 area: ['500px', '350px'], content: '
\
\ \ \ \

\
\ \

\
\ \
\
', btn: [i18next.t('common.Confirm'), i18next.t('common.Cancel')],//╠common.Confirm⇒確定╣╠common.Cancel⇒取消╣ success: function (layero, index) { $('.pop-box .input-group-addon').text('.' + file.subname); $('#FileName').val(file.filename); $('#Link').val(file.link); uniformInit(layero);//表單美化 }, yes: function (index, layero) { var sFileName = $('#FileName').val(), data = { FileName: sFileName, Link: $('#Link').val(), Description: $('#FileDescription').val() }; if (!data.FileName) { showMsg(i18next.t("message.FileName_Required")); // ╠common.message⇒文件名稱不能為空╣ return false; } data.FileName += '.' + file.subname; CallAjax(ComFn.W_Com, ComFn.GetUpd, { Params: { files: { values: data, keys: { FileID: file.fileid } } } }, function (res) { if (res.d > 0) { file.filename = sFileName; file.link = data.Link; file.description = data.Description; var img_title = el.find('.jFiler-item-title>b'), img_name = el.find('.file-name li:first'), img_description = el.find('.jFiler-item-description span'); if (img_title.length > 0) { img_title.attr('title', data.FileName).text(data.FileName); } if (img_name.length > 0) { img_name.text(data.FileName); } if (img_description.length > 0) { img_description.text(data.Description); } layer.close(index); showMsg(i18next.t("message.Modify_Success"), 'success'); //╠message.Modify_Success⇒修改成功╣ } else { showMsg(i18next.t("message.Modify_Failed"), 'error'); //╠message.Modify_Failed⇒修改失敗╣ } }); } }); }; /** * 刪除文件 * @param {String} fileid 文件id * @param {String} idtype id類型 */ w.DelFile = function (fileid, idtype, bAlert) { bAlert = (bAlert === undefined || bAlert === null) ? true : bAlert; if (fileid && $.trim(fileid)) { return g_api.ConnectLite(Service.com, 'DelFile', { FileID: fileid, IDType: idtype || '' }, function (res) { if (res.RESULT) { if (bAlert) { if (res.DATA.rel) { showMsg(i18next.t("message.Delete_Success"), 'success'); // ╠message.Delete_Success⇒刪除成功╣ } else { showMsg(i18next.t("message.Delete_Failed"), 'error'); // ╠message.Delete_Failed⇒刪除失敗╣ } } } else { showMsg(i18next.t("message.Delete_Failed"), 'error'); // ╠message.Delete_Failed⇒刪除失敗╣ } }); } else { return $.Deferred().resolve().promise(); } }; /** * 刪除代辦 * @param {String} sourseid 代辦id */ w.DelTask = function (sourseid) { return CallAjax(ComFn.W_Com, ComFn.GetDel, { Params: { task: { SourceID: sourseid, OrgID: parent.top.OrgID } } }); }; /** * 用於表單序列化去除禁用欄位 * @param {HTMLElement} dom 父層物件 */ w.reFreshInput = function (dom) { dom.find('[disabled]').each(function () { $(this).attr('hasdisable', 1).removeAttr('disabled'); }); }; /** * 用於表單序列化恢復禁用欄位 * @param {HTMLElement} dom 父層物件 */ w.reSetInput = function (dom) { dom.find('[hasdisable]').each(function () { $(this).removeAttr('hasdisable').prop('disabled', true); }); }; /** * 用於表單序列化恢復禁用欄位 * @param {HTMLElement} dom 要禁用的物件標籤 * @param {HTMLElement} notdom 不要禁用的物件標籤 */ w.disableInput = function (dom, notdom, bdisabled) { bdisabled = (bdisabled === undefined || bdisabled === null) ? true : bdisabled; dom = dom.find(':input,select-one,select,checkbox,radio,textarea'); if (notdom) { dom = dom.not(notdom); } dom.each(function () { $(this).prop('disabled', bdisabled); }); }; /** * 序列化form表單 * @param {HTMLElement} form 表單form物件 * @param {String} type 傳回類型 * @return {Object Or String} 表單資料 */ w.getFormSerialize = function (form, type) { var formdata = {}; reFreshInput(form); if (type) { formdata = form.serializeJSON(); } else { formdata = form.serializeObject(); } reSetInput(form); return formdata; }; /** * 參數添加修改人/時間,創建人/時間 * @param {Object} data 表單資料 * @param {String} type 是否是修改 * @return {Object} data 表單資料 */ w.packParams = function (data, type) { data.ModifyUser = parent.top.UserInfo.MemberID; data.ModifyDate = new Date().formate('yyyy/MM/dd HH:mm'); if (!type) { data.CreateUser = data.ModifyUser; data.CreateDate = data.ModifyDate; } return data; }; /** * 移除null項目 * @param {Object} data 表單資料 * @return {Object} data 表單資料 */ w.removeNull = function (data) { var dataNew = {}; if (data instanceof (Object)) { for (var o in data) { if (data[o] !== null) { dataNew[o] = data[o]; } } } return dataNew; }; /** * 取得Url參數 * @param {String} name 取得部分的名稱 例如輸入"Action",就能取到"Add"之類參數 * @return {String}參數值 */ w.getUrlParam = function (name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //構造一個含有目標參數的正則表達式對象 var r = w.location.search.substr(1).match(reg); //匹配目標參數 if (r != null) return unescape(r[2]); return null; //返回參數值 }; /** * 對網址、路徑進行編碼 * @param {String} url 要編碼的url或路徑 * @return {String} 編碼後的url或路徑 */ w.encodeURL = function (url) { return encodeURIComponent(url).replace(/\'/g, "%27").replace(/\!/g, "%21").replace(/\(/g, "%28").replace(/\)/g, "%29"); }; /** * 對網址、路徑進行解碼 * @param {String} url 要解碼的url或路徑 * @return {String} 解碼後的url或路徑 */ w.decodeURL = function (url) { return decodeURIComponent(url); }; /** * 透過代號或名稱快速查詢人員 * @param {String} set 要移出数据的jquery對象 * @param {String} get 要移入数据的jquery對象 */ w.optionListMove = function (set, get) { var size = set.find("option").size(); var selsize = set.find("option:selected").size(); if (size > 0 && selsize > 0) { set.find("option:selected").each(function () { $(this).prependTo(get); }); } }; /** * select options 排序 * @param {String} set 要排序的select * @param {String} ordertype 正序還是倒序 */ w.optionListOrder = function (set, ordertype) { var size = set.find("option").size(), select = set.find("option:selected"), selsize = select.size(); if (size > 0 && selsize > 0) { var firstsel = set.find("option:selected:first"), lastsel = set.find("option:selected:last") if (ordertype) { if (firstsel.prev().length > 0) { firstsel.prev().before(select); } } else { if (lastsel.next().length > 0) { lastsel.next().after(select); } } } }; /** * select options 排序 * @param {String} set 要排序的select * @param {String} ordertype 正序還是倒序 */ w.optionListSearch = function (set, get, input) { //給左邊的每一項添加title效果 $('option', set).attr('title', function () { return this.innerHTML; }); //給右邊的每一項添加title效果 $('option', get).attr('title', function () { return this.innerHTML; }); var tempValue = set.html(), //儲存初始listbox值 searchtxt = ''; $.each(set.find('option'), function () { if ($(this).val() + $(this).text() != 'undefined') { searchtxt += $(this).val() + '|' + $(this).text() + ','; } }); //給搜尋按鈕註冊事件 input.off('keyup').on('keyup', function () { var sWord = this.value; set.empty(); if (sWord != "") { $.each(searchtxt.split(','), function (key, val) { if (val.toLowerCase().indexOf(sWord.toLowerCase()) >= 0) { var setValue = val.split('|')[0]; var setText = val.split('|')[1]; set.append('') } }); } else { set.html(tempValue); //搜尋欄位為空返還初始值(全部人員) } //移除右邊存在的值 if (get.html() != '') { $.each(get.find('option'), function () { set.find('option[value=' + $(this).val().replace(".", "\\.") + ']').remove(); }); } }); }; /** * 時間格式化處理 * @param {Date} date 日期時間 * @param {Boolean} type 格式(日期 || 日期+時間) * @return {Boolean} 是否可傳回空 */ w.newDate = function (date, type, empty) { var r = ''; if (date) { if (typeof date == 'string') { r = date.replace('T', ' ').replaceAll('-', '/'); if (r.indexOf(".") > -1) { r = r.slice(0, r.indexOf(".")); } } else { r = new Date(date); } r = new Date(r); } else { if (!empty) { r = new Date(); } } return r === '' ? '' : !type ? r.formate("yyyy/MM/dd HH:mm") : r.formate("yyyy/MM/dd"); }; /** * 獲取html模版 * @param {String} sUrl 模版路徑 * @param {Boolean} bAsync 是否同步 */ w.getHtmlTmp = function (sUrl, bAsync) { return $.ajax({ async: true, url: sUrl, success: function (html) { if (typeof callback === 'function') { callback(html); } } }); }; /** * 產生guid * @param {Number} len 指定长度,比如guid(8, 16) // "098F4D35" * @param {Number} radix 基数 * @return {String} guid */ w.guid = function (len, radix) { var buf = new Uint16Array(8), cryptObj = w.crypto || w.msCrypto, // For IE11 s4 = function (num) { var ret = num.toString(16); while (ret.length < 4) { ret = '0' + ret; } return ret; }; cryptObj.getRandomValues(buf); return s4(buf[0]) + s4(buf[1]) + '-' + s4(buf[2]) + '-' + s4(buf[3]) + '-' + s4(buf[4]) + '-' + s4(buf[5]) + s4(buf[6]) + s4(buf[7]); }; /** * 產生隨機數 * @param {Number} len 指定长度,比如random(8) * @return {String} rnd 亂數碼 */ rndnum = function (len) { var rnd = ""; len = len || 10; for (var i = 0; i < len; i++) rnd += Math.floor(Math.random() * 10); return rnd; }; /** * 添加提示Tips * @param {HTMLElement} handle dom物件 */ w.addTips = function (handle) { handle = (handle !== undefined) ? handle : $('[title]'); handle.each(function () { var oTips = $(this); if (oTips.attr('title') && oTips.attr('tooltips') !== 'Y') { oTips.attr('tooltips', 'Y').jBox('Tooltip'); } }); }; /** * 停止冒泡行为时 * @param {HTMLElement} e 事件对象 */ w.stopBubble = function (e) { //如果提供了事件对象,则这是一个非IE浏览器 if (e && e.stopPropagation) //因此它支持W3C的stopPropagation()方法 e.stopPropagation(); else //否则,我们需要使用IE的方式来取消事件冒泡 w.event.cancelBubble = true; }; /** * 阻止默认行为时 * @param {HTMLElement} e 事件对象 */ w.stopDefault = function (e) { //阻止默认浏览器动作(W3C) if (e && e.preventDefault) e.preventDefault(); //IE中阻止函数器默认动作的方式 else w.event.returnValue = false; return false; }; /** * 獲取權限 * @param {String} programid 程式id * @param {Function} 回調函數 * @return {Object} ajax 物件 */ w.getAuthority = function (programid, callback, cus, opt) { var sTopMod = getTopMod(programid), sAction = getUrlParam('Action') === null ? 'add' : getUrlParam('Action').toLowerCase(); return g_api.ConnectLite('Authorize', 'GetAuthorize', { ProgramID: programid, TopModuleID: sTopMod }, function (res) { if (res.RESULT) { var saAuthorize = res.DATA.rel, saBtn = [], oHasBtn = {}, oLastBtn = null, initToolbar = function () {//等待 ToolBar(wedget)初始化ok后在執行,否則會報錯 $('#Toolbar').ToolBar({ btns: saBtn, fncallback: callback || function () { } }); transLang($('#Toolbar')); }, delayInitToolbar = function () { //initToolbar(); if ($.fn.ToolBar) { initToolbar(); } else { delayInitToolbar(); } }; $.each(saAuthorize, function (idx, roleright) { if (roleright.AllowRight) { var saRights = roleright.AllowRight.split('|'); $.each(saRights, function (e, btnright) { var sBtn = $.trim(btnright); if (oHasBtn[sBtn.toLowerCase()] === undefined) { oHasBtn[sBtn.toLowerCase()] = sBtn; } }); } }); if (!oHasBtn['upd']) { delete oHasBtn.save; delete oHasBtn.readd; } if (sAction === 'upd') { delete oHasBtn.readd; } if (sAction === 'add') { delete oHasBtn.del; } delete oHasBtn.upd; delete oHasBtn.view; for (var btnkey in oHasBtn) { var oBtn = {}; oBtn.key = oHasBtn[btnkey]; if (btnkey === 'leave') { oLastBtn = oBtn; oLastBtn.hotkey = 'ctrl + l'; } else { switch (btnkey) { case 'qry': oBtn.hotkey = 'enter'; break; case 'add': oBtn.hotkey = 'ctrl + i'; break; case 'readd': oBtn.hotkey = 'ctrl + r'; break; case 'save': oBtn.hotkey = 'ctrl + s'; break; case 'del': oBtn.hotkey = 'ctrl + d'; break; case 'clear': oBtn.hotkey = 'ctrl + q'; break; } saBtn.push(oBtn); } } if (cus) { saBtn.push.apply(saBtn, cus); } if (oLastBtn) { saBtn.push(oLastBtn); } delayInitToolbar(); let SpecialCse = 'InvoiceApplyForCustomer_View, InvoiceApplyForPersonal_View, BillChangeApply_View'; //button Ready 再執行 if (opt.PrgId.indexOf('_Upd') > -1 || SpecialCse.indexOf(opt.PrgId) > -1) { if (sAction === 'Upd'.toLocaleLowerCase()) {//判斷當前頁面是否有人在操作 parent.top.msgs.server.checkEdit(opt.PrgId, sCheckId); } $('#form_main').find(':input,select').not('[data-type=select2]').change(function () { if (!$(this).attr('data-trigger')) { bRequestStorage = true; } }); setTimeout(function () { $('#form_main').find('[data-type=select2]').change(function () { if (!$(this).attr('data-trigger')) { bRequestStorage = true; } }); }, 3000); } else { if (opt.PrgId.indexOf('_Qry') > -1) { parent.top.msgs.server.removeEditPrg(opt.PrgId.replace('_Qry', '_Upd'));//防止重複點擊首頁菜單導致之前編輯資料狀態無法移除 } var oQueryBtn = $('#Toolbar_Qry'); if (oQueryBtn.length > 0) { $('select').on('change', function (e, arg) { //select2下拉單改變自動查詢 setTimeout(function () { if (arg !== 'clear') {//清除動作(賦值)不查詢 $('#Toolbar_Qry').click(); } }, 10); }); $(':input[type="radio"],:input[type="checkbox"]').on('click', function (e, arg) { //radio值改變自動查詢 if (arg !== 'clear') {//清除動作(賦值)不查詢 $('#Toolbar_Qry').click(); } }); } } } }); }; /** * createPageTitle * @param {String} programid 程式id * @param {HTMLElement} handle 標有標籤 * @return {Object} ajax 物件 */ w.createPageTitle = function (programid, handle) { if (!programid) { return; } handle = handle || $('.page-title'); var saPrgList = g_db.GetItem('programList'), sModTree = "", saModTree = [], setProgramPath = function (sModuleID) { var oParent = getParentMod(sModuleID); if (oParent.ModuleID) { saModTree.unshift('
'); } if (oParent.ParentID) { setProgramPath(oParent.ParentID); } }; if (saPrgList == null || saPrgList === '') { return; } var saProgramList = $.parseJSON(saPrgList); var saProgram = $.grep(saProgramList, function (item) { return item.ModuleID === programid; }); if (saProgram.length === 0) { return; } var oProgram = saProgram[0]; if (!oProgram.ParentID) { return; } setProgramPath(oProgram.ParentID); saModTree.push('
'); sModTree = saModTree.join(''); //串起父層路徑名稱 return $.get(ComTmp.PageTitle).done(function (tmpl) { $.templates({ tmpl: tmpl }); handle.html($.render.tmpl({ ProgramName: "common." + oProgram.ModuleID, showTable: parent.top.SysSet.TbShowOrHide, MainTableName: oProgram.MainTableName, ModTree: sModTree })); transLang(handle); if (navigator.userAgent.match(/mobile/i)) { $('.ismobile').hide(); } }); }; /** * 產生下拉選單(公用) * @param {Object} list datalist * @param {String} id 顯示的id名稱 * @param {String} name 顯示的name名稱 * @param {Boolean} showid 是否顯示id * @param {String} cusattr 客制化添加屬性 * @param {Boolean} isreapet 是否允許重複 * @return {String} option html */ w.createOptions = function (list, id, name, showid, cusattr, isreapet) { isreapet == isreapet || true; list = list || []; var Options = [], originAry = []; if (typeof list === 'number') { var intNum = list; while (list > 0) { var svalue = intNum - list + 1; svalue = $.trim(svalue); Options.push($('