basic-service.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /**
  2. *
  3. * Basic
  4. * 所有页面的共用基础功能
  5. * // TODO: 文件名可能需要修改
  6. * // TODO: failing ES-Lint
  7. * // TODO: Automated Test
  8. *
  9. * dependency:
  10. * jQuery (ajax, selector)
  11. *
  12. * @ jason.lu
  13. * */
  14. import 'whatwg-fetch';
  15. var BasicFunction = new (function () {
  16. this.Queue = {
  17. THRESHOLD: 1000,
  18. IS_LOADED: false,
  19. nowuse: 0, SVR_URL: "/server/",
  20. groupsCount: 0, groups: [],
  21. shouldStop: false,
  22. backup: ["/server/",
  23. "http://127.0.0.1:8866/server/",
  24. "http://south.niimei.com:8866/server/",
  25. "https://4.niimei.com/server/"],
  26. list: [], temporary: 0, errorCount: 0
  27. };
  28. this.Users = {list: []};
  29. this.Sectors = {list: []};
  30. this.AlertClosingTimeout = 0;
  31. this.loglog = function (a) {
  32. console.log(a);
  33. };
  34. this.logwarn = function (obj) {
  35. console.warn(obj);
  36. };
  37. this.logerror = function (obj) {
  38. console.warn(obj);
  39. };
  40. this.logtrace = function () {
  41. console.trace();
  42. };
  43. this.logverbose = function () {
  44. // Not Echoing
  45. };
  46. this.asserThat = function(cond, why) {
  47. console.assert(cond, why);
  48. };
  49. this.goajax = function (jqObject) {
  50. return fetch(jqObject.url, {
  51. method: 'POST',
  52. headers: {
  53. 'Content-Type': 'application/json',
  54. //'x-doiby-authenticate' : 'CISICMIEINAOQPMDPWIDNENU'
  55. },
  56. body: jqObject.data
  57. });
  58. };
  59. this.utils_get_param = function (name) {
  60. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  61. var r = window.location.search.substr(1).match(reg);
  62. if (r != null) return unescape(r[2]);
  63. return null;
  64. };
  65. this.reloadPage = function () {
  66. location.reload()
  67. };
  68. this.get_server_url = function () {
  69. // AJAX
  70. this.output = this.goajax({url: this.Queue.SVR_URL + "fcFlow/list", timeout: 1000})
  71. .then(this.checkStatus)
  72. .then(this.parseJson)
  73. .then(this.onReachServer)
  74. .catch(this.onCheckFail);
  75. // .then(BasicFunction.onCheckFail);
  76. };
  77. this.onReachServer = function (checkResponse) {
  78. BasicFunction.Queue.IS_LOADED = true;
  79. BasicFunction.logwarn("Using SERVER : ");
  80. BasicFunction.logwarn(BasicFunction.Queue.SVR_URL);
  81. setTimeout(BasicFunction.parse_queue, 50, BasicFunction);
  82. };
  83. this.onCheckFail = function (errmsg) {
  84. if (BasicFunction.Queue.nowuse === BasicFunction.Queue.backup.length - 1) {
  85. BasicFunction.logwarn("Backup Failed : " + BasicFunction.Queue.backup[BasicFunction.Queue.nowuse]);
  86. BasicFunction.logwarn(this);
  87. var out = "";
  88. BasicFunction.Queue.backup.forEach(function (val, index, arr) {
  89. out += index + ":[" +val +"] \n";
  90. });
  91. BasicFunction.logerror("抱歉, 服务器连接失败! \n 请确认 "+ out +" 其中之一可用");
  92. } else {
  93. BasicFunction.loglog(errmsg);
  94. BasicFunction.Queue.nowuse++;
  95. BasicFunction.Queue.SVR_URL = BasicFunction.Queue.backup[BasicFunction.Queue.nowuse];
  96. // AJAX
  97. BasicFunction.goajax({url: BasicFunction.Queue.SVR_URL + "fcFlow/list", timeout: 1000})
  98. .then(BasicFunction.checkStatus)
  99. .then(BasicFunction.parseJson)
  100. .then(BasicFunction.onReachServer)
  101. .catch(BasicFunction.onCheckFail);
  102. //.fail(BasicFunction.onCheckFail).done(BasicFunction.onReachServer);
  103. }
  104. };
  105. this.get_data = function (url, callback, scope) {
  106. BasicFunction.Queue.list.push({url: url, callback: callback, gid: -1, scope: scope});
  107. };
  108. this.new_data_group = function (groupName, callback) {
  109. var gid = -1;
  110. BasicFunction.Queue.groups.forEach(function (val) {
  111. if (val.groupName === groupName) {
  112. gid = val.gid;
  113. }
  114. });
  115. if (gid === -1) {
  116. gid = BasicFunction.Queue.groupsCount;
  117. BasicFunction.Queue.groupsCount++;
  118. BasicFunction.Queue.groups.push({
  119. gid: gid, groupName: groupName, callme: callback, counter: 0
  120. });
  121. }
  122. return gid;
  123. };
  124. this.group_get_data = function (groupName, url, callback) {
  125. var gid = -1;
  126. BasicFunction.Queue.groups.forEach(function (val) {
  127. if (val.groupName === groupName) {
  128. gid = val.gid;
  129. }
  130. });
  131. if (gid === -1) {
  132. BasicFunction.send_alert("Group 方法使用错误!!!")
  133. }
  134. BasicFunction.Queue.list.push({url: url, callback: callback, gid: gid});
  135. };
  136. this.parse_queue = function () {
  137. BasicFunction.logverbose("Queue Length : " + BasicFunction.Queue.list.length);
  138. if (BasicFunction.Queue.temporary > new Date().getTime()) {
  139. for (let i = 0; i < BasicFunction.Queue.list.length; i++) {
  140. BasicFunction.Queue.list.pop();
  141. }
  142. }
  143. BasicFunction.Queue.temporary = 0;
  144. if (BasicFunction.Queue.list.length > 0) {
  145. let one = BasicFunction.Queue.list.pop();
  146. if (one.gid === -1) {
  147. request_data(one.url, one.callback, one.scope);
  148. } else {
  149. g_request_data(one.url, one.callback, one.gid, one.scope);
  150. }
  151. }
  152. if (BasicFunction.Queue.shouldStop === false) {
  153. setTimeout(BasicFunction.parse_queue, 50);
  154. }
  155. };
  156. this.parseJSON = function(response) {
  157. return response.json();
  158. };
  159. this.checkStatus = function(response) {
  160. if (response.status >= 200 && response.status < 300) {
  161. return response;
  162. }
  163. const error = new Error(response.statusText);
  164. error.response = response;
  165. throw error;
  166. };
  167. function request_data(url, callback, scope) {
  168. BasicFunction.goajax({
  169. url: BasicFunction.Queue.SVR_URL + url,
  170. apiName: url,
  171. sendTime: new Date()
  172. }).then(BasicFunction.checkStatus)
  173. .then(BasicFunction.parseJson)
  174. .then(function(response){return response.json()})
  175. .then(callback)
  176. .catch(BasicFunction.on_fail);
  177. }
  178. function g_request_data(url, callback, gid) {
  179. BasicFunction.goajax({
  180. url: BasicFunction.Queue.SVR_URL + url,
  181. apiName: url,
  182. sendTime: new Date(),
  183. gid: gid,
  184. callme: callback
  185. }).then(BasicFunction.checkStatus)
  186. .then(BasicFunction.parseJson)
  187. .then(function(response){return response.json()})
  188. .then(BasicFunction.onReqeustDataReceived)
  189. .then(callback)
  190. .catch(BasicFunction.on_fail);
  191. }
  192. this.on_gp_success = function(response) {
  193. var obj = response.json();
  194. return obj;
  195. };
  196. this.onReqeustDataReceived = function(responseJson) {
  197. console.warn(responseJson);
  198. var a = responseJson;
  199. if (!BasicFunction.check_if_authfail(a)) {
  200. const error = new Error(responseJson.statusText);
  201. error.response = responseJson;
  202. throw error;
  203. }
  204. if (!BasicFunction.check_if_success(a)) {
  205. const error = new Error(responseJson.statusText);
  206. error.response = responseJson;
  207. throw error;
  208. }
  209. return responseJson;
  210. // BasicFunction.setCookieWithTimeout("doibyUser", "", -10);
  211. // location.href = "sign-in1.html?from=entrance-5&msg=server-redirect-detected";
  212. // return;
  213. };
  214. this.check_if_authfail = function (errormsg) {
  215. BasicFunction.logerror(errormsg);
  216. var a = errormsg;
  217. if (a == null || typeof a !== "string") {
  218. return false;
  219. } else {
  220. if (a.indexOf("login?from=") > 0 || a.startsWith("<!DOCTYPE html>") || a.indexOf("<!-- SME::LOGINPAGE -->") > 0) {
  221. return true;
  222. }
  223. }
  224. return false;
  225. };
  226. this.check_if_success = function (response) {
  227. // this == BasicFunction
  228. BasicFunction.loglog("---------------Check-If-Success----------------");
  229. var a = response.json();
  230. var b = response.status;
  231. if (typeof a === "string") {
  232. try {
  233. a = JSON.parse(a);
  234. } catch (e) {
  235. BasicFunction.logwarn("=---------- 异常 -----------=");
  236. BasicFunction.logwarn(a);
  237. BasicFunction.logwarn("=----------------------------=");
  238. BasicFunction.send_alert("信息失败 : 1 : " + e);
  239. return;
  240. }
  241. } else if (typeof a === "undefined") {
  242. BasicFunction.logwarn("=---------- 异常 -----------=");
  243. BasicFunction.logwarn(a);
  244. BasicFunction.logwarn("=------------------------------=");
  245. BasicFunction.logwarn(b);
  246. BasicFunction.logwarn("=------------------------------=");
  247. BasicFunction.send_alert("信息失败 - 2 " );
  248. return;
  249. }
  250. if (a.ret === "10000") {
  251. return true;
  252. } else {
  253. BasicFunction.logtrace();
  254. BasicFunction.logerror(b);
  255. BasicFunction.logerror(JSON.stringify(a));
  256. BasicFunction.send_alert("查询失败 : 请参阅控制台输出! ");
  257. }
  258. return false;
  259. };
  260. this.on_fail = function (msg) {
  261. BasicFunction.Queue.errorCount += 1;
  262. if (BasicFunction.Queue.errorCount >= 10) {
  263. BasicFunction.Queue.errorCount = 0;
  264. BasicFunction.Queue.temporary = new Date().getTime() + 30 * 1000;
  265. BasicFunction.Queue.shouldStop = true;
  266. BasicFunction.logwarn("----- Too many failure, temporary stop HTTP ------");
  267. BasicFunction.send_alert("很抱歉,网络错误数量过多,暂时终止HTTP功能30s");
  268. }
  269. BasicFunction.send_alert(" 很抱歉,网络错误,请查看 Console");
  270. BasicFunction.logwarn("----- 网络请求失败 ---------");
  271. BasicFunction.logwarn("-----------msg-------------");
  272. BasicFunction.logwarn(JSON.stringify(msg));
  273. BasicFunction.logwarn("----------------------------");
  274. };
  275. this.first_parse = function (ajax, obj) {
  276. if (typeof obj === "string") {
  277. obj = JSON.parse(obj);
  278. }
  279. if (typeof obj !== "object") {
  280. BasicFunction.logwarn(ajax);
  281. throw "Error ! Parsing JSON failed ." + JSON.stringify(obj);
  282. }
  283. if (obj.ret === "10000") {
  284. return obj.model;
  285. } else {
  286. BasicFunction.logwarn(ajax);
  287. throw "Error ! Server returned error." + JSON.stringify(obj);
  288. }
  289. };
  290. this.send_alert = function (a, b) {
  291. if (BasicFunction.Queue.shouldStop) return;
  292. if (BasicFunction.AlertClosingTimeout > 0) {
  293. clearTimeout(BasicFunction.AlertClosingTimeout);
  294. }
  295. BasicFunction.logwarn(a);
  296. BasicFunction.logwarn(b);
  297. // alert(a +"\n"+ b);
  298. BasicFunction.AlertClosingTimeout = setTimeout(function () {
  299. //$("#mpAlert").hide();
  300. }, 10000);
  301. };
  302. this.getUserName = function (uid) {
  303. var uname = null;
  304. BasicFunction.Users.list.forEach(function (val, aid) {
  305. BasicFunction.loglog(aid);
  306. if (val.worker.staffId === uid) {
  307. uname = val.worker.staffName;
  308. }
  309. });
  310. if (uname == null) {
  311. if (uid !== 0) {
  312. BasicFunction.get_data("oaStaff/list?staffId=" + uid, BasicFunction.on_username_retn);
  313. return "[用户:" + uid + "]";
  314. } else return "[用户:" + uid + "]";
  315. } else {
  316. return uname;
  317. }
  318. };
  319. this.on_username_retn = function (obj) {
  320. var uid = this.url.substring(this.url.indexOf("staffId=") + 8);
  321. let ruid = parseInt(uid);
  322. var out = BasicFunction.first_parse(this, obj);
  323. if (out.list.length > 0) {
  324. BasicFunction.Users.list.push({
  325. uid: ruid, worker: out.list[0]
  326. });
  327. }
  328. };
  329. this.setCookieWithTimeout = function (name, value, liveMinutes) {
  330. if (liveMinutes === undefined || liveMinutes == null) {
  331. liveMinutes = 60 * 2;
  332. }
  333. if (typeof (liveMinutes) !== 'number') {
  334. liveMinutes = 60 * 2;//默认120分钟
  335. }
  336. var minutes = liveMinutes * 60 * 1000;
  337. var exp = new Date();
  338. exp.setTime(exp.getTime() + minutes + 8 * 3600 * 1000);
  339. //path=/表示全站有效,而不是当前页
  340. document.cookie = name + "=" + value + ";path=/;expires=" + exp.toUTCString();
  341. };
  342. this.setCookie = function (c_name, value, expiredays) {
  343. var exdate = new Date();
  344. exdate.setDate(exdate.getDate() + expiredays);
  345. document.cookie = c_name + "=" + escape(value) +
  346. ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
  347. };
  348. this.getCookie = function (c_name) {
  349. if (document.cookie.length > 0) {
  350. var c_start = document.cookie.indexOf(c_name + "=");
  351. if (c_start !== -1) {
  352. c_start = c_start + c_name.length + 1;
  353. var c_end = document.cookie.indexOf(";", c_start);
  354. if (c_end === -1) c_end = document.cookie.length;
  355. return unescape(document.cookie.substring(c_start, c_end))
  356. }
  357. }
  358. return "";
  359. };
  360. /*this.userId = utils_get_param("userId");
  361. this.getUserId = function() {
  362. BasicFunction.loglog("Original USERID : " + userId);
  363. var use = getCookie("doibyUser");
  364. if (use == null || use === undefined || use.length <= 0) {
  365. location.href = "sign-in1.html?from=entrance-1&msg=nologin-mustauth";
  366. return;
  367. }
  368. BasicFunction.loglog("Got UID From COOKIE : " + use);
  369. try {
  370. var mm = parseInt(use);
  371. if (mm > 0) {
  372. BasicFunction.userId = mm;
  373. }
  374. } catch (e) {
  375. location.href = "sign-in1.html?from=entrance-1&msg=cookie-wrong-format";
  376. return;
  377. }
  378. BasicFunction.loglog("Got UserId Eventually : " + userId);
  379. };*/
  380. this.get_server_url();
  381. //this.on_document_load();
  382. })();
  383. window.BasicFunction = BasicFunction;
  384. export {
  385. BasicFunction
  386. };