util.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. import {
  2. base64_encode,
  3. base64_decode
  4. } from 'base64';
  5. import md5 from 'md5';
  6. var siteInfo = require('../../../siteinfo.js')
  7. var util = {};
  8. var app = getApp() || {siteInfo: siteInfo};
  9. util.base64_encode = function(str) {
  10. return base64_encode(str)
  11. };
  12. util.base64_decode = function(str) {
  13. return base64_decode(str)
  14. };
  15. util.md5 = function(str) {
  16. return md5(str)
  17. };
  18. /**
  19. 构造微擎地址,
  20. @params action 微擎系统中的controller, action, do,格式为 'wxapp/home/navs'
  21. @params querystring 格式为 {参数名1 : 值1, 参数名2 : 值2}
  22. */
  23. util.url = function(action, querystring) {
  24. var url = app.siteInfo.siteroot + '?i=' + app.siteInfo.uniacid + '&t=' + app.siteInfo.multiid + '&v=' + app.siteInfo.version + '&from=wxapp&';
  25. if (action) {
  26. action = action.split('/');
  27. if (action[0]) {
  28. url += 'c=' + action[0] + '&';
  29. }
  30. if (action[1]) {
  31. url += 'a=' + action[1] + '&';
  32. }
  33. if (action[2]) {
  34. url += 'do=' + action[2] + '&';
  35. }
  36. }
  37. if (querystring && typeof querystring === 'object') {
  38. for (let param in querystring) {
  39. if (param && querystring.hasOwnProperty(param) && querystring[param]) {
  40. url += param + '=' + querystring[param] + '&';
  41. }
  42. }
  43. }
  44. return url;
  45. }
  46. function getQuery(url) {
  47. var theRequest = [];
  48. if (url.indexOf("?") != -1) {
  49. var str = url.split('?')[1];
  50. var strs = str.split("&");
  51. for (var i = 0; i < strs.length; i++) {
  52. if (strs[i].split("=")[0] && unescape(strs[i].split("=")[1])) {
  53. theRequest[i] = {
  54. 'name': strs[i].split("=")[0],
  55. 'value': unescape(strs[i].split("=")[1])
  56. }
  57. }
  58. }
  59. }
  60. return theRequest;
  61. }
  62. /*
  63. * 获取链接某个参数
  64. * url 链接地址
  65. * name 参数名称
  66. */
  67. function getUrlParam(url, name) {
  68. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  69. var r = url.split('?')[1].match(reg); //匹配目标参数
  70. if (r != null) return unescape(r[2]);
  71. return null; //返回参数值
  72. }
  73. /**
  74. * 获取签名 将链接地址的所有参数按字母排序后拼接加上token进行md5
  75. * url 链接地址
  76. * date 参数{参数名1 : 值1, 参数名2 : 值2} *
  77. * token 签名token 非必须
  78. */
  79. function getSign(url, data, token) {
  80. var _ = require('underscore.js');
  81. var md5 = require('md5.js');
  82. var querystring = '';
  83. var sign = getUrlParam(url, 'sign');
  84. if (sign || (data && data.sign)) {
  85. return false;
  86. } else {
  87. if (url) {
  88. querystring = getQuery(url);
  89. }
  90. if (data) {
  91. var theRequest = [];
  92. for (let param in data) {
  93. if (param && data[param]) {
  94. theRequest = theRequest.concat({
  95. 'name': param,
  96. 'value': data[param]
  97. })
  98. }
  99. }
  100. querystring = querystring.concat(theRequest);
  101. }
  102. //排序
  103. querystring = _.sortBy(querystring, 'name');
  104. //去重
  105. querystring = _.uniq(querystring, true, 'name');
  106. var urlData = '';
  107. for (let i = 0; i < querystring.length; i++) {
  108. if (querystring[i] && querystring[i].name && querystring[i].value) {
  109. urlData += querystring[i].name + '=' + querystring[i].value;
  110. if (i < (querystring.length - 1)) {
  111. urlData += '&';
  112. }
  113. }
  114. }
  115. token = token ? token : app.siteInfo.token;
  116. sign = md5(urlData + token);
  117. return sign;
  118. }
  119. }
  120. util.getSign = function(url, data, token) {
  121. return getSign(url, data, token);
  122. };
  123. /**
  124. 二次封装微信wx.request函数、增加交互体全、配置缓存、以及配合微擎格式化返回数据
  125. @params option 弹出参数表,
  126. {
  127. url : 同微信,
  128. data : 同微信,
  129. header : 同微信,
  130. method : 同微信,
  131. success : 同微信,
  132. fail : 同微信,
  133. complete : 同微信,
  134. cachetime : 缓存周期,在此周期内不重复请求http,默认不缓存
  135. }
  136. */
  137. util.request = function(option) {
  138. var _ = require('underscore.js');
  139. var md5 = require('md5.js');
  140. var option = option ? option : {};
  141. option.cachetime = option.cachetime ? option.cachetime : 0;
  142. option.showLoading = typeof option.showLoading != 'undefined' ? option.showLoading : true;
  143. var sessionid = wx.getStorageSync('userInfo').sessionid;
  144. var url = option.url;
  145. if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
  146. url = util.url(url);
  147. }
  148. var state = getUrlParam(url, 'state');
  149. if (!state && !(option.data && option.data.state) && sessionid) {
  150. url = url + '&state=we7sid-' + sessionid
  151. }
  152. if (!option.data || !option.data.m) {
  153. var nowPage = getCurrentPages();
  154. if (nowPage.length) {
  155. nowPage = nowPage[getCurrentPages().length - 1];
  156. if (nowPage && nowPage.__route__) {
  157. url = url + '&m=' + nowPage.__route__.split('/')[0];
  158. }
  159. }
  160. }
  161. var sign = getSign(url, option.data);
  162. if (sign) {
  163. url = url + "&sign=" + sign;
  164. }
  165. if (!url) {
  166. return false;
  167. }
  168. //wx.showNavigationBarLoading();
  169. if (option.showLoading) {
  170. //util.showLoading();
  171. }
  172. if (option.cachetime) {
  173. var cachekey = md5(url);
  174. var cachedata = wx.getStorageSync(cachekey);
  175. var timestamp = Date.parse(new Date());
  176. if (cachedata && cachedata.data) {
  177. if (cachedata.expire > timestamp) {
  178. if (option.complete && typeof option.complete == 'function') {
  179. option.complete(cachedata);
  180. }
  181. if (option.success && typeof option.success == 'function') {
  182. option.success(cachedata);
  183. }
  184. console.log('cache:' + url);
  185. // wx.hideLoading();
  186. //wx.hideNavigationBarLoading();
  187. return true;
  188. } else {
  189. wx.removeStorageSync(cachekey)
  190. }
  191. }
  192. }
  193. wx.request({
  194. 'url': url,
  195. 'data': option.data ? option.data : {},
  196. 'header': option.header ? option.header : {},
  197. 'method': option.method ? option.method : 'GET',
  198. 'header': {
  199. 'content-type': 'application/x-www-form-urlencoded'
  200. },
  201. 'success': function(response) {
  202. //wx.hideNavigationBarLoading();
  203. //wx.hideLoading();
  204. if (response.data.errno) {
  205. if (response.data.errno == '41009') {
  206. wx.setStorageSync('userInfo', '');
  207. util.getUserInfo(function() {
  208. util.request(option)
  209. });
  210. return;
  211. } else {
  212. if (option.fail && typeof option.fail == 'function') {
  213. option.fail(response);
  214. } else {
  215. if (response.data.message) {
  216. if (response.data.data != null && response.data.data.redirect) {
  217. var redirect = response.data.data.redirect;
  218. } else {
  219. var redirect = '';
  220. }
  221. app.util.message(response.data.message, redirect, 'error');
  222. }
  223. }
  224. return;
  225. }
  226. } else {
  227. if (option.success && typeof option.success == 'function') {
  228. option.success(response);
  229. }
  230. //写入缓存,减少HTTP请求,并且如果网络异常可以读取缓存数据
  231. if (option.cachetime) {
  232. var cachedata = {
  233. 'data': response.data,
  234. 'expire': timestamp + option.cachetime * 1000
  235. };
  236. wx.setStorageSync(cachekey, cachedata);
  237. }
  238. }
  239. },
  240. 'fail': function(response) {
  241. wx.hideNavigationBarLoading();
  242. wx.hideLoading();
  243. //如果请求失败,尝试从缓存中读取数据
  244. var md5 = require('md5.js');
  245. var cachekey = md5(url);
  246. var cachedata = wx.getStorageSync(cachekey);
  247. if (cachedata && cachedata.data) {
  248. if (option.success && typeof option.success == 'function') {
  249. option.success(cachedata);
  250. }
  251. console.log('failreadcache:' + url);
  252. return true;
  253. } else {
  254. if (option.fail && typeof option.fail == 'function') {
  255. option.fail(response);
  256. }
  257. }
  258. },
  259. 'complete': function(response) {
  260. // wx.hideNavigationBarLoading();
  261. // wx.hideLoading();
  262. if (option.complete && typeof option.complete == 'function') {
  263. option.complete(response);
  264. }
  265. }
  266. });
  267. }
  268. /*
  269. * 获取用户信息
  270. */
  271. util.getUserInfo = function(cb) {
  272. var login = function() {
  273. console.log('start login');
  274. var userInfo = {
  275. 'sessionid': '',
  276. 'wxInfo': '',
  277. 'memberInfo': '',
  278. };
  279. wx.login({
  280. success: function(res) {
  281. util.request({
  282. url: 'auth/session/openid',
  283. data: {
  284. code: res.code
  285. },
  286. cachetime: 0,
  287. success: function(session) {
  288. if (!session.data.errno) {
  289. userInfo.sessionid = session.data.data.sessionid
  290. wx.setStorageSync('userInfo', userInfo);
  291. wx.getUserInfo({
  292. success: function(wxInfo) {
  293. userInfo.wxInfo = wxInfo.userInfo
  294. wx.setStorageSync('userInfo', userInfo);
  295. util.request({
  296. url: 'auth/session/userinfo',
  297. data: {
  298. signature: wxInfo.signature,
  299. rawData: wxInfo.rawData,
  300. iv: wxInfo.iv,
  301. encryptedData: wxInfo.encryptedData
  302. },
  303. method: 'POST',
  304. header: {
  305. 'content-type': 'application/x-www-form-urlencoded'
  306. },
  307. cachetime: 0,
  308. success: function(res) {
  309. if (!res.data.errno) {
  310. userInfo.memberInfo = res.data.data;
  311. wx.setStorageSync('userInfo', userInfo);
  312. }
  313. typeof cb == "function" && cb(userInfo);
  314. }
  315. });
  316. },
  317. fail: function() {
  318. typeof cb == "function" && cb(userInfo);
  319. },
  320. complete: function() {}
  321. })
  322. }
  323. }
  324. });
  325. },
  326. fail: function() {
  327. wx.showModal({
  328. title: '获取信息失败',
  329. content: '请允许授权以便为您提供给服务',
  330. success: function(res) {
  331. if (res.confirm) {
  332. util.getUserInfo();
  333. }
  334. }
  335. })
  336. }
  337. });
  338. };
  339. var app = wx.getStorageSync('userInfo');
  340. if (app.sessionid) {
  341. wx.checkSession({
  342. success: function() {
  343. typeof cb == "function" && cb(app);
  344. },
  345. fail: function() {
  346. app.sessionid = '';
  347. console.log('relogin');
  348. wx.removeStorageSync('userInfo');
  349. login();
  350. }
  351. })
  352. } else {
  353. //调用登录接口
  354. login();
  355. }
  356. }
  357. util.navigateBack = function(obj) {
  358. let delta = obj.delta ? obj.delta : 1;
  359. if (obj.data) {
  360. let pages = getCurrentPages()
  361. let curPage = pages[pages.length - (delta + 1)];
  362. if (curPage.pageForResult) {
  363. curPage.pageForResult(obj.data);
  364. } else {
  365. curPage.setData(obj.data);
  366. }
  367. }
  368. wx.navigateBack({
  369. delta: delta, // 回退前 delta(默认为1) 页面
  370. success: function(res) {
  371. // success
  372. typeof obj.success == "function" && obj.success(res);
  373. },
  374. fail: function(err) {
  375. // fail
  376. typeof obj.fail == "function" && obj.fail(err);
  377. },
  378. complete: function() {
  379. // complete
  380. typeof obj.complete == "function" && obj.complete();
  381. }
  382. })
  383. };
  384. util.footer = function($this) {
  385. let that = $this;
  386. let tabBar = app.tabBar;
  387. for (let i in tabBar['list']) {
  388. tabBar['list'][i]['pageUrl'] = tabBar['list'][i]['pagePath'].replace(/(\?|#)[^"]*/g, '')
  389. }
  390. that.setData({
  391. tabBar: tabBar,
  392. 'tabBar.thisurl': that.__route__
  393. })
  394. };
  395. /*
  396. * 提示信息
  397. * type 为 success, error 当为 success, 时,为toast方式,否则为模态框的方式
  398. * redirect 为提示后的跳转地址, 跳转的时候可以加上 协议名称
  399. * navigate:/we7/pages/detail/detail 以 navigateTo 的方法跳转,
  400. * redirect:/we7/pages/detail/detail 以 redirectTo 的方式跳转,默认为 redirect
  401. */
  402. util.message = function (title, redirect, type, confirmText="确定") {
  403. if (!title) {
  404. return true;
  405. }
  406. if (typeof title == 'object') {
  407. redirect = title.redirect;
  408. type = title.type;
  409. title = title.title;
  410. }
  411. if (redirect) {
  412. var redirectType = redirect.substring(0, 9),
  413. url = '',
  414. redirectFunction = '';
  415. if (redirectType == 'navigate:') {
  416. redirectFunction = 'navigateTo';
  417. url = redirect.substring(9);
  418. } else if (redirectType == 'redirect:') {
  419. redirectFunction = 'redirectTo';
  420. url = redirect.substring(9);
  421. } else if (redirectType == 'switchTo:') {
  422. redirectFunction = 'switchTab';
  423. url = redirect.substring(9);
  424. } else {
  425. url = redirect;
  426. redirectFunction = 'redirectTo';
  427. }
  428. }
  429. if (!type) {
  430. type = 'success';
  431. }
  432. if (type == 'success') {
  433. wx.showToast({
  434. title: title,
  435. icon: 'success',
  436. duration: 2000,
  437. mask: url ? true : false,
  438. complete: function() {
  439. if (url) {
  440. setTimeout(function() {
  441. wx[redirectFunction]({
  442. url: url,
  443. });
  444. }, 1800);
  445. }
  446. }
  447. });
  448. } else if (type == 'error') {
  449. wx.showModal({
  450. title: '提示',
  451. content: title,
  452. showCancel: false,
  453. confirmColor: '#ff5041',
  454. confirmText,
  455. complete: function() {
  456. if (url) {
  457. wx[redirectFunction]({
  458. url: url,
  459. });
  460. }
  461. }
  462. });
  463. }
  464. }
  465. util.navTo = function (redirect){
  466. if (redirect) {
  467. var redirectType = redirect.substring(0, 9),
  468. url = '',
  469. redirectFunction = '';
  470. if (redirectType == 'navigate:') {
  471. redirectFunction = 'navigateTo';
  472. url = redirect.substring(9);
  473. } else if (redirectType == 'redirect:') {
  474. redirectFunction = 'redirectTo';
  475. url = redirect.substring(9);
  476. } else if (redirectType == 'switchTo:') {
  477. redirectFunction = 'switchTab';
  478. url = redirect.substring(9);
  479. } else {
  480. url = redirect;
  481. redirectFunction = 'redirectTo';
  482. }
  483. url && wx[redirectFunction]({ url });
  484. }
  485. }
  486. util.user = util.getUserInfo;
  487. //封装微信等待提示,防止ajax过多时,show多次
  488. util.showLoading = function() {
  489. var isShowLoading = wx.getStorageSync('isShowLoading');
  490. if (isShowLoading) {
  491. wx.hideLoading();
  492. wx.setStorageSync('isShowLoading', false);
  493. }
  494. wx.showLoading({
  495. title: '加载中',
  496. complete: function() {
  497. wx.setStorageSync('isShowLoading', true);
  498. },
  499. fail: function() {
  500. wx.setStorageSync('isShowLoading', false);
  501. }
  502. });
  503. }
  504. util.showImage = function(event) {
  505. var url = event ? event.currentTarget.dataset.preview : '';
  506. if (!url) {
  507. return false;
  508. }
  509. wx.previewImage({
  510. urls: [url]
  511. });
  512. }
  513. /**
  514. * 转换内容中的emoji表情为 unicode 码点,在Php中使用utf8_bytes来转换输出
  515. */
  516. util.parseContent = function(string) {
  517. if (!string) {
  518. return string;
  519. }
  520. var ranges = [
  521. '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
  522. '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
  523. '\ud83d[\ude80-\udeff]' // U+1F680 to U+1F6FF
  524. ];
  525. var emoji = string.match(
  526. new RegExp(ranges.join('|'), 'g'));
  527. if (emoji) {
  528. for (var i in emoji) {
  529. string = string.replace(emoji[i], '[U+' + emoji[i].codePointAt(0).toString(16).toUpperCase() + ']');
  530. }
  531. }
  532. return string;
  533. }
  534. util.date = function() {
  535. /**
  536. * 判断闰年
  537. * @param date Date日期对象
  538. * @return boolean true 或false
  539. */
  540. this.isLeapYear = function(date) {
  541. return (0 == date.getYear() % 4 && ((date.getYear() % 100 != 0) || (date.getYear() % 400 == 0)));
  542. }
  543. /**
  544. * 日期对象转换为指定格式的字符串
  545. * @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
  546. * @param date Date日期对象, 如果缺省,则为当前时间
  547. *
  548. * YYYY/yyyy/YY/yy 表示年份
  549. * MM/M 月份
  550. * W/w 星期
  551. * dd/DD/d/D 日期
  552. * hh/HH/h/H 时间
  553. * mm/m 分钟
  554. * ss/SS/s/S 秒
  555. * @return string 指定格式的时间字符串
  556. */
  557. this.dateToStr = function(formatStr, date) {
  558. formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
  559. date = arguments[1] || new Date();
  560. var str = formatStr;
  561. var Week = ['日', '一', '二', '三', '四', '五', '六'];
  562. str = str.replace(/yyyy|YYYY/, date.getFullYear());
  563. str = str.replace(/yy|YY/, (date.getYear() % 100) > 9 ? (date.getYear() % 100).toString() : '0' + (date.getYear() % 100));
  564. str = str.replace(/MM/, date.getMonth() > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1));
  565. str = str.replace(/M/g, date.getMonth());
  566. str = str.replace(/w|W/g, Week[date.getDay()]);
  567. str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
  568. str = str.replace(/d|D/g, date.getDate());
  569. str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : '0' + date.getHours());
  570. str = str.replace(/h|H/g, date.getHours());
  571. str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : '0' + date.getMinutes());
  572. str = str.replace(/m/g, date.getMinutes());
  573. str = str.replace(/ss|SS/, date.getSeconds() > 9 ? date.getSeconds().toString() : '0' + date.getSeconds());
  574. str = str.replace(/s|S/g, date.getSeconds());
  575. return str;
  576. }
  577. /**
  578. * 日期计算
  579. * @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  580. * @param num int
  581. * @param date Date 日期对象
  582. * @return Date 返回日期对象
  583. */
  584. this.dateAdd = function(strInterval, num, date) {
  585. date = arguments[2] || new Date();
  586. switch (strInterval) {
  587. case 's':
  588. return new Date(date.getTime() + (1000 * num));
  589. case 'n':
  590. return new Date(date.getTime() + (60000 * num));
  591. case 'h':
  592. return new Date(date.getTime() + (3600000 * num));
  593. case 'd':
  594. return new Date(date.getTime() + (86400000 * num));
  595. case 'w':
  596. return new Date(date.getTime() + ((86400000 * 7) * num));
  597. case 'm':
  598. return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
  599. case 'y':
  600. return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
  601. }
  602. }
  603. /**
  604. * 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串
  605. * @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  606. * @param dtStart Date 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  607. * @param dtEnd Date 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  608. */
  609. this.dateDiff = function(strInterval, dtStart, dtEnd) {
  610. switch (strInterval) {
  611. case 's':
  612. return parseInt((dtEnd - dtStart) / 1000);
  613. case 'n':
  614. return parseInt((dtEnd - dtStart) / 60000);
  615. case 'h':
  616. return parseInt((dtEnd - dtStart) / 3600000);
  617. case 'd':
  618. return parseInt((dtEnd - dtStart) / 86400000);
  619. case 'w':
  620. return parseInt((dtEnd - dtStart) / (86400000 * 7));
  621. case 'm':
  622. return (dtEnd.getMonth() + 1) + ((dtEnd.getFullYear() - dtStart.getFullYear()) * 12) - (dtStart.getMonth() + 1);
  623. case 'y':
  624. return dtEnd.getFullYear() - dtStart.getFullYear();
  625. }
  626. }
  627. /**
  628. * 字符串转换为日期对象 // eval 不可用
  629. * @param date Date 格式为yyyy-MM-dd HH:mm:ss,必须按年月日时分秒的顺序,中间分隔符不限制
  630. */
  631. this.strToDate = function(dateStr) {
  632. var data = dateStr;
  633. var reCat = /(\d{1,4})/gm;
  634. var t = data.match(reCat);
  635. t[1] = t[1] - 1;
  636. eval('var d = new Date(' + t.join(',') + ');');
  637. return d;
  638. }
  639. /**
  640. * 把指定格式的字符串转换为日期对象yyyy-MM-dd HH:mm:ss
  641. *
  642. */
  643. this.strFormatToDate = function(formatStr, dateStr) {
  644. var year = 0;
  645. var start = -1;
  646. var len = dateStr.length;
  647. if ((start = formatStr.indexOf('yyyy')) > -1 && start < len) {
  648. year = dateStr.substr(start, 4);
  649. }
  650. var month = 0;
  651. if ((start = formatStr.indexOf('MM')) > -1 && start < len) {
  652. month = parseInt(dateStr.substr(start, 2)) - 1;
  653. }
  654. var day = 0;
  655. if ((start = formatStr.indexOf('dd')) > -1 && start < len) {
  656. day = parseInt(dateStr.substr(start, 2));
  657. }
  658. var hour = 0;
  659. if (((start = formatStr.indexOf('HH')) > -1 || (start = formatStr.indexOf('hh')) > 1) && start < len) {
  660. hour = parseInt(dateStr.substr(start, 2));
  661. }
  662. var minute = 0;
  663. if ((start = formatStr.indexOf('mm')) > -1 && start < len) {
  664. minute = dateStr.substr(start, 2);
  665. }
  666. var second = 0;
  667. if ((start = formatStr.indexOf('ss')) > -1 && start < len) {
  668. second = dateStr.substr(start, 2);
  669. }
  670. return new Date(year, month, day, hour, minute, second);
  671. }
  672. /**
  673. * 日期对象转换为毫秒数
  674. */
  675. this.dateToLong = function(date) {
  676. return date.getTime();
  677. }
  678. /**
  679. * 毫秒转换为日期对象
  680. * @param dateVal number 日期的毫秒数
  681. */
  682. this.longToDate = function(dateVal) {
  683. return new Date(dateVal);
  684. }
  685. /**
  686. * 判断字符串是否为日期格式
  687. * @param str string 字符串
  688. * @param formatStr string 日期格式, 如下 yyyy-MM-dd
  689. */
  690. this.isDate = function(str, formatStr) {
  691. if (formatStr == null) {
  692. formatStr = "yyyyMMdd";
  693. }
  694. var yIndex = formatStr.indexOf("yyyy");
  695. if (yIndex == -1) {
  696. return false;
  697. }
  698. var year = str.substring(yIndex, yIndex + 4);
  699. var mIndex = formatStr.indexOf("MM");
  700. if (mIndex == -1) {
  701. return false;
  702. }
  703. var month = str.substring(mIndex, mIndex + 2);
  704. var dIndex = formatStr.indexOf("dd");
  705. if (dIndex == -1) {
  706. return false;
  707. }
  708. var day = str.substring(dIndex, dIndex + 2);
  709. if (!isNumber(year) || year > "2100" || year < "1900") {
  710. return false;
  711. }
  712. if (!isNumber(month) || month > "12" || month < "01") {
  713. return false;
  714. }
  715. if (day > getMaxDay(year, month) || day < "01") {
  716. return false;
  717. }
  718. return true;
  719. }
  720. this.getMaxDay = function(year, month) {
  721. if (month == 4 || month == 6 || month == 9 || month == 11)
  722. return "30";
  723. if (month == 2)
  724. if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
  725. return "29";
  726. else
  727. return "28";
  728. return "31";
  729. }
  730. /**
  731. * 变量是否为数字
  732. */
  733. this.isNumber = function(str) {
  734. var regExp = /^\d+$/g;
  735. return regExp.test(str);
  736. }
  737. /**
  738. * 把日期分割成数组 [年、月、日、时、分、秒]
  739. */
  740. this.toArray = function(myDate) {
  741. myDate = arguments[0] || new Date();
  742. var myArray = Array();
  743. myArray[0] = myDate.getFullYear();
  744. myArray[1] = myDate.getMonth();
  745. myArray[2] = myDate.getDate();
  746. myArray[3] = myDate.getHours();
  747. myArray[4] = myDate.getMinutes();
  748. myArray[5] = myDate.getSeconds();
  749. return myArray;
  750. }
  751. /**
  752. * 取得日期数据信息
  753. * 参数 interval 表示数据类型
  754. * y 年 M月 d日 w星期 ww周 h时 n分 s秒
  755. */
  756. this.datePart = function(interval, myDate) {
  757. myDate = arguments[1] || new Date();
  758. var partStr = '';
  759. var Week = ['日', '一', '二', '三', '四', '五', '六'];
  760. switch (interval) {
  761. case 'y':
  762. partStr = myDate.getFullYear();
  763. break;
  764. case 'M':
  765. partStr = myDate.getMonth() + 1;
  766. break;
  767. case 'd':
  768. partStr = myDate.getDate();
  769. break;
  770. case 'w':
  771. partStr = Week[myDate.getDay()];
  772. break;
  773. case 'ww':
  774. partStr = myDate.WeekNumOfYear();
  775. break;
  776. case 'h':
  777. partStr = myDate.getHours();
  778. break;
  779. case 'm':
  780. partStr = myDate.getMinutes();
  781. break;
  782. case 's':
  783. partStr = myDate.getSeconds();
  784. break;
  785. }
  786. return partStr;
  787. }
  788. /**
  789. * 取得当前日期所在月的最大天数
  790. */
  791. this.maxDayOfDate = function(date) {
  792. date = arguments[0] || new Date();
  793. date.setDate(1);
  794. date.setMonth(date.getMonth() + 1);
  795. var time = date.getTime() - 24 * 60 * 60 * 1000;
  796. var newDate = new Date(time);
  797. return newDate.getDate();
  798. }
  799. };
  800. util.getLightColor = function(color, level) {
  801. color = color ? color.toUpperCase() : color;
  802. var r = /^\#?[0-9A-F]{6}$/;
  803. if (!r.test(color)) return color;
  804. color = color.replace("#", "");
  805. var hxs = color.match(/../g);
  806. for (var i = 0; i < 3; i++) {
  807. var col = parseInt(hxs[i], 16);
  808. hxs[i] = Math.floor((255 - col) * level + col);
  809. }
  810. return `rgb(${hxs[0]}, ${hxs[1]}, ${hxs[2]})`;
  811. }
  812. util.ProReq = function(controller, params) {
  813. return new Promise((resolve, reject)=>{
  814. util.request({
  815. url: 'entry/wxapp/index',
  816. data: {
  817. controller,
  818. ...params
  819. },
  820. dataType: 'json',
  821. success: function (res) {
  822. wx.hideLoading();
  823. if (res.data.code == 0) {
  824. resolve(res.data)
  825. } else {
  826. reject(res.data)
  827. }
  828. },
  829. fail: err=>{
  830. console.log(err)
  831. }
  832. })
  833. })
  834. }
  835. module.exports = util;