basic-service.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. if(typeof jqObject.data !== "string"){
  51. if(jqObject.toString().indexOf("FromData") !== -1) {
  52. return fetch(jqObject.url, {
  53. method: 'POST',
  54. body: jqObject.data
  55. });
  56. }
  57. }
  58. return fetch(jqObject.url, {
  59. method: 'POST',
  60. headers: {
  61. 'Content-Type': 'application/json'
  62. },
  63. body: jqObject.data
  64. });
  65. };
  66. this.utils_get_param = function (name) {
  67. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  68. var r = window.location.search.substr(1).match(reg);
  69. if (r != null) return unescape(r[2]);
  70. return null;
  71. };
  72. this.reloadPage = function () {
  73. location.reload()
  74. };
  75. this.get_server_url = function () {
  76. // AJAX
  77. this.output = this.goajax({url: this.Queue.SVR_URL + "fcFlow/list", timeout: 1000})
  78. .then(this.checkStatus)
  79. .then(this.parseJson)
  80. .then(this.onReachServer)
  81. .catch(this.onCheckFail);
  82. // .then(BasicFunction.onCheckFail);
  83. };
  84. this.onReachServer = function () {
  85. BasicFunction.Queue.IS_LOADED = true;
  86. BasicFunction.logwarn("Using SERVER : ");
  87. BasicFunction.logwarn(BasicFunction.Queue.SVR_URL);
  88. setTimeout(BasicFunction.parse_queue, 50, BasicFunction);
  89. };
  90. this.onCheckFail = function (errmsg) {
  91. if (BasicFunction.Queue.nowuse === BasicFunction.Queue.backup.length - 1) {
  92. BasicFunction.logwarn("Backup Failed : " + BasicFunction.Queue.backup[BasicFunction.Queue.nowuse]);
  93. BasicFunction.logwarn(this);
  94. var out = "";
  95. BasicFunction.Queue.backup.forEach(function (val, index) {
  96. out += index + ":[" +val +"] \n";
  97. });
  98. BasicFunction.logerror("抱歉, 服务器连接失败! \n 请确认 "+ out +" 其中之一可用");
  99. } else {
  100. BasicFunction.loglog(errmsg);
  101. BasicFunction.Queue.nowuse++;
  102. BasicFunction.Queue.SVR_URL = BasicFunction.Queue.backup[BasicFunction.Queue.nowuse];
  103. // AJAX
  104. BasicFunction.goajax({url: BasicFunction.Queue.SVR_URL + "fcFlow/list", timeout: 1000})
  105. .then(BasicFunction.checkStatus)
  106. .then(function (response) {return response.json();} )
  107. .then(BasicFunction.onReachServer)
  108. .catch(BasicFunction.onCheckFail);
  109. }
  110. };
  111. this.get_data = function (url, callback, data, onescope) {
  112. console.log('calling get_data()');
  113. let jsonData = data;
  114. if(typeof data !== "string"){
  115. if(data.toString().indexOf("FormData") !== -1){
  116. jsonData = data;
  117. }else {
  118. jsonData = JSON.stringify(jsonData);
  119. }
  120. }
  121. BasicFunction.Queue.list.push({url: url, callback: callback, gid: -1, data: jsonData, scope: onescope});
  122. };
  123. this.new_data_group = function (groupName, callback) {
  124. let gid = -1;
  125. BasicFunction.Queue.groups.forEach(function (val) {
  126. if (val.groupName === groupName) {
  127. gid = val.gid;
  128. }
  129. });
  130. if (gid === -1) {
  131. gid = BasicFunction.Queue.groupsCount;
  132. BasicFunction.Queue.groupsCount++;
  133. BasicFunction.Queue.groups.push({
  134. gid: gid, groupName: groupName, callme: callback, counter: 0
  135. });
  136. }
  137. return gid;
  138. };
  139. this.group_get_data = function (groupName, url, callback) {
  140. let gid = -1;
  141. BasicFunction.Queue.groups.forEach(function (val) {
  142. if (val.groupName === groupName) {
  143. gid = val.gid;
  144. }
  145. });
  146. if (gid === -1) {
  147. BasicFunction.send_alert("Group 方法使用错误!!!")
  148. }
  149. BasicFunction.Queue.list.push({url: url, callback: callback, gid: gid});
  150. };
  151. this.parse_queue = function () {
  152. BasicFunction.logverbose("Queue Length : " + BasicFunction.Queue.list.length);
  153. if (BasicFunction.Queue.temporary > new Date().getTime()) {
  154. for (let i = 0; i < BasicFunction.Queue.list.length; i++) {
  155. BasicFunction.Queue.list.pop();
  156. }
  157. }
  158. BasicFunction.Queue.temporary = 0;
  159. if (BasicFunction.Queue.list.length > 0) {
  160. let one = BasicFunction.Queue.list.pop();
  161. if (one.gid === -1) {
  162. request_data(one.url, one.callback, one.data, one.scope);
  163. } else {
  164. g_request_data(one.url, one.callback, one.gid, one.data, one.scope);
  165. }
  166. }
  167. if (BasicFunction.Queue.shouldStop === false) {
  168. setTimeout(BasicFunction.parse_queue, 50);
  169. }
  170. };
  171. this.parseJSON = function(response) {
  172. return response.json();
  173. };
  174. this.checkStatus = function(response) {
  175. if (response.status >= 200 && response.status < 300) {
  176. return response;
  177. }
  178. const error = new Error(response.statusText);
  179. error.response = response;
  180. throw error;
  181. };
  182. function request_data(url, callback, data, scope) {
  183. var vurl = "";
  184. if(url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1){
  185. vurl = url;
  186. } else {
  187. if(url.length > 2 && url.substring(0,2) === "!!"){
  188. vurl = url.substring(2);
  189. } else {
  190. vurl = BasicFunction.Queue.SVR_URL + url;
  191. }
  192. }
  193. BasicFunction.goajax({
  194. url: vurl,
  195. apiName: url,
  196. data: data,
  197. scope: scope,
  198. sendTime: new Date()
  199. }).then(BasicFunction.checkStatus)
  200. .then(BasicFunction.parseJson)
  201. .then(function(response){return response.json()})
  202. .then(callback)
  203. .catch(BasicFunction.on_fail);
  204. }
  205. function g_request_data(url, callback, gid) {
  206. BasicFunction.goajax({
  207. url: BasicFunction.Queue.SVR_URL + url,
  208. apiName: url,
  209. sendTime: new Date(),
  210. gid: gid,
  211. callme: callback
  212. }).then(BasicFunction.checkStatus)
  213. .then(BasicFunction.parseJson)
  214. .then(function(response){return response.json()})
  215. .then(BasicFunction.onReqeustDataReceived)
  216. .then(callback)
  217. .catch(BasicFunction.on_fail);
  218. }
  219. this.on_gp_success = function(response) {
  220. let obj = response.json();
  221. return obj;
  222. };
  223. this.onReqeustDataReceived = function(responseJson) {
  224. console.warn(responseJson);
  225. let a = responseJson;
  226. if (!BasicFunction.check_if_authfail(a)) {
  227. const error = new Error(responseJson.statusText);
  228. error.response = responseJson;
  229. throw error;
  230. }
  231. if (!BasicFunction.check_if_success(a)) {
  232. const error = new Error(responseJson.statusText);
  233. error.response = responseJson;
  234. throw error;
  235. }
  236. return responseJson;
  237. // BasicFunction.setCookieWithTimeout("doibyUser", "", -10);
  238. // location.href = "sign-in1.html?from=entrance-5&msg=server-redirect-detected";
  239. // return;
  240. };
  241. this.check_if_authfail = function (errormsg) {
  242. BasicFunction.logerror(errormsg);
  243. let a = errormsg;
  244. if (a == null || typeof a !== "string") {
  245. return false;
  246. } else {
  247. if (a.indexOf("login?from=") > 0 || a.startsWith("<!DOCTYPE html>") || a.indexOf("<!-- SME::LOGINPAGE -->") > 0) {
  248. return true;
  249. }
  250. }
  251. return false;
  252. };
  253. this.check_if_success = function (response) {
  254. // this == BasicFunction
  255. BasicFunction.loglog("---------------Check-If-Success----------------");
  256. let a = response.json();
  257. let b = response.status;
  258. if (typeof a === "string") {
  259. try {
  260. a = JSON.parse(a);
  261. } catch (e) {
  262. BasicFunction.logwarn("=---------- 异常 -----------=");
  263. BasicFunction.logwarn(a);
  264. BasicFunction.logwarn("=----------------------------=");
  265. BasicFunction.send_alert("信息失败 : 1 : " + e);
  266. return;
  267. }
  268. } else if (typeof a === "undefined") {
  269. BasicFunction.logwarn("=---------- 异常 -----------=");
  270. BasicFunction.logwarn(a);
  271. BasicFunction.logwarn("=------------------------------=");
  272. BasicFunction.logwarn(b);
  273. BasicFunction.logwarn("=------------------------------=");
  274. BasicFunction.send_alert("信息失败 - 2 " );
  275. return;
  276. }
  277. if (a.ret === "10000") {
  278. return true;
  279. } else {
  280. BasicFunction.logtrace();
  281. BasicFunction.logerror(b);
  282. BasicFunction.logerror(JSON.stringify(a));
  283. BasicFunction.send_alert("查询失败 : 请参阅控制台输出! ");
  284. }
  285. return false;
  286. };
  287. this.on_fail = function (msg) {
  288. BasicFunction.Queue.errorCount += 1;
  289. if (BasicFunction.Queue.errorCount >= 10) {
  290. BasicFunction.Queue.errorCount = 0;
  291. BasicFunction.Queue.temporary = new Date().getTime() + 30 * 1000;
  292. BasicFunction.Queue.shouldStop = true;
  293. BasicFunction.logwarn("----- Too many failure, temporary stop HTTP ------");
  294. BasicFunction.send_alert("很抱歉,网络错误数量过多,暂时终止HTTP功能30s");
  295. }
  296. BasicFunction.send_alert(" 很抱歉,网络错误,请查看 Console");
  297. BasicFunction.logwarn("----- 网络请求失败 ---------");
  298. BasicFunction.logwarn("-----------msg-------------");
  299. BasicFunction.logwarn(JSON.stringify(msg));
  300. BasicFunction.logwarn("----------------------------");
  301. };
  302. this.first_parse = function (ajax, obj) {
  303. if (typeof obj === "string") {
  304. obj = JSON.parse(obj);
  305. }
  306. if (typeof obj !== "object") {
  307. BasicFunction.logwarn(ajax);
  308. throw "Error ! Parsing JSON failed ." + JSON.stringify(obj);
  309. }
  310. if (obj.ret === "10000") {
  311. return obj.model;
  312. } else {
  313. BasicFunction.logwarn(ajax);
  314. throw "Error ! Server returned error." + JSON.stringify(obj);
  315. }
  316. };
  317. this.send_alert = function (a, b) {
  318. if (BasicFunction.Queue.shouldStop) return;
  319. if (BasicFunction.AlertClosingTimeout > 0) {
  320. clearTimeout(BasicFunction.AlertClosingTimeout);
  321. }
  322. BasicFunction.logwarn(a);
  323. BasicFunction.logwarn(b);
  324. // alert(a +"\n"+ b);
  325. BasicFunction.AlertClosingTimeout = setTimeout(function () {
  326. //$("#mpAlert").hide();
  327. }, 10000);
  328. };
  329. this.getUserName = function (uid) {
  330. let uname = null;
  331. BasicFunction.Users.list.forEach(function (val, aid) {
  332. BasicFunction.loglog(aid);
  333. if (val.worker.staffId === uid) {
  334. uname = val.worker.staffName;
  335. }
  336. });
  337. if (uname == null) {
  338. if (uid !== 0) {
  339. BasicFunction.get_data("oaStaff/list?staffId=" + uid, BasicFunction.on_username_retn);
  340. return "[用户:" + uid + "]";
  341. } else return "[用户:" + uid + "]";
  342. } else {
  343. return uname;
  344. }
  345. };
  346. this.on_username_retn = function (obj) {
  347. let uid = this.url.substring(this.url.indexOf("staffId=") + 8);
  348. let ruid = parseInt(uid);
  349. let out = BasicFunction.first_parse(this, obj);
  350. if (out.list.length > 0) {
  351. BasicFunction.Users.list.push({
  352. uid: ruid, worker: out.list[0]
  353. });
  354. }
  355. };
  356. this.setCookieWithTimeout = function (name, value, liveMinutes) {
  357. if (liveMinutes === undefined || liveMinutes == null) {
  358. liveMinutes = 60 * 2;
  359. }
  360. if (typeof (liveMinutes) !== 'number') {
  361. liveMinutes = 60 * 2;//默认120分钟
  362. }
  363. let minutes = liveMinutes * 60 * 1000;
  364. let exp = new Date();
  365. exp.setTime(exp.getTime() + minutes + 8 * 3600 * 1000);
  366. //path=/表示全站有效,而不是当前页
  367. document.cookie = name + "=" + value + ";path=/;expires=" + exp.toUTCString();
  368. };
  369. this.setCookie = function (c_name, value, expiredays) {
  370. let exdate = new Date();
  371. exdate.setDate(exdate.getDate() + expiredays);
  372. document.cookie = c_name + "=" + escape(value) +
  373. ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
  374. };
  375. this.getCookie = function (c_name) {
  376. if (document.cookie.length > 0) {
  377. let c_start = document.cookie.indexOf(c_name + "=");
  378. if (c_start !== -1) {
  379. c_start = c_start + c_name.length + 1;
  380. let c_end = document.cookie.indexOf(";", c_start);
  381. if (c_end === -1) c_end = document.cookie.length;
  382. return unescape(document.cookie.substring(c_start, c_end))
  383. }
  384. }
  385. return "";
  386. };
  387. this.getSigned = function() {
  388. var APPID = "wx47691e7aabf77631";
  389. var re_uri = "https://gift.fogice.com/wxjs/oauth.php?otp=" + this.utils_get_parm("otp");
  390. var redir = encodeURIComponent(re_uri);
  391. location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ APPID+ "&redirect_uri=" +redir+ "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
  392. };
  393. this.gotoJsLogin = function() {
  394. var APPID = "wx47691e7aabf77631";
  395. var re_uri = "https://gift.fogice.com/wxjs/oauth.php?otp=" + this.utils_get_parm("otp");
  396. var redir = encodeURIComponent(re_uri);
  397. location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ APPID+ "&redirect_uri=" +redir+ "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
  398. };
  399. /*this.userId = utils_get_param("userId");
  400. this.getUserId = function() {
  401. BasicFunction.loglog("Original USERID : " + userId);
  402. let use = getCookie("doibyUser");
  403. if (use == null || use === undefined || use.length <= 0) {
  404. location.href = "sign-in1.html?from=entrance-1&msg=nologin-mustauth";
  405. return;
  406. }
  407. BasicFunction.loglog("Got UID From COOKIE : " + use);
  408. try {
  409. let mm = parseInt(use);
  410. if (mm > 0) {
  411. BasicFunction.userId = mm;
  412. }
  413. } catch (e) {
  414. location.href = "sign-in1.html?from=entrance-1&msg=cookie-wrong-format";
  415. return;
  416. }
  417. BasicFunction.loglog("Got UserId Eventually : " + userId);
  418. };*/
  419. this.get_server_url();
  420. //this.on_document_load();
  421. })();
  422. window.BasicFunction = BasicFunction;
  423. export {
  424. BasicFunction
  425. };