common.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import store from '@/store'
  2. import { mobileReg } from './tools/validate'
  3. import { uploadPic } from '@/api/common'
  4. import CONSTANT from '@/constant/index'
  5. import { parse } from '@/utils/util'
  6. // 判断是mobile 还是pc
  7. export function isMobile() {
  8. // 移动端
  9. if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
  10. return true
  11. }
  12. return false
  13. }
  14. // 获取当前连接地址
  15. export function getUrlHref() {
  16. // let comProtocolUrl = window.location.protocol // 协议
  17. // let comHostUrl = window.location.host // 主机
  18. // let url = comProtocolUrl + '//' + comHostUrl
  19. // url = 'http://dev.meijiabang.com'
  20. return CONSTANT.formal
  21. }
  22. /** *
  23. * 跳转到商城
  24. * @parmas jumpUrl 跳转的页面地址
  25. * @parmas attrUrl 用户的头像地址
  26. * @parmas titleName 用户的名字
  27. * @parmas urlEndStr 跳转的页面url需要补充的参数 例'&aaa=111'
  28. */
  29. export function jumpShop(jumpUrl, attrUrl, titleName, urlEndStr) {
  30. }
  31. // 获取小程序地址完整路径
  32. export function getMiniAppUrl(data = {}, isPath = false) {
  33. let getCurPages = getCurrentPages()
  34. if (getCurPages.length == 0) return false
  35. let getCurPagesObj = getCurPages[getCurPages.length - 1]
  36. console.log(getCurPagesObj)
  37. // let getRoute = getCurPagesObj.route + queryData(getCurPagesObj.options)
  38. // let getRoute = getCurPagesObj.route + queryData(data)
  39. let getRoute = getCurPagesObj.route + parse(data)
  40. getRoute = isPath ? `${CONSTANT.formal}/#/${getRoute}` : getRoute
  41. return getRoute
  42. }
  43. // 获取当前时间戳
  44. export function getTimestamp() {
  45. return Date.parse(new Date())
  46. }
  47. // 生成从minNum到maxNum的随机数
  48. export function getRandomNum(minNum, maxNum) {
  49. switch (arguments.length) {
  50. case 1:
  51. return parseInt(Math.random() * minNum + 1, 10)
  52. // eslint-disable-next-line no-unreachable
  53. break
  54. case 2:
  55. return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10)
  56. break
  57. default:
  58. return 0
  59. break
  60. }
  61. }
  62. // 节流
  63. export function debounce(fn, time) {
  64. let handle
  65. return function (e) {
  66. // 取消之前的延时调用
  67. clearTimeout(handle)
  68. handle = setTimeout(() => {
  69. fn(e)
  70. }, time || 50)
  71. }
  72. }
  73. // 登录页面公共地址栏参数传递
  74. export function loginParmas(data) {
  75. // eslint-disable-next-line one-var
  76. const query = {},
  77. ownerUserId = data.owner_user_id,
  78. shareUserId = data.share_user_id,
  79. pShareUserId = data.p_share_user_id,
  80. f = data.f
  81. // eslint-disable-next-line camelcase
  82. if (ownerUserId) {
  83. query['owner_user_id'] = ownerUserId
  84. }
  85. if (shareUserId) {
  86. query['share_user_id'] = shareUserId
  87. }
  88. if (pShareUserId) {
  89. query['p_share_user_id'] = pShareUserId
  90. }
  91. if (f) {
  92. query['f'] = f
  93. }
  94. return query
  95. }
  96. /** *
  97. * 根据时间戳获取日期时间
  98. * fmt格式 例:yyyy-MM-dd hh:mm:ss
  99. * status 为 true 时是13位时间
  100. */
  101. export function getFormatDate(time, fmt, status) {
  102. try {
  103. time = status ? time : time * 1000
  104. const now = new Date(time)
  105. return now.Format(fmt)
  106. } catch (e) {
  107. if (window.console) {
  108. console.log(e)
  109. }
  110. }
  111. }
  112. /** *
  113. * 时间格式化
  114. */
  115. // eslint-disable-next-line no-extend-native
  116. Date.prototype.Format = function (fmt = 'yyyy-MM-dd hh:mm:ss') {
  117. const o = {
  118. 'M+': this.getMonth() + 1, // 月份
  119. 'd+': this.getDate(), // 日
  120. 'h+': this.getHours(), // 小时
  121. 'm+': this.getMinutes(), // 分
  122. 's+': this.getSeconds(), // 秒
  123. 'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
  124. S: this.getMilliseconds() // 毫秒
  125. }
  126. if (/(y+)/.test(fmt)) {
  127. fmt = fmt.replace(
  128. RegExp.$1,
  129. (this.getFullYear() + '').substr(4 - RegExp.$1.length)
  130. )
  131. }
  132. for (const k in o) {
  133. if (new RegExp('(' + k + ')').test(fmt)) {
  134. fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  135. }
  136. }
  137. return fmt
  138. }
  139. /** *
  140. * 根据日期获取时间戳
  141. * @parmas yyyy-MM-dd hh:mm:ss
  142. * @params second true的话获取的时间戳是到秒的
  143. */
  144. // 获取时间戳方法
  145. export function getDataTimestamp(time, second) {
  146. let etime = time || new Date
  147. if (second) {
  148. etime = Date.parse(time) / 1000
  149. } else {
  150. etime = new Date(etime)
  151. etime = etime.getTime()
  152. }
  153. return etime
  154. }
  155. /** *
  156. * 是否是微信浏览器
  157. */
  158. export function isWxBrowser() {
  159. let status = false
  160. // #ifdef H5
  161. const ua = window.navigator.userAgent.toLowerCase()
  162. // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
  163. if (ua.match(/MicroMessenger/i) == 'micromessenger') {
  164. status = true
  165. } else {
  166. status = false
  167. }
  168. // #endif
  169. // #ifdef MP-WEIXIN
  170. status = false
  171. // #endif
  172. return status
  173. }
  174. /** *
  175. * 是否是微信小程序
  176. */
  177. export function isWxMiniapp() {
  178. let status = false
  179. // #ifdef MP-WEIXIN
  180. status = true
  181. // #endif
  182. return status
  183. }
  184. // 验证手机号码格式
  185. export function verifiPhone(phone) {
  186. if (phone.length != 11) {
  187. return false
  188. }
  189. return mobileReg.test(phone)
  190. }
  191. /** *
  192. * 获取位置距离
  193. * form 开始经纬度数据信息
  194. * to 结束经纬度数据信息
  195. * rule 运费规则
  196. * onlyDistance 是否只需要距离值
  197. */
  198. export function calcDistance(form = null, to = null, rule = {}, onlyDistance = false) {
  199. console.log('我开始计算运费了')
  200. console.log('form', form)
  201. console.log('to', to)
  202. console.log('rule', rule)
  203. if (!form || !to) {
  204. return
  205. }
  206. let lat1 = to.lat || to.latitude,
  207. lng1 = to.lng || to.longitude,
  208. lat2 = form.lat || form.latitude,
  209. lng2 = form.lng || form.longitude
  210. if (lat1 && lng1 && lat2 && lng2) {
  211. // eslint-disable-next-line one-var
  212. lat1 = lat1 * 1
  213. lng1 = lng1 * 1
  214. lat2 = parseFloat(lat2)
  215. lng2 = parseFloat(lng2)
  216. let distance = parseInt(calcDistanceFn(lat1, lng1, lat2, lng2))
  217. // 只需要返回距离的时候
  218. if (onlyDistance) {
  219. return distance
  220. }
  221. // 需要返回具体金额
  222. let freight = (distance - rule.first) * rule.add
  223. console.log('freight', freight)
  224. return freight
  225. } else {
  226. return 0
  227. }
  228. }
  229. // 计算距离 公用方法
  230. export function calcDistanceFn(lat1, lng1, lat2, lng2) {
  231. const f = (((lat1 + lat2) / 2) * Math.PI) / 180.0
  232. const g = (((lat1 - lat2) / 2) * Math.PI) / 180.0
  233. const l = (((lng1 - lng2) / 2) * Math.PI) / 180.0
  234. let sg = Math.sin(g)
  235. let sl = Math.sin(l)
  236. let sf = Math.sin(f)
  237. let s, c, w, r, d, h1, h2
  238. const a = 6378.137 // 取WGS84标准参考椭球中的地球长半径 单位M
  239. const fl = 1 / 298.257
  240. sg = sg * sg
  241. sl = sl * sl
  242. sf = sf * sf
  243. s = sg * (1 - sl) + (1 - sf) * sl
  244. c = (1 - sg) * (1 - sl) + sf * sl
  245. w = Math.atan(Math.sqrt(s / c))
  246. r = Math.sqrt(s * c) / w
  247. d = 2 * w * a
  248. h1 = (3 * r - 1) / 2 / c
  249. h2 = (3 * r + 1) / 2 / s
  250. return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg))
  251. }
  252. // 对象参数转为url参数
  253. // export function queryData(data, getArr) {
  254. // let queryStr = ''
  255. // let num = 0
  256. // for (const i in data) {
  257. // if (!util.isEmpty(data[i])) {
  258. // if (num === 0) {
  259. // let arr = data[i]
  260. // if (getArr && Array.isArray(arr)) {
  261. // let str = ''
  262. // for (let j = 0; j < arr.length; j++) {
  263. // if (j == 0) {
  264. // str += `${i}[${j}]=${arr[j]}`
  265. // } else {
  266. // str += `&${i}[${j}]=${arr[j]}`
  267. // }
  268. // }
  269. // queryStr += `?${str}`
  270. // } else {
  271. // queryStr += `?${i}=${data[i]}`
  272. // }
  273. // } else {
  274. // let arr = data[i]
  275. // if (getArr && Array.isArray(arr)) {
  276. // let str = ''
  277. // for (let j = 0; j < arr.length; j++) {
  278. // str += `&${i}[${j}]=${arr[j]}`
  279. // }
  280. // queryStr += `${str}`
  281. // } else {
  282. // queryStr += `&${i}=${data[i]}`
  283. // }
  284. // }
  285. // num++
  286. // }
  287. // }
  288. // return queryStr
  289. // }
  290. // 上传图片到服务器
  291. export function upLoadImg(arr) {
  292. let params = {}
  293. if (arr.length === 1) {
  294. params['file[content]'] = arr[0]
  295. } else {
  296. arr.forEach((item, index) => {
  297. params[`file[${index}][content]`] = item
  298. })
  299. }
  300. return new Promise((resolve, reject) => {
  301. if (arr.length) {
  302. uploadPic({
  303. ...params,
  304. relative_path: 1
  305. }).then(res => {
  306. if (res.status === 'success') {
  307. const list = res.data.image_url.reverse()
  308. resolve(list)
  309. } else {
  310. reject(res)
  311. }
  312. })
  313. } else {
  314. resolve(arr)
  315. }
  316. })
  317. }
  318. // weixin base64转图片
  319. export function weixinBase64src(base64data) {
  320. return new Promise((resolve, reject) => {
  321. const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || []
  322. if (!format) {
  323. return (new Error('ERROR_BASE64SRC_PARSE'))
  324. }
  325. const filePath = `${wx.env.USER_DATA_PATH}/temporary_files1111aaccdd996633acv.${format}`
  326. const buffer = wx.base64ToArrayBuffer(bodyData)
  327. uni.getFileSystemManager().writeFile({
  328. filePath,
  329. data: buffer,
  330. encoding: 'binary',
  331. success: function (res) {
  332. resolve(filePath)
  333. },
  334. fail: function (err) {
  335. reject()
  336. console.log(err)
  337. }
  338. })
  339. })
  340. }
  341. // 深拷贝
  342. export function deepCopy(obj) {
  343. if (typeof obj !== 'object') { return }
  344. var str = JSON.stringify(obj)
  345. return JSON.parse(str)
  346. }
  347. // 复制到粘贴板
  348. export function copyText(str) {
  349. let that = this
  350. // #ifdef H5
  351. // 动态创建 textarea 标签
  352. const textarea = document.createElement('textarea')
  353. // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
  354. textarea.readOnly = 'readonly'
  355. textarea.style.position = 'absolute'
  356. textarea.style.left = '-9999upx'
  357. // 将要 copy 的值赋给 textarea 标签的 value 属性
  358. textarea.value = str
  359. // 将 textarea 插入到 body 中
  360. document.body.appendChild(textarea)
  361. // 选中值并复制
  362. textarea.select()
  363. textarea.setSelectionRange(0, textarea.value.length)
  364. const result = document.execCommand('Copy')
  365. if (result) {
  366. that.$msg('复制成功')
  367. }
  368. document.body.removeChild(textarea)
  369. // #endif
  370. // #ifndef H5
  371. uni.setClipboardData({
  372. data: str,
  373. success: function () {
  374. that.$msg('复制成功')
  375. }
  376. })
  377. // #endif
  378. }
  379. // 冒泡排序
  380. export function bubbleSort(array) {
  381. if (Object.prototype.toString.call(array).slice(8, -1) === 'Array') {
  382. var len = array.length,
  383. temp
  384. for (var i = 0; i < len - 1; i++) {
  385. for (var j = len - 1; j >= i; j--) {
  386. if (array[j - 1] && array[j].level < array[j - 1].level) {
  387. temp = array[j]
  388. array[j] = array[j - 1]
  389. array[j - 1] = temp
  390. }
  391. }
  392. }
  393. return array
  394. } else {
  395. return 'array is not an Array!'
  396. }
  397. }
  398. export default {
  399. copyText,
  400. deepCopy,
  401. debounce,
  402. getUrlHref,
  403. jumpShop,
  404. getMiniAppUrl,
  405. getTimestamp,
  406. getRandomNum,
  407. loginParmas,
  408. getFormatDate,
  409. isMobile,
  410. getDataTimestamp,
  411. isWxBrowser,
  412. isWxMiniapp,
  413. verifiPhone,
  414. calcDistance,
  415. upLoadImg,
  416. bubbleSort
  417. }