util.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. var api = require('./api');
  2. function formatTime(date) {
  3. var year = date.getFullYear()
  4. var month = date.getMonth() + 1
  5. var day = date.getDate()
  6. var hour = date.getHours()
  7. var minute = date.getMinutes()
  8. var second = date.getSeconds()
  9. return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  10. }
  11. function formatTime_1(fmt, date) {
  12. date = new Date(date)
  13. let ret;
  14. const opt = {
  15. "Y+": date.getFullYear().toString(), // 年
  16. "m+": (date.getMonth() + 1).toString(), // 月
  17. "d+": date.getDate().toString(), // 日
  18. "H+": date.getHours().toString(), // 时
  19. "M+": date.getMinutes().toString(), // 分
  20. "S+": date.getSeconds().toString(), // 秒
  21. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  22. };
  23. for (let k in opt) {
  24. ret = new RegExp("(" + k + ")").exec(fmt);
  25. if (ret) {
  26. fmt = fmt.replace(
  27. ret[1],
  28. ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
  29. );
  30. }
  31. }
  32. return fmt;
  33. }
  34. const formatNumber = n => {
  35. n = n.toString()
  36. return n[1] ? n : '0' + n
  37. }
  38. function formatTimeNum(number, format) {
  39. var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  40. var returnArr = [];
  41. var date = new Date(number * 1000);
  42. returnArr.push(date.getFullYear());
  43. returnArr.push(formatNumber(date.getMonth() + 1));
  44. returnArr.push(formatNumber(date.getDate()));
  45. returnArr.push(formatNumber(date.getHours()));
  46. returnArr.push(formatNumber(date.getMinutes()));
  47. returnArr.push(formatNumber(date.getSeconds()));
  48. for (var i in returnArr) {
  49. format = format.replace(formateArr[i], returnArr[i]);
  50. }
  51. return format;
  52. }
  53. function testMobile(num) {
  54. console.log
  55. var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(16[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
  56. if (num.length == 0) {
  57. wx.showToast({
  58. title: '手机号为空',
  59. image: '/images/icon/icon_error.png',
  60. })
  61. return false;
  62. } else if (num.length < 11) {
  63. wx.showToast({
  64. title: '手机号长度有误!',
  65. image: '/images/icon/icon_error.png',
  66. })
  67. return false;
  68. } else if (!myreg.test(num)) {
  69. wx.showToast({
  70. title: '手机号有误!',
  71. image: '/images/icon/icon_error.png',
  72. })
  73. return false;
  74. } else {
  75. return true;
  76. }
  77. }
  78. /**
  79. * 封封微信的的request
  80. */
  81. function request(url, data = {}, method = "GET") {
  82. return new Promise(function (resolve, reject) {
  83. wx.request({
  84. url: url,
  85. data: data,
  86. method: method,
  87. header: {
  88. 'Content-Type': 'application/json',
  89. 'X-Nideshop-Token': wx.getStorageSync('token')
  90. },
  91. success: function (res) {
  92. if (res.statusCode == 200) {
  93. if (res.data.errno == 401) {
  94. //需要登录后才可以操作
  95. let code = null;
  96. return login().then((res) => {
  97. code = res.code;
  98. return getUserInfo();
  99. }).then((userInfo) => {
  100. //登录远程服务器
  101. request(api.AuthLoginByWeixin, {
  102. code: code,
  103. userInfo: userInfo
  104. }, 'POST').then(res => {
  105. if (res.errno === 0) {
  106. //存储用户信息
  107. wx.setStorageSync('userInfo', res.data.userInfo);
  108. wx.setStorageSync('token', res.data.token);
  109. resolve(res);
  110. } else {
  111. reject(res);
  112. }
  113. }).catch((err) => {
  114. reject(err);
  115. });
  116. }).catch((err) => {
  117. reject(err);
  118. })
  119. } else {
  120. resolve(res.data);
  121. }
  122. } else {
  123. reject(res.errMsg);
  124. }
  125. },
  126. fail: function (err) {
  127. reject(err)
  128. }
  129. })
  130. });
  131. }
  132. /**
  133. * 检查微信会话是否过期
  134. */
  135. function checkSession() {
  136. return new Promise(function (resolve, reject) {
  137. wx.checkSession({
  138. success: function () {
  139. resolve(true);
  140. },
  141. fail: function () {
  142. reject(false);
  143. }
  144. })
  145. });
  146. }
  147. /**
  148. * 调用微信登录
  149. */
  150. function login() {
  151. return new Promise(function (resolve, reject) {
  152. wx.login({
  153. success: function (res) {
  154. if (res.code) {
  155. //登录远程服务器
  156. resolve(res);
  157. } else {
  158. reject(res);
  159. }
  160. },
  161. fail: function (err) {
  162. reject(err);
  163. }
  164. });
  165. });
  166. }
  167. function getUserInfo() {
  168. return new Promise(function (resolve, reject) {
  169. wx.getUserInfo({
  170. withCredentials: true,
  171. success: function (res) {
  172. resolve(res);
  173. },
  174. fail: function (err) {
  175. reject(err);
  176. }
  177. })
  178. });
  179. }
  180. function redirect(url) {
  181. //判断页面是否需要登录
  182. if (false) {
  183. } else {
  184. wx.redirectTo({
  185. url: url
  186. });
  187. }
  188. }
  189. function showErrorToast(msg) {
  190. wx.showToast({
  191. title: msg,
  192. icon: 'none',
  193. })
  194. }
  195. function showSuccessToast(msg) {
  196. wx.showToast({
  197. title: msg,
  198. icon: 'success',
  199. })
  200. }
  201. function sentRes(url, data, method, fn) {
  202. data = data || null;
  203. if (data == null) {
  204. var content = require('querystring').stringify(data);
  205. } else {
  206. var content = JSON.stringify(data); //json format
  207. }
  208. var parse_u = require('url').parse(url, true);
  209. var isHttp = parse_u.protocol == 'http:';
  210. var options = {
  211. host: parse_u.hostname,
  212. port: parse_u.port || (isHttp ? 80 : 443),
  213. path: parse_u.path,
  214. method: method,
  215. headers: {
  216. 'Content-Type': 'application/json',
  217. 'Content-Length': Buffer.byteLength(content, "utf8"),
  218. 'Trackingmore-Api-Key': '1b70c67e-d191-4301-9c05-a50436a2526d'
  219. }
  220. };
  221. var req = require(isHttp ? 'http' : 'https').request(options, function (res) {
  222. var _data = '';
  223. res.on('data', function (chunk) {
  224. _data += chunk;
  225. });
  226. res.on('end', function () {
  227. fn != undefined && fn(_data);
  228. });
  229. });
  230. req.write(content);
  231. req.end();
  232. }
  233. function loginNow() {
  234. var company = getApp().globalData.company
  235. let userInfo = wx.getStorageSync('userLogin');
  236. if (userInfo == '') {
  237. switch (company) {
  238. // 未来出行港
  239. case "nTFkj1GpWQ":
  240. wx.navigateTo({
  241. url: '/nova-travel/app-auth/index',
  242. });
  243. break;
  244. // 推理社
  245. case "mwgEpKKsGg":
  246. wx.navigateTo({
  247. url: '/nova-drama/app-auth/index',
  248. });
  249. break;
  250. //VR旅游
  251. case "5G6p8gMdOH":
  252. wx.navigateTo({
  253. url: "/nova-vrtrip/app-auth/index",
  254. })
  255. break;
  256. case "668rM7MPii":
  257. wx.navigateTo({
  258. url: "/nova-workers/app-auth/index",
  259. })
  260. break;
  261. case "i3cwsEHS4U":
  262. wx.navigateTo({
  263. url: "/nova-page/diypage/app-auth/index"
  264. })
  265. break;
  266. case "Aoh1ZFpBSa":
  267. wx.navigateTo({
  268. url: "/nova-qingServiceCenter/app-auth/index"
  269. })
  270. break;
  271. // 学位通
  272. case "tBm19Q58Zm":
  273. wx.navigateTo({
  274. url: "/nova-degree/app-auth/index"
  275. })
  276. break;
  277. // 成长口袋
  278. case "WpgR8iSgGM":
  279. wx.navigateTo({
  280. url: "/nova-pocket/app-auth/index"
  281. })
  282. break;
  283. }
  284. return false;
  285. } else {
  286. return true;
  287. }
  288. }
  289. function getTextLength(str, full) {
  290. let len = 0;
  291. for (let i = 0; i < str.length; i++) {
  292. let c = str.charCodeAt(i);
  293. //单字节加1
  294. if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
  295. len++;
  296. } else {
  297. len += (full ? 2 : 1);
  298. }
  299. }
  300. return len;
  301. }
  302. /**
  303. * rgba(255, 255, 255, 1) => #ffffff
  304. * @param {String} color
  305. */
  306. function transferColor(color = '') {
  307. let res = '#';
  308. color = color.replace(/^rgba?\(/, '').replace(/\)$/, '');
  309. color = color.split(', ');
  310. color.length > 3 ? color.length = 3 : '';
  311. for (let item of color) {
  312. item = parseInt(item || 0);
  313. if (item < 10) {
  314. res += ('0' + item)
  315. } else {
  316. res += (item.toString(16))
  317. }
  318. }
  319. return res;
  320. }
  321. function transferBorder(border = '') {
  322. let res = border.match(/(\w+)px\s(\w+)\s(.*)/);
  323. let obj = {};
  324. if (res) {
  325. obj = {
  326. width: +res[1],
  327. style: res[2],
  328. color: res[3]
  329. }
  330. }
  331. return res ? obj : null;
  332. }
  333. /**
  334. * 内边距,依次为上右下左
  335. * @param {*} padding
  336. */
  337. function transferPadding(padding = '0 0 0 0') {
  338. padding = padding.split(' ');
  339. for (let i = 0, len = padding.length; i < len; i++) {
  340. padding[i] = +padding[i].replace('px', '');
  341. }
  342. return padding;
  343. }
  344. /**
  345. * type1: 0, 25, 17, rgba(0, 0, 0, 0.3)
  346. * type2: rgba(0, 0, 0, 0.3) 0px 25px 17px 0px => (0, 25, 17, rgba(0, 0, 0, 0.3))
  347. * @param {*} shadow
  348. */
  349. function transferBoxShadow(shadow = '', type) {
  350. if (!shadow || shadow === 'none') return;
  351. let color;
  352. let split;
  353. split = shadow.match(/(\w+)\s(\w+)\s(\w+)\s(rgb.*)/);
  354. if (split) {
  355. split.shift();
  356. shadow = split;
  357. color = split[3] || '#ffffff';
  358. } else {
  359. split = shadow.split(') ');
  360. color = split[0] + ')'
  361. shadow = split[1].split('px ');
  362. }
  363. return {
  364. offsetX: +shadow[0] || 0,
  365. offsetY: +shadow[1] || 0,
  366. blur: +shadow[2] || 0,
  367. color
  368. }
  369. }
  370. function getUid(prefix) {
  371. prefix = prefix || '';
  372. return (
  373. prefix +
  374. 'xxyxxyxx'.replace(/[xy]/g, c => {
  375. let r = (Math.random() * 16) | 0;
  376. let v = c === 'x' ? r : (r & 0x3) | 0x8;
  377. return v.toString(16);
  378. })
  379. );
  380. }
  381. function initProfile() {
  382. var company = getApp().globalData.company
  383. let userVetify = wx.getStorageSync('userVetify');
  384. if (userVetify == '') {
  385. switch (company) {
  386. case "668rM7MPii":
  387. wx.redirectTo({
  388. url: "/nova-workers/app-auth/Vetify/Vetify",
  389. })
  390. break;
  391. }
  392. return false;
  393. } else {
  394. return true;
  395. }
  396. }
  397. module.exports = {
  398. formatTime_1: formatTime_1,
  399. formatTime: formatTime,
  400. formatTimeNum: formatTimeNum,
  401. request,
  402. redirect,
  403. showErrorToast,
  404. showSuccessToast,
  405. checkSession,
  406. login,
  407. getUserInfo,
  408. testMobile,
  409. sentRes,
  410. loginNow,
  411. getTextLength,
  412. transferBorder,
  413. transferColor,
  414. transferPadding,
  415. transferBoxShadow,
  416. getUid,
  417. initProfile
  418. }