common.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. import * as db from './db.js' //引入common
  2. import * as api from './api.js'
  3. import {
  4. baseUrl,
  5. cndUrl,
  6. bgClass,
  7. title,
  8. baseLogo,
  9. } from './config.js'
  10. import htmlParser from '@/common/html-parser' //引入htmlParser
  11. /**
  12. * 跳转登陆页面
  13. */
  14. function toLogin() {
  15. uni.showToast({
  16. title: '请登录...',
  17. icon: 'loading',
  18. duration: 2000,
  19. success: function(res) {
  20. var pages = getCurrentPages() // 获取栈实例
  21. let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
  22. //console.log("路由当前页面路径"+currentRoute)
  23. let currentPage = pages[pages.length - 1]['$page']['fullPath'] //当前页面路径(带参数)
  24. // console.log(currentPage)
  25. // #ifdef H5 || APP-PLUS
  26. uni.navigateTo({
  27. url: '/pages/user/login?redirect=' + escape(currentPage)
  28. })
  29. // #endif
  30. // #ifdef MP-WEIXIN
  31. uni.navigateTo({
  32. url: '/pages/user/login?redirect=' + escape(currentPage),
  33. animationType: 'pop-in',
  34. animationDuration: 200
  35. });
  36. // #endif
  37. }
  38. })
  39. }
  40. /**
  41. * 是否登陆,和绑定手机号,否则返回登录页
  42. */
  43. function isLogin() {
  44. let user = db.get('user');
  45. //用户存在,不跳转,不存在直接跳转
  46. if (user) {
  47. if (user.id) {
  48. // if(user.mobile==''){
  49. // uni.navigateTo({
  50. // url: '/pages/user/bind'
  51. // })
  52. // }
  53. } else {
  54. console.log("user: ", user);
  55. db.del('user');
  56. db.del('auth');
  57. toLogin()
  58. }
  59. }
  60. }
  61. /**
  62. * 无图标提示
  63. * @param {String} msg 提示消息
  64. * @param {Function} callback 回调函数
  65. */
  66. function normalToShow(msg = '保存成功', callback = function() {}) {
  67. uni.showToast({
  68. title: msg,
  69. icon: 'none',
  70. duration: 2000,
  71. });
  72. setTimeout(function() {
  73. callback();
  74. }, 1000);
  75. }
  76. /**
  77. * 成功提示
  78. * @param {String} msg 提示消息
  79. * @param {Function} callback 回调函数
  80. */
  81. function successToShow(msg = '保存成功', callback = function() {}) {
  82. uni.showToast({
  83. title: msg,
  84. icon: 'success',
  85. duration: 2000,
  86. });
  87. setTimeout(function() {
  88. callback();
  89. }, 1500);
  90. }
  91. /**
  92. * 失败提示
  93. * @param {String} msg 提示消息
  94. * @param {Function} callback 回调函数
  95. */
  96. function errorToShow(msg = '操作失败', callback = function() {}) {
  97. uni.showToast({
  98. title: msg,
  99. icon: 'none',
  100. duration: 2000,
  101. });
  102. setTimeout(function() {
  103. callback();
  104. }, 2000);
  105. }
  106. /**
  107. * 加载显示
  108. * @param {String} msg 提示消息
  109. */
  110. function loadToShow(msg = '加载中', icon = 'loading') {
  111. uni.showToast({
  112. title: msg,
  113. icon: icon,
  114. });
  115. }
  116. /**
  117. * 加载隐藏
  118. */
  119. function loadToHide() {
  120. uni.hideToast();
  121. }
  122. /**
  123. * 提示框
  124. * @param {String} title 提示标题
  125. * @param {String} content 提示内容
  126. * @param {Function} callback 回调函数
  127. * @param {Boolean} showCancel = [true|false] 显示关闭按钮
  128. * @param {String} cancelText 关闭按钮文字
  129. * @param {String} confirmText 确定按钮文字
  130. * @example
  131. * modelShow('提示','确认执行此操作吗?',()=>{},()=>{},true,'取消','确定')
  132. */
  133. function modelShow(title = '提示', content = '确认执行此操作吗?', callback = () => {}, callback2 = () => {}, showCancel = true,
  134. cancelText = '拒绝',
  135. confirmText = '通过') {
  136. uni.showModal({
  137. title: title,
  138. content: content,
  139. showCancel: showCancel,
  140. cancelText: cancelText,
  141. confirmText: confirmText,
  142. success: function(res) {
  143. if (res.confirm) {
  144. // 用户点击确定操作
  145. setTimeout(() => {
  146. callback()
  147. }, 500)
  148. } else if (res.cancel) {
  149. // 用户取消操作
  150. setTimeout(() => {
  151. callback2()
  152. }, 500)
  153. }
  154. }
  155. });
  156. }
  157. /**
  158. * 判断数组
  159. * @param {Object} arr 数组
  160. */
  161. function isArray(object) {
  162. return object && typeof object === 'object'
  163. }
  164. /**
  165. * 统一跳转
  166. * @param {String} url 跳转链接
  167. */
  168. function navigateTo(url) {
  169. if (url == '')
  170. return;
  171. if (url.indexOf("/pages/index/index") >= 0 || url.indexOf("answer_pages/home/dashboard") >= 0 || url.indexOf(
  172. "/pages/shouhu/shouhu") >= 0 || url.indexOf("/pages/feiyi/feiyi") >= 0 || url.indexOf(
  173. "/pages/user/index") >= 0) {
  174. uni.switchTab({
  175. url: url,
  176. animationType: 'pop-in',
  177. animationDuration: 300
  178. });
  179. } else {
  180. uni.navigateTo({
  181. url: url,
  182. animationType: 'pop-in',
  183. animationDuration: 300
  184. });
  185. }
  186. }
  187. /**
  188. * 关闭当前页面并跳转
  189. * @param {String} url 跳转链接
  190. */
  191. function redirectTo(url) {
  192. uni.redirectTo({
  193. url: url,
  194. animationType: 'pop-in',
  195. animationDuration: 300
  196. })
  197. }
  198. /**
  199. * 返回上一层的逻辑判断
  200. * @param {num} delta 跳转上一层,或者几层
  201. */
  202. function navigateBack(delta = 1) {
  203. let pages = getCurrentPages(); //当前页
  204. //console.log(pages);
  205. //当有前一页的时候。
  206. if (pages.length > 1) {
  207. let page = pages[pages.length - 2]; //上个页面
  208. // console.log(page.route);
  209. if (page.route == "pages/index/index" || page.route == 'pages/index/homepage' || page.route ==
  210. 'pages/user/index' || page.route == 'pages/consult/index') {
  211. uni.switchTab({
  212. url: '/' + page.route
  213. })
  214. } else if (page.route == "pages/user/login") {
  215. uni.switchTab({
  216. url: '/pages/user/index'
  217. })
  218. } else if (page.route == "pages/user/register") {
  219. uni.switchTab({
  220. url: '/pages/user/user'
  221. })
  222. } else {
  223. uni.navigateBack({
  224. delta: delta
  225. })
  226. }
  227. } else {
  228. uni.switchTab({
  229. url: '/pages/index/index'
  230. })
  231. }
  232. }
  233. /**
  234. * 判断是否在微信浏览器
  235. */
  236. function isWeiXinBrowser() {
  237. // #ifdef H5
  238. // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息,这个属性可以用来判断浏览器类型
  239. let ua = window.navigator.userAgent.toLowerCase()
  240. // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
  241. if (ua.match(/MicroMessenger/i) == 'micromessenger') {
  242. return true
  243. } else {
  244. return false
  245. }
  246. // #endif
  247. // #ifdef MP
  248. return false;
  249. // #endif
  250. }
  251. /**
  252. * 加载cms列表
  253. * @param {Array} data
  254. *
  255. */
  256. function cmsGetList(data, callback = function() {}) {
  257. api.cmsGetList(data, res => {
  258. if (res.code) {
  259. res.data.list.forEach(function(ele, index) {
  260. ele.ctime = timeToDate(ele.createtime);
  261. if (ele.image.substring(0, 9) == '/uploads/') {
  262. ele.image = cndUrl + ele.image
  263. }
  264. });
  265. callback(res.data)
  266. } else {
  267. errorToShow(res.msg)
  268. }
  269. })
  270. }
  271. /**
  272. * 加载cms详情
  273. * @param {Array} data
  274. *
  275. */
  276. function cmsGetDetails(data, callback = function() {}) {
  277. api.cmsGetDetails(data, res => {
  278. //console.log(data)
  279. if (res.code) {
  280. res.data.content = htmlParser(res.data.content); // 设置资源cdn;
  281. res.data.ctime = timeToDate(res.data.createtime);
  282. if (res.data.image) {
  283. if (res.data.image.substring(0, 9) == '/uploads/') {
  284. res.data.image = cndUrl + res.data.image
  285. }
  286. }
  287. callback(res.data)
  288. } else {
  289. modelShow(
  290. '错误提示',
  291. res.msg,
  292. () => {
  293. uni.navigateBack({})
  294. },
  295. false
  296. );
  297. }
  298. })
  299. }
  300. /**
  301. * 初始化页面
  302. * @param {Function} callback 回调函数
  303. * @param {String} route 页面路径/默认当前路径
  304. */
  305. function initPages(callback = function() {}, route) {
  306. if (!route) {
  307. let pages = getCurrentPages();
  308. let page = pages[pages.length - 1];
  309. route = page.route
  310. }
  311. let init_data = db.get('init_' + route)
  312. setTimeout(() => {
  313. api.getInit({
  314. route: route
  315. }, res => {
  316. // console.log(res);
  317. if (res.code) {
  318. res.data.slide.forEach(function(ele, index) {
  319. if (ele.image.substring(0, 9) == '/uploads/') {
  320. ele.image = cndUrl + ele.image
  321. }
  322. });
  323. res.data.content.forEach(function(ele, index) {
  324. ele.content = ele.content.replace(new RegExp(`style="width: 100%;`, 'g'),
  325. 'style="width: 100%;margin-top: -3px;') // 无缝连接图片;
  326. ele.content = ele.content.replace(new RegExp(`src="/uploads`, 'g'),
  327. 'src="' + cndUrl + '/uploads')
  328. ele.content = htmlParser(ele.content); // 设置资源cdn;
  329. });
  330. db.set('init_' + route, res.data)
  331. callback(res.data)
  332. }
  333. });
  334. }, 1000);
  335. if (init_data) {
  336. callback(init_data)
  337. } else {
  338. // loadToShow('初始化页面...');
  339. }
  340. }
  341. /**
  342. * 跳转链接
  343. * @param {String} url 跳转链接
  344. */
  345. function toUrl(url) {
  346. if (url) {
  347. var objExp = new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/);
  348. if (objExp.test(url) != true) {
  349. // #ifdef APP-PLUS
  350. url = baseUrl + url
  351. // #endif
  352. // #ifdef H5
  353. url = baseUrl + url
  354. // #endif
  355. }
  356. //console.log(url)
  357. //return false
  358. // #ifdef MP
  359. uni.navigateTo({
  360. url: url
  361. })
  362. // #endif
  363. // #ifdef APP-PLUS
  364. plus.runtime.openURL(url);
  365. // #endif
  366. // #ifdef H5
  367. window.open(url);
  368. // #endif
  369. }
  370. }
  371. /**
  372. * 保存登陆状态
  373. * @param {Array} data 用户数据
  374. */
  375. function saveLogin(data) {
  376. db.set('auth', data.auth)
  377. if (data.user.avatar.substring(0, 9) == '/uploads/') {
  378. data.user.avatar = cndUrl + data.user.avatar
  379. }
  380. db.set('user', data.user)
  381. }
  382. /**
  383. * 刷新用户
  384. * @param {Function} callback 回调函数(用户数据)
  385. * @example
  386. * refreshUser((user)=>{_this.user = user})
  387. */
  388. function refreshUser(callback = function() {}) {
  389. let user = db.get('user');
  390. if (user.id) {
  391. api.refreshUser({}, res => {
  392. if (res.code == 1) {
  393. saveLogin(res.data)
  394. callback(res.data)
  395. } else {
  396. db.del('user');
  397. toLogin()
  398. }
  399. })
  400. } else {
  401. db.del('user');
  402. db.del('auth');
  403. toLogin()
  404. }
  405. }
  406. /**
  407. * 清理用户
  408. * @param {String} page 清理后跳转页面
  409. */
  410. function cleanUser(page) {
  411. db.del('user')
  412. db.del('auth')
  413. if (page) {
  414. redirectTo(page)
  415. }
  416. }
  417. /**
  418. * 字符串校验
  419. * @param {String} str 字符串
  420. * @param {String} model = [number|mobile|name|idcard|] 模式
  421. * @example
  422. * testString('17080057443','mobile')
  423. * testString('17080057443','mobile')
  424. */
  425. function testString(str, model = null) {
  426. if (typeof(model) == 'number') {
  427. if (str.length >= model) {
  428. return true
  429. }
  430. } else {
  431. switch (model) {
  432. case null:
  433. return false
  434. break
  435. case 'idcard':
  436. return RegExp(/^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/)
  437. .test(str)
  438. break
  439. case 'mobile':
  440. return RegExp(/^1[0-9]{10}$/).test(str)
  441. break
  442. case 'name':
  443. return RegExp(/^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/).test(str)
  444. break
  445. default:
  446. return false
  447. break
  448. }
  449. }
  450. return false
  451. }
  452. /**
  453. * 时间戳转时差
  454. * @param {String} date 时间戳
  455. */
  456. function timeToDate(time) {
  457. time = time * 1000
  458. var interval = new Date().getTime() - time;
  459. //计算出相差天数
  460. var returnTime = "";
  461. var days = Math.floor(interval / (24 * 3600 * 1000))
  462. if (days == 0) {
  463. //计算出小时数
  464. var leaveTime = interval % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
  465. var hours = Math.floor(leaveTime / (3600 * 1000))
  466. if (hours == 0) {
  467. //计算相差分钟数
  468. leaveTime = leaveTime % (3600 * 1000) //计算小时数后剩余的毫秒数
  469. var minutes = Math.floor(leaveTime / (60 * 1000))
  470. if (minutes == 0) {
  471. //计算相差秒数
  472. leaveTime = leaveTime % (60 * 1000) //计算分钟数后剩余的毫秒数
  473. var seconds = Math.round(leaveTime / 1000)
  474. return seconds + "秒前";
  475. }
  476. return minutes + "分钟前";
  477. }
  478. return hours + "小时前";
  479. }
  480. return days + "天前";
  481. }
  482. /**
  483. * 基本信息
  484. */
  485. function baseInfo() {
  486. return {
  487. bgClass: bgClass,
  488. title: title,
  489. baseLogo: baseLogo,
  490. }
  491. }
  492. //校验邮箱格式
  493. function checkEmail(email) {
  494. return RegExp(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/).test(
  495. email);
  496. }
  497. //校验手机格式
  498. function checkMobile(mobile) {
  499. return RegExp(/^1[0-9]{10}$/).test(mobile);
  500. }
  501. /**
  502. * 用户信息
  503. */
  504. function userInfo() {
  505. let user = db.get('user')
  506. if (user) {
  507. return user
  508. } else {
  509. return false;
  510. }
  511. // return {
  512. // bgClass: bgClass,
  513. // title: title,
  514. // baseLogo: baseLogo,
  515. // }
  516. }
  517. /**
  518. * 上传图片
  519. * @param {Array} data 附带数据
  520. * @param {Function} callback 回调函数
  521. * @param {int} num 限制数量
  522. * @param {String} type 类型
  523. * @return {String} url
  524. */
  525. function uploadImage(data = {}, callback = function() {}, num = 1, type) {
  526. api.uploadImage(
  527. 'common/upload', data, (res) => {
  528. if (res.code) {
  529. if (res.data.url.substring(0, 9) == '/uploads/') {
  530. res.data.url = cndUrl + res.data.url
  531. }
  532. callback(res.data.url)
  533. } else {
  534. errorToShow(res.msg)
  535. }
  536. }, type)
  537. }
  538. function formatRichText(html) {
  539. let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
  540. match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
  541. match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
  542. match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
  543. return match;
  544. });
  545. newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
  546. match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
  547. return match;
  548. });
  549. newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  550. newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:10px 0;"');
  551. return newContent;
  552. }
  553. export {
  554. toLogin,
  555. isLogin,
  556. normalToShow,
  557. successToShow,
  558. errorToShow,
  559. isArray,
  560. loadToShow,
  561. loadToHide,
  562. navigateTo,
  563. navigateBack,
  564. redirectTo,
  565. modelShow,
  566. isWeiXinBrowser,
  567. initPages,
  568. toUrl,
  569. saveLogin,
  570. refreshUser,
  571. cleanUser,
  572. testString,
  573. timeToDate,
  574. cmsGetList,
  575. cmsGetDetails,
  576. baseInfo,
  577. userInfo,
  578. uploadImage,
  579. checkEmail,
  580. checkMobile,
  581. formatRichText
  582. }