Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

util.js 16 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. let WebIM = uni.WebIM = require("./WebIM.js")["default"];
  2. function formatLongTime(mss) {
  3. var days = parseInt(mss / (1000 * 60 * 60 * 24));
  4. var hours = parseInt(mss % (1000 * 60 * 60 * 24) / (1000 * 60 * 60));
  5. var minutes = parseInt(mss % (1000 * 60 * 60) / (1000 * 60));
  6. var seconds = mss % (1000 * 60) / 1000;
  7. seconds = parseInt(seconds);
  8. if (minutes < 9) {
  9. minutes = "0" + minutes;
  10. }
  11. if (seconds < 9) {
  12. seconds = "0" + seconds;
  13. }
  14. return minutes + ":" + seconds + "";
  15. }
  16. /**
  17. * 格式化时间
  18. * @param {String} date 原始时间格式
  19. * 格式后的时间:yyyy/mm/dd hh:mm:ss
  20. **/
  21. /**
  22. * 格式化时间
  23. * @param {String} date 原始时间格式
  24. * 格式后的时间:yyyy/mm/dd hh:mm:ss
  25. **/
  26. const formatSecond = seconds => {
  27. var result = typeof seconds === "string" ? parseFloat(seconds) : seconds;
  28. if (isNaN(result)) return "";
  29. let h = Math.floor(result / 3600) < 10 ? "0" + Math.floor(result / 3600) : Math.floor(result / 3600);
  30. let m = Math.floor((result / 60) % 60) < 10 ? "0" + Math.floor((result / 60) % 60) : Math.floor((result / 60) % 60);
  31. let s = Math.floor(result % 60) < 10 ? "0" + Math.floor(result % 60) : Math.floor(result % 60);
  32. return `${h}:${m}:${s}`;
  33. }
  34. const formatTime = date => {
  35. const year = date.getFullYear();
  36. const month = date.getMonth() + 1;
  37. const day = date.getDate();
  38. const hour = date.getHours();
  39. const minute = date.getMinutes();
  40. const second = date.getSeconds();
  41. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(
  42. ':');
  43. };
  44. /**
  45. * 格式化时间
  46. * @param {String} date 原始时间格式
  47. * 格式后的时间:hh:mm
  48. **/
  49. const formatDateTime = date => {
  50. const hour = date.getHours();
  51. const minute = date.getMinutes();
  52. return [hour, minute, second].map(formatNumber).join(':');
  53. };
  54. /**
  55. * 格式化时间
  56. * @param {String} date 原始时间格式
  57. * 格式后的时间:yyyy-mm-dd
  58. **/
  59. const formatDate = date => {
  60. const year = date.getFullYear();
  61. const month = date.getMonth() + 1;
  62. const day = date.getDate();
  63. return [year, month, day].map(formatNumber).join('-');
  64. };
  65. const formatNumber = n => {
  66. n = n.toString();
  67. return n[1] ? n : '0' + n;
  68. };
  69. /**
  70. * 获取指定日期前后N天的日期、前N个月日期、后N个月日期
  71. * @param {String} sdate 当前日期
  72. * @param {Number} interval 间隔天数
  73. * @param {String} caret 间隔符号
  74. * @example 获取当天日期 getNowFormatDate("",0,"-"); 结果为"2018-09-18";
  75. 获取前一天日期  getNowFormatDate("2018-03-01",-1,"-"); 结果为"2018-02-18";
  76. 获取后一天日期  getNowFormatDate("2018-02-28",1,"-"); 结果为"2018-03-01";
  77. **/
  78. function getNowFormatDate(sdate, interval, caret) {
  79. var patt1 = /^\d{4}-([0-1]?[0-9])-([0-3]?[0-9])$/; //判断输入的日期是否符合格式正则表达式
  80. if (!(sdate && typeof sdate == "string" && patt1.test(sdate))) {
  81. sdate = new Date(); //不满足日期的则使用当前年月日
  82. }
  83. interval = isNaN(parseInt(interval)) ? 0 : parseInt(interval); //若没有输入间隔,则使用当前日
  84. caret = caret && typeof caret == "string" ? caret : "";
  85. var gdate = new Date(sdate).getTime(); //获取指定年月日
  86. gdate = gdate + 1000 * 60 * 60 * 24 * interval; //加减相差毫秒数
  87. var speDate = new Date(gdate); //获取指定好毫秒数时间
  88. var preYear = speDate.getFullYear();
  89. var preMonth = speDate.getMonth() + 1;
  90. var preDay = speDate.getDate();
  91. preMonth = preMonth < 10 ? "0" + preMonth : preMonth;
  92. preDay = preDay < 10 ? "0" + preDay : preDay;
  93. var preDate = preYear + caret + preMonth + caret + preDay;
  94. return preDate;
  95. } // 获取某年某月的有多少周
  96. String.prototype.weekInMonthCount = function() {
  97. var date = new Date(new Date(this.replace(/-/g, "/")) || new Date());
  98. var firstWeekDate = 1; // 默认第一周是本月1号 为了模拟本月1号是否为本月第1周的判断
  99. if (date.getDay() === 1) {
  100. // 判断1号是周一
  101. firstWeekDate = 1;
  102. } else if (date.getDay() === 0) {
  103. // 判断1号是周日
  104. firstWeekDate = 8 - 7 + 1;
  105. } else {
  106. // 判断1号是周二至周六之间
  107. firstWeekDate = 8 - date.getDay() + 1;
  108. }
  109. date.setMonth(date.getMonth() + 1);
  110. date.setDate(0);
  111. var monthHasDays = date.getDate(); // 本月天数
  112. monthHasDays = date.getDate() - firstWeekDate + 1;
  113. var hasWeek = Math.ceil(monthHasDays / 7); // 计算本月有几周
  114. return hasWeek;
  115. }; // 获取今天是第几周 注:ios不支持2018-01-14 需转化为2018/01/14
  116. String.prototype.weekIndexInMonth = function() {
  117. var date_trim = (this.trim() != "" ? this : new Date()).replace(/-/g, "/");
  118. var date = new Date(date_trim);
  119. var dateStart_trim = new Date((this.trim() != "" ? this : new Date()).replace(/-/g, "/")).setDate(1);
  120. var dateStart = new Date(dateStart_trim); // 本月初
  121. var firstWeek = 1;
  122. if (dateStart.getDay() === 1) {
  123. firstWeek = 1;
  124. } else if (dateStart.getDay() === 0) {
  125. firstWeek = 8 - 7 + 1;
  126. } else {
  127. firstWeek = 8 - dateStart.getDay() + 1;
  128. }
  129. var weekIndex = 1;
  130. var c = date.getDate();
  131. if (date.getDay() === 1 && date.getDate() < 7) {
  132. weekIndex = 1;
  133. } else if (c < firstWeek) {
  134. weekIndex = -1;
  135. } else {
  136. if (c < 7) {
  137. weekIndex = Math.ceil(c / 7);
  138. } else {
  139. c = c - firstWeek + 1;
  140. if (c % 7 === 0) {
  141. if (dateStart.getDay() !== 6) {
  142. weekIndex = c / 7;
  143. } else {
  144. weekIndex = c / 7 + 1;
  145. }
  146. } else {
  147. weekIndex = Math.ceil(c / 7);
  148. }
  149. }
  150. }
  151. return weekIndex;
  152. };
  153. /**
  154. * 验证车牌号是否正确
  155. * @param number carNumber
  156. **/
  157. function isLicensePlate(carNumber) {
  158. if (carNumber == '') {
  159. return false;
  160. }
  161. if (/^[A-Za-z]+$/.test(carNumber.slice(1))) {
  162. //全为字母
  163. return false;
  164. }
  165. return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/
  166. .test(carNumber);
  167. }
  168. /**
  169. * 验证手机号
  170. */
  171. function checkPhone(phone) {
  172. let that = this;
  173. if (phone == '') {
  174. return false;
  175. }
  176. if (!/^1[3456789]\d{9}$/.test(phone)) {
  177. return false;
  178. }
  179. return true;
  180. }
  181. /**
  182. * 隐藏字符串
  183. * @param string str 字符串
  184. * @param int frontLen 前面需要保留几位
  185. * @param int endLen 后面需要保留几位
  186. */
  187. function hiddenString(str, frontLen, endLen) {
  188. var len = str.length - frontLen - endLen;
  189. var xing = '';
  190. for (var i = 0; i < len; i++) {
  191. xing += '*';
  192. }
  193. return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
  194. }
  195. /**
  196. * 从一个数组中随机取出若干个元素组成数组
  197. * @param {Array} arr 原数组
  198. * @param {Number} count 需要随机取得个数
  199. **/
  200. const getRandomArray = (arr, count) => {
  201. var shuffled = arr.slice(0),
  202. i = arr.length,
  203. min = i - count,
  204. temp,
  205. index;
  206. while (i-- > min) {
  207. index = Math.floor((i + 1) * Math.random());
  208. temp = shuffled[index];
  209. shuffled[index] = shuffled[i];
  210. shuffled[i] = temp;
  211. }
  212. return shuffled.slice(min);
  213. };
  214. /**
  215. * 从一个数组中随机取出一个元素
  216. * @param {Array} arr 原数组
  217. **/
  218. const getRandomArrayElement = arr => {
  219. return arr[Math.floor(Math.random() * arr.length)];
  220. };
  221. /**
  222. * 去除数组中重复的值
  223. * @param {Array} arr 原数组
  224. **/
  225. const getUnique = array => {
  226. var n = {},
  227. r = [],
  228. len = array.length,
  229. val,
  230. type;
  231. for (var i = 0; i < array.length; i++) {
  232. val = array[i];
  233. type = typeof val;
  234. if (!n[val]) {
  235. n[val] = [type];
  236. r.push(val);
  237. } else if (n[val].indexOf(type) < 0) {
  238. n[val].push(type);
  239. r.push(val);
  240. }
  241. }
  242. return r;
  243. };
  244. /**
  245. * 读取xml字符串
  246. * @param {String} xmlString 数据
  247. **/
  248. function loadXMLStr(xmlString) {
  249. var danmulist = [];
  250. if (xmlString.indexOf("<d p")) {
  251. var str = xmlString.substring(xmlString.indexOf("<d p"), xmlString.length);
  252. var reg = /<d p/g;
  253. var arr = str.match(reg);
  254. if (arr) {
  255. console.log(str);
  256. console.log(arr.length);
  257. for (var i = 0; i < arr.length; ++i) {
  258. var getstr = str.substring(0, str.indexOf("</d>") + "</d>".length);
  259. str = str.substring(str.indexOf("</d>") + "</d>".length, str.length);
  260. var danmu = {
  261. text: getstr.substring(getstr.indexOf(">") + ">".length, getstr.indexOf("</d>")),
  262. color: '#ff00ff',
  263. time: Math.floor(getstr.substring(getstr.indexOf("<d p=\"") + "<d p=\"".length, getstr.indexOf(
  264. ",")))
  265. };
  266. danmulist.push(danmu);
  267. }
  268. }
  269. }
  270. return danmulist;
  271. } // 显示警告提示(7个汉字长度)
  272. var showWarn = text => uni.showToast({
  273. title: text,
  274. image: 'https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/warn.png'
  275. }); // 显示错误提示(7个汉字长度)
  276. var showError = text => uni.showToast({
  277. title: text,
  278. image: 'https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/error.png'
  279. }); // 显示繁忙提示(7个汉字长度)
  280. var showBusy = text => uni.showToast({
  281. title: text,
  282. icon: 'loading',
  283. duration: 1500
  284. }); // 显示成功提示(7个汉字长度)
  285. var showSuccess = text => uni.showToast({
  286. title: text,
  287. icon: 'success'
  288. }); // 显示无图标提示(两行)
  289. var showNone = text => uni.showToast({
  290. title: text,
  291. icon: 'none',
  292. duration: 1500
  293. }); // 显示失败提示框
  294. var showModel = (title, content) => {
  295. uni.hideToast();
  296. uni.showModal({
  297. title,
  298. content: JSON.stringify(content),
  299. showCancel: false
  300. });
  301. }; //获取列表
  302. function getList(url, userinfo, page, pageSize, callback) {
  303. this.showBusy('加载中...');
  304. var token = uni.getStorageSync('weapp_session_login_data');
  305. uni.request({
  306. url: url,
  307. data: {
  308. skey: userinfo.skey,
  309. tel: userinfo.userinfo.mobile_phone,
  310. page: page,
  311. pageSize: pageSize
  312. },
  313. method: 'POST',
  314. header: {
  315. 'content-type': 'application/x-www-form-urlencoded',
  316. "Access-Token": token.token
  317. },
  318. success: function(result) {
  319. if (result.data.code == '200') {
  320. uni.hideToast();
  321. var result = result.data;
  322. callback(result);
  323. }
  324. },
  325. fail(error) {
  326. this.showModel('请求失败', error);
  327. return false;
  328. }
  329. });
  330. } //请求数据
  331. function getRequest(url, params, callback) {
  332. this.showBusy('加载中...');
  333. var token = uni.getStorageSync('weapp_session_login_data');
  334. uni.request({
  335. url: url,
  336. data: params,
  337. method: 'POST',
  338. header: {
  339. 'content-type': 'application/json',
  340. 'Access-Token': token.token
  341. },
  342. success: function(result) {
  343. if (result.data.code == '10003' || result.data.code == '20006') {
  344. //未登录
  345. uni.hideToast();
  346. uni.showModal({
  347. title: '提示',
  348. content: '您的登录已失效,请重新登录',
  349. showCancel: false,
  350. success(res) {
  351. if (res.confirm) {
  352. try {
  353. uni.clearStorageSync();
  354. uni.reLaunch({
  355. url: '/pages/main/login/index' //绝对路径
  356. });
  357. } catch (e) {
  358. return false;
  359. }
  360. }
  361. }
  362. }); // WebIM.conn.close();
  363. return false;
  364. }
  365. if (result.data.code == '10000') {
  366. uni.hideToast();
  367. var result = result.data;
  368. callback(result.data);
  369. } else {
  370. uni.hideToast();
  371. uni.showModal({
  372. title: '提示',
  373. content: '加载失败,请重新刷新',
  374. showCancel: false
  375. });
  376. return false;
  377. }
  378. },
  379. fail(error) {
  380. uni.hideToast();
  381. uni.showModal({
  382. title: '提示',
  383. content: '网络异常,请重新刷新',
  384. showCancel: false
  385. });
  386. return false;
  387. }
  388. });
  389. } //请求数据(异步)
  390. function getRequestPromise(url, params, isNone, option) {
  391. var isNone = isNone ? true : false;
  392. if (!isNone) {
  393. this.showBusy('加载中...');
  394. }
  395. var token = uni.getStorageSync('weapp_session_login_data');
  396. return new Promise(function(resolve, reject) {
  397. uni.request({
  398. url: url,
  399. data: params,
  400. method: option ? option : 'POST',
  401. header: {
  402. 'content-type': 'application/json',
  403. 'Access-Token': token.token
  404. },
  405. success: function(result) {
  406. if (result.data.code == '10000') {
  407. uni.hideToast();
  408. var results = result.data;
  409. resolve(results.data);
  410. } else if (result.data.code == '10003' || result.data.code == '20006') {
  411. //未登录
  412. uni.hideToast();
  413. uni.showModal({
  414. title: '提示',
  415. content: '您的登录已失效,请重新登录',
  416. showCancel: false,
  417. success(res) {
  418. if (res.confirm) {
  419. try {
  420. uni.clearStorageSync();
  421. uni.reLaunch({
  422. url: '/pages/main/login/index' //绝对路径
  423. });
  424. } catch (e) {
  425. return false;
  426. }
  427. }
  428. }
  429. }); // WebIM.conn.close();
  430. return false;
  431. } else if (result.data.code == '60001') {
  432. //已录入客户
  433. uni.hideToast();
  434. uni.showToast({
  435. title: '您已经录入了该客户!',
  436. icon: 'none',
  437. duration: 1500
  438. });
  439. return false;
  440. } else if (result.data.code == '20005') {
  441. //已录入客户
  442. uni.hideToast();
  443. uni.showModal({
  444. title: '提示',
  445. content: '原始密码错误',
  446. showCancel: false
  447. });
  448. return false;
  449. } else {
  450. uni.hideToast();
  451. uni.showModal({
  452. title: '提示',
  453. content: result.data.message ? result.data.message : '请求数据失败,请重新尝试',
  454. showCancel: false
  455. });
  456. return false;
  457. }
  458. },
  459. fail(error) {
  460. console.log(error);
  461. uni.hideToast();
  462. uni.showModal({
  463. title: '提示',
  464. content: '网络异常,请重新尝试',
  465. showCancel: false
  466. });
  467. return false;
  468. }
  469. });
  470. });
  471. } //请求数据自定义
  472. function getRequestCustom(url, params, isShow) {
  473. if (isShow != 1) {
  474. this.showBusy('加载中...');
  475. }
  476. var token = uni.getStorageSync('weapp_session_login_data');
  477. return new Promise(function(resolve, reject) {
  478. uni.request({
  479. url: url,
  480. data: params,
  481. method: 'POST',
  482. header: {
  483. 'content-type': 'application/x-www-form-urlencoded',
  484. 'Access-Token': token.token
  485. },
  486. success: function(result) {
  487. if (result.data.data == undefined) {
  488. resolve(result.data);
  489. } else {
  490. if (result.data.success) {
  491. resolve(result.data.data);
  492. } else {
  493. uni.hideToast();
  494. uni.showModal({
  495. title: '提示',
  496. content: result.data.message ? result.data.message :
  497. '请求数据失败,请重新尝试',
  498. showCancel: false
  499. });
  500. return false;
  501. }
  502. }
  503. },
  504. fail(error) {
  505. uni.showModal({
  506. title: '提示',
  507. content: '网络异常,请重新尝试',
  508. showCancel: false
  509. });
  510. return false;
  511. }
  512. });
  513. });
  514. } //请求数据(异步)-自定义
  515. function getRequestPromiseCustom(url, params, option) {
  516. this.showBusy('请求中...');
  517. var token = uni.getStorageSync('weapp_session_login_data');
  518. return new Promise(function(resolve, reject) {
  519. uni.request({
  520. url: url,
  521. data: params,
  522. method: option ? option : 'POST',
  523. header: {
  524. 'content-type': 'application/json',
  525. 'token': token.token
  526. },
  527. success: function(result) {
  528. uni.hideToast();
  529. var results = result.data;
  530. resolve(results);
  531. },
  532. fail(error) {
  533. uni.hideToast();
  534. uni.showModal({
  535. title: '提示',
  536. content: '网络异常,请重新尝试',
  537. showCancel: false
  538. });
  539. return false;
  540. }
  541. });
  542. });
  543. }
  544. module.exports = {
  545. formatSecond,
  546. formatTime,
  547. formatDate,
  548. formatDateTime,
  549. getRandomArray: getRandomArray,
  550. getRandomArrayElement: getRandomArrayElement,
  551. showWarn,
  552. showError,
  553. showBusy,
  554. showSuccess,
  555. showNone,
  556. showModel,
  557. getList: getList,
  558. getRequest: getRequest,
  559. getRequestPromise: getRequestPromise,
  560. getRequestCustom: getRequestCustom,
  561. getRequestPromiseCustom: getRequestPromiseCustom,
  562. getNowFormatDate: getNowFormatDate,
  563. isLicensePlate: isLicensePlate,
  564. checkPhone: checkPhone,
  565. hiddenString: hiddenString,
  566. getUnique: getUnique,
  567. loadXMLStr: loadXMLStr,
  568. formatLongTime: formatLongTime
  569. };