basic-service.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. console.log('----------using get_data()-----------');
  107. BasicFunction.Queue.list.push({url: url, callback: callback, gid: -1, scope: scope});
  108. };
  109. this.new_data_group = function (groupName, callback) {
  110. var gid = -1;
  111. BasicFunction.Queue.groups.forEach(function (val) {
  112. if (val.groupName === groupName) {
  113. gid = val.gid;
  114. }
  115. });
  116. if (gid === -1) {
  117. gid = BasicFunction.Queue.groupsCount;
  118. BasicFunction.Queue.groupsCount++;
  119. BasicFunction.Queue.groups.push({
  120. gid: gid, groupName: groupName, callme: callback, counter: 0
  121. });
  122. }
  123. return gid;
  124. };
  125. this.group_get_data = function (groupName, url, callback) {
  126. var gid = -1;
  127. BasicFunction.Queue.groups.forEach(function (val) {
  128. if (val.groupName === groupName) {
  129. gid = val.gid;
  130. }
  131. });
  132. if (gid === -1) {
  133. BasicFunction.send_alert("Group 方法使用错误!!!")
  134. }
  135. BasicFunction.Queue.list.push({url: url, callback: callback, gid: gid});
  136. };
  137. this.parse_queue = function () {
  138. BasicFunction.logverbose("Queue Length : " + BasicFunction.Queue.list.length);
  139. if (BasicFunction.Queue.temporary > new Date().getTime()) {
  140. for (let i = 0; i < BasicFunction.Queue.list.length; i++) {
  141. BasicFunction.Queue.list.pop();
  142. }
  143. }
  144. BasicFunction.Queue.temporary = 0;
  145. if (BasicFunction.Queue.list.length > 0) {
  146. let one = BasicFunction.Queue.list.pop();
  147. if (one.gid === -1) {
  148. request_data(one.url, one.callback, one.scope);
  149. } else {
  150. g_request_data(one.url, one.callback, one.gid, one.scope);
  151. }
  152. }
  153. if (BasicFunction.Queue.shouldStop === false) {
  154. setTimeout(BasicFunction.parse_queue, 50);
  155. }
  156. };
  157. this.parseJSON = function(response) {
  158. return response.json();
  159. };
  160. this.checkStatus = function(response) {
  161. if (response.status >= 200 && response.status < 300) {
  162. return response;
  163. }
  164. const error = new Error(response.statusText);
  165. error.response = response;
  166. throw error;
  167. };
  168. function request_data(url, callback, scope) {
  169. BasicFunction.goajax({
  170. url: BasicFunction.Queue.SVR_URL + url,
  171. apiName: url,
  172. sendTime: new Date()
  173. }).then(BasicFunction.checkStatus)
  174. .then(BasicFunction.parseJson)
  175. .then(function(response){return response.json()})
  176. .then(callback)
  177. .catch(BasicFunction.on_fail);
  178. }
  179. function g_request_data(url, callback, gid) {
  180. BasicFunction.goajax({
  181. url: BasicFunction.Queue.SVR_URL + url,
  182. apiName: url,
  183. sendTime: new Date(),
  184. gid: gid,
  185. callme: callback
  186. }).then(BasicFunction.checkStatus)
  187. .then(BasicFunction.parseJson)
  188. .then(function(response){return response.json()})
  189. .then(BasicFunction.onReqeustDataReceived)
  190. .then(callback)
  191. .catch(BasicFunction.on_fail);
  192. }
  193. this.on_gp_success = function(response) {
  194. var obj = response.json();
  195. return obj;
  196. };
  197. this.onReqeustDataReceived = function(responseJson) {
  198. console.warn(responseJson);
  199. var a = responseJson;
  200. if (!BasicFunction.check_if_authfail(a)) {
  201. const error = new Error(responseJson.statusText);
  202. error.response = responseJson;
  203. throw error;
  204. }
  205. if (!BasicFunction.check_if_success(a)) {
  206. const error = new Error(responseJson.statusText);
  207. error.response = responseJson;
  208. throw error;
  209. }
  210. return responseJson;
  211. // BasicFunction.setCookieWithTimeout("doibyUser", "", -10);
  212. // location.href = "sign-in1.html?from=entrance-5&msg=server-redirect-detected";
  213. // return;
  214. };
  215. this.check_if_authfail = function (errormsg) {
  216. BasicFunction.logerror(errormsg);
  217. var a = errormsg;
  218. if (a == null || typeof a !== "string") {
  219. return false;
  220. } else {
  221. if (a.indexOf("login?from=") > 0 || a.startsWith("<!DOCTYPE html>") || a.indexOf("<!-- SME::LOGINPAGE -->") > 0) {
  222. return true;
  223. }
  224. }
  225. return false;
  226. };
  227. this.check_if_success = function (response) {
  228. // this == BasicFunction
  229. BasicFunction.loglog("---------------Check-If-Success----------------");
  230. var a = response.json();
  231. var b = response.status;
  232. if (typeof a === "string") {
  233. try {
  234. a = JSON.parse(a);
  235. } catch (e) {
  236. BasicFunction.logwarn("=---------- 异常 -----------=");
  237. BasicFunction.logwarn(a);
  238. BasicFunction.logwarn("=----------------------------=");
  239. BasicFunction.send_alert("信息失败 : 1 : " + e);
  240. return;
  241. }
  242. } else if (typeof a === "undefined") {
  243. BasicFunction.logwarn("=---------- 异常 -----------=");
  244. BasicFunction.logwarn(a);
  245. BasicFunction.logwarn("=------------------------------=");
  246. BasicFunction.logwarn(b);
  247. BasicFunction.logwarn("=------------------------------=");
  248. BasicFunction.send_alert("信息失败 - 2 " );
  249. return;
  250. }
  251. if (a.ret === "10000") {
  252. return true;
  253. } else {
  254. BasicFunction.logtrace();
  255. BasicFunction.logerror(b);
  256. BasicFunction.logerror(JSON.stringify(a));
  257. BasicFunction.send_alert("查询失败 : 请参阅控制台输出! ");
  258. }
  259. return false;
  260. };
  261. this.on_fail = function (msg) {
  262. BasicFunction.Queue.errorCount += 1;
  263. if (BasicFunction.Queue.errorCount >= 10) {
  264. BasicFunction.Queue.errorCount = 0;
  265. BasicFunction.Queue.temporary = new Date().getTime() + 30 * 1000;
  266. BasicFunction.Queue.shouldStop = true;
  267. BasicFunction.logwarn("----- Too many failure, temporary stop HTTP ------");
  268. BasicFunction.send_alert("很抱歉,网络错误数量过多,暂时终止HTTP功能30s");
  269. }
  270. BasicFunction.send_alert(" 很抱歉,网络错误,请查看 Console");
  271. BasicFunction.logwarn("----- 网络请求失败 ---------");
  272. BasicFunction.logwarn("-----------msg-------------");
  273. BasicFunction.logwarn(JSON.stringify(msg));
  274. BasicFunction.logwarn("----------------------------");
  275. };
  276. this.first_parse = function (ajax, obj) {
  277. if (typeof obj === "string") {
  278. obj = JSON.parse(obj);
  279. }
  280. if (typeof obj !== "object") {
  281. BasicFunction.logwarn(ajax);
  282. throw "Error ! Parsing JSON failed ." + JSON.stringify(obj);
  283. }
  284. if (obj.ret === "10000") {
  285. return obj.model;
  286. } else {
  287. BasicFunction.logwarn(ajax);
  288. throw "Error ! Server returned error." + JSON.stringify(obj);
  289. }
  290. };
  291. this.send_alert = function (a, b) {
  292. if (BasicFunction.Queue.shouldStop) return;
  293. if (BasicFunction.AlertClosingTimeout > 0) {
  294. clearTimeout(BasicFunction.AlertClosingTimeout);
  295. }
  296. BasicFunction.logwarn(a);
  297. BasicFunction.logwarn(b);
  298. // alert(a +"\n"+ b);
  299. BasicFunction.AlertClosingTimeout = setTimeout(function () {
  300. //$("#mpAlert").hide();
  301. }, 10000);
  302. };
  303. this.getUserName = function (uid) {
  304. var uname = null;
  305. BasicFunction.Users.list.forEach(function (val, aid) {
  306. BasicFunction.loglog(aid);
  307. if (val.worker.staffId === uid) {
  308. uname = val.worker.staffName;
  309. }
  310. });
  311. if (uname == null) {
  312. if (uid !== 0) {
  313. BasicFunction.get_data("oaStaff/list?staffId=" + uid, BasicFunction.on_username_retn);
  314. return "[用户:" + uid + "]";
  315. } else return "[用户:" + uid + "]";
  316. } else {
  317. return uname;
  318. }
  319. };
  320. this.on_username_retn = function (obj) {
  321. var uid = this.url.substring(this.url.indexOf("staffId=") + 8);
  322. let ruid = parseInt(uid);
  323. var out = BasicFunction.first_parse(this, obj);
  324. if (out.list.length > 0) {
  325. BasicFunction.Users.list.push({
  326. uid: ruid, worker: out.list[0]
  327. });
  328. }
  329. };
  330. this.setCookieWithTimeout = function (name, value, liveMinutes) {
  331. if (liveMinutes === undefined || liveMinutes == null) {
  332. liveMinutes = 60 * 2;
  333. }
  334. if (typeof (liveMinutes) !== 'number') {
  335. liveMinutes = 60 * 2;//默认120分钟
  336. }
  337. var minutes = liveMinutes * 60 * 1000;
  338. var exp = new Date();
  339. exp.setTime(exp.getTime() + minutes + 8 * 3600 * 1000);
  340. //path=/表示全站有效,而不是当前页
  341. document.cookie = name + "=" + value + ";path=/;expires=" + exp.toUTCString();
  342. };
  343. this.setCookie = function (c_name, value, expiredays) {
  344. var exdate = new Date();
  345. exdate.setDate(exdate.getDate() + expiredays);
  346. document.cookie = c_name + "=" + escape(value) +
  347. ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
  348. };
  349. this.getCookie = function (c_name) {
  350. if (document.cookie.length > 0) {
  351. var c_start = document.cookie.indexOf(c_name + "=");
  352. if (c_start !== -1) {
  353. c_start = c_start + c_name.length + 1;
  354. var c_end = document.cookie.indexOf(";", c_start);
  355. if (c_end === -1) c_end = document.cookie.length;
  356. return unescape(document.cookie.substring(c_start, c_end))
  357. }
  358. }
  359. return "";
  360. };
  361. /*this.userId = utils_get_param("userId");
  362. this.getUserId = function() {
  363. BasicFunction.loglog("Original USERID : " + userId);
  364. var use = getCookie("doibyUser");
  365. if (use == null || use === undefined || use.length <= 0) {
  366. location.href = "sign-in1.html?from=entrance-1&msg=nologin-mustauth";
  367. return;
  368. }
  369. BasicFunction.loglog("Got UID From COOKIE : " + use);
  370. try {
  371. var mm = parseInt(use);
  372. if (mm > 0) {
  373. BasicFunction.userId = mm;
  374. }
  375. } catch (e) {
  376. location.href = "sign-in1.html?from=entrance-1&msg=cookie-wrong-format";
  377. return;
  378. }
  379. BasicFunction.loglog("Got UserId Eventually : " + userId);
  380. };*/
  381. this.get_server_url();
  382. //this.on_document_load();
  383. })();
  384. window.BasicFunction = BasicFunction;
  385. export {
  386. BasicFunction
  387. };