common.js 13 KB

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