util.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. import api from '@/common/http/'
  2. import wx from 'weixin-js-sdk'
  3. import { axios } from '@/common/http/'
  4. import { isWeixin } from './common.js'
  5. import store from '@/store/index.js'
  6. import axios2 from 'axios'
  7. import { setStorage, getStorage, removeStorage } from '@/common/utils/storage.js'
  8. export const mini_env = function (cb) {
  9. if (isWeixin()) {
  10. wx.miniProgram.getEnv(res => {
  11. if (res.miniprogram) {
  12. cb(true)
  13. } else {
  14. cb(false)
  15. }
  16. })
  17. } else {
  18. cb(false)
  19. }
  20. }
  21. // 获取用户信息
  22. export const getUserInfo = () => {
  23. return new Promise((resolve, reject) => {
  24. api
  25. .get('/user/user/detail', {
  26. userId: store.state.user.userId
  27. })
  28. .then(response => {
  29. const { data } = response
  30. setStorage('user', data)
  31. resolve(data)
  32. })
  33. .catch(error => {
  34. reject(error)
  35. })
  36. })
  37. }
  38. export async function redirection() {
  39. const appid = getQueryVariable('appid') || getQueryVariable('appId')
  40. const goHome = [
  41. '/packageWorkorder/pages/orderList',
  42. '/packageMaterial/pages/stock/index',
  43. '/packageMaterial/pages/sale/index',
  44. '/packageMaterial/pages/newSale/index'
  45. ]
  46. const goMycon = [
  47. '/packageMine/pages/collection',
  48. '/packageMine/pages/profit/list',
  49. '/packageMine/pages/salesProfit/index',
  50. '/packageMine/pages/ranking/list',
  51. '/packageMine/pages/myWebsit'
  52. ]
  53. var userInfo = await getUserInfo()
  54. if (userInfo) {
  55. if (userInfo.type === 'GENERAL') {
  56. if (goHome.find(url => !!~window.location.href.split('?')[0].indexOf(url))) {
  57. uni.showModal({
  58. title: '提示',
  59. content: '您的账号没有权限!',
  60. showCancel: false,
  61. success: function (res) {
  62. if (res.confirm) {
  63. window.history.go(-(window.history.length - 1))
  64. window.location.href = `${process.env.VUE_APP_HREF}/pages/index/index?appid=${appid}`
  65. }
  66. }
  67. })
  68. return
  69. }
  70. if (goMycon.find(url => !!~window.location.href.split('?')[0].indexOf(url))) {
  71. uni.showModal({
  72. title: '提示',
  73. content: '您的账号没有权限!',
  74. showCancel: false,
  75. success: function (res) {
  76. if (res.confirm) {
  77. window.history.go(-(window.history.length - 1))
  78. window.location.href = `${process.env.VUE_APP_HREF}/pages/mine/index?appid=${appid}`
  79. }
  80. }
  81. })
  82. return
  83. }
  84. } else if (userInfo.type === 'SERVICE') {
  85. } else if (userInfo.type === 'WORKER') {
  86. }
  87. }
  88. }
  89. // 解析地址栏参数
  90. export const getQueryVariable = variable => {
  91. if (!window) {
  92. return undefined
  93. }
  94. // 从?开始获取后面的所有数据
  95. var query = window.location.search.substring(1)
  96. // 从字符串&开始分隔成数组split
  97. var vars = query.split('&')
  98. // 遍历该数组
  99. for (var i = 0; i < vars.length; i++) {
  100. // 从等号部分分割成字符
  101. var pair = vars[i].split('=')
  102. // 如果第一个元素等于 传进来的参的话 就输出第二个元素
  103. if (pair[0] == variable) {
  104. return pair[1] || ''
  105. }
  106. }
  107. return undefined
  108. }
  109. export function compareUrls(url1, url2) {
  110. // 创建 URL 对象来解析地址
  111. const parsedUrl1 = new URL(url1)
  112. const parsedUrl2 = new URL(url2)
  113. // 比较主要部分(不包括查询参数)
  114. const mainPartUrl1 = parsedUrl1.origin + parsedUrl1.pathname
  115. const mainPartUrl2 = parsedUrl2.origin + parsedUrl2.pathname
  116. return mainPartUrl1 === mainPartUrl2
  117. }
  118. export function removePreviousHistory() {
  119. // 获取当前页面的url
  120. const currentUrl = window.location.href
  121. if (compareUrls(getStorage('CurrentHrefUrlAddress') || '', currentUrl)) {
  122. removeStorage('CurrentHrefUrlAddress')
  123. // 使用 history 对象的 go 方法跳转到上一个历史记录
  124. window.history.go(-1)
  125. // 使用 history.replaceState
  126. window.history.replaceState(null, '', currentUrl)
  127. // 刷新页面
  128. window.location.reload()
  129. }
  130. }
  131. // 删除 url 上的参数
  132. function removeUrlParams(key) {
  133. let href = location.href
  134. const e = eval(`/&?${key}=[^&#]*/g`)
  135. href = href.replace(e, '')
  136. history.replaceState('', '', href)
  137. return href
  138. }
  139. function setStore(data = {}) {
  140. store.commit('user/set_userId', data.userId)
  141. store.commit('user/set_openId', data.openId)
  142. store.commit('user/set_name', data.nickName)
  143. store.commit('user/set_avatar', data.avatar)
  144. store.commit('user/set_mobile', data.mobile)
  145. store.commit('user/set_token', data.token)
  146. }
  147. export function truePath() {
  148. var currentURL = window.location.href
  149. var url = new URL(currentURL)
  150. var path = url.pathname
  151. var partToRemove = (function () {
  152. var hrefUrl = new URL(process.env.VUE_APP_HREF)
  153. if (hrefUrl.pathname && hrefUrl.pathname === '/') {
  154. return ''
  155. }
  156. return url.pathname
  157. })()
  158. if (path.startsWith(partToRemove)) {
  159. path = path.slice(partToRemove.length)
  160. }
  161. return path
  162. }
  163. export function rompamUrl() {
  164. // 获取当前页面的 URL
  165. var currentURL = window.location.href
  166. // 创建 URL 对象
  167. var url = new URL(currentURL)
  168. return url.origin + url.pathname
  169. }
  170. export function isEncoded(url) {
  171. return !!~url.indexOf('%3A%2F%2F') ? url : encodeURIComponent(url)
  172. }
  173. // 微信鉴权登入
  174. export function webLogin(bool = false) {
  175. return new Promise(async (resolve, reject) => {
  176. // 获取地址栏appid信息
  177. const appid = getQueryVariable('appid') || getQueryVariable('appId')
  178. // 判断是否微信环境下
  179. if (isWeixin() && appid) {
  180. // code是由授权后重定向返回携带
  181. const code = getQueryVariable('code')
  182. // isAuthorization用于强制重新获取授权token
  183. const isAuthorization = getQueryVariable('isAuthorization')
  184. // 获取当前地址
  185. var url = location.href
  186. // 获取记录的时间
  187. const isAuthorizationTime = getStorage('isAuthorizationTime')
  188. // 获取历史code
  189. const previousCode = getStorage('previousCode')
  190. if (code) {
  191. url = removeUrlParams('code')
  192. url = removeUrlParams('state')
  193. }
  194. // 是否强制授权
  195. if (isAuthorization && (!isAuthorizationTime || isAuthorizationTime < new Date().getTime())) {
  196. // 设置时间
  197. setStorage('isAuthorizationTime', new Date().getTime() + 2 * 60 * 60 * 1000)
  198. // 删除本地缓存
  199. setStore()
  200. url = removeUrlParams('x-token')
  201. // 去获取授权
  202. setTimeout(function () {
  203. window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${isEncoded(
  204. url
  205. )}&response_type=code&scope=snsapi_userinfo#wechat_redirect`
  206. }, 50)
  207. } else if (bool) {
  208. // 删除本地缓存
  209. setStore()
  210. // url = `${rompamUrl()}?appid=${appid}`
  211. url = removeUrlParams('x-token')
  212. // 去获取授权
  213. setTimeout(function () {
  214. window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${isEncoded(
  215. url
  216. )}&response_type=code&scope=snsapi_userinfo#wechat_redirect`
  217. }, 50)
  218. }
  219. // 判断是否有token有则不需要授权执行
  220. else if (code && code !== previousCode) {
  221. // 设置时间
  222. setStorage('previousCode', code)
  223. // 有token表示授权回来则执行code静默登入
  224. api
  225. .post('/user/auth2', {
  226. code: code
  227. })
  228. .then(async res => {
  229. setStore(res.data)
  230. resolve({})
  231. })
  232. .catch(reject)
  233. } else {
  234. resolve({})
  235. }
  236. } else {
  237. resolve({})
  238. }
  239. })
  240. }
  241. // 获取配置信息
  242. export const getConfigInfo = () => {
  243. return new Promise((resolve, reject) => {
  244. api
  245. .get('/common/config/get')
  246. .then(response => {
  247. const { data } = response
  248. resolve(data)
  249. })
  250. .catch(error => {
  251. reject(error)
  252. })
  253. })
  254. }
  255. // 获取模版信息
  256. export const getTemplateInfo = () => {
  257. return new Promise((resolve, reject) => {
  258. api
  259. .get('/renovation/detail')
  260. .then(response => {
  261. const { data } = response
  262. resolve(data)
  263. })
  264. .catch(error => {
  265. reject(error)
  266. })
  267. })
  268. }
  269. // 获取未读消息数量
  270. export const getNoticeNum = () => {
  271. return new Promise((resolve, reject) => {
  272. api
  273. .get('/notice/list/count', {
  274. readFlag: 'NO',
  275. noticeType: ''
  276. })
  277. .then(res => {
  278. if (res.data && res.data > 0) {
  279. uni.setTabBarBadge({
  280. index: 3,
  281. text: String(res.data)
  282. })
  283. } else {
  284. uni.removeTabBarBadge({
  285. index: 3
  286. })
  287. }
  288. resolve(res.data)
  289. })
  290. .catch(error => {
  291. resolve(0)
  292. })
  293. })
  294. }
  295. // 获取代办工单数量
  296. export const getOrderNum = async () => {
  297. const userInfo = await getUserInfo()
  298. return new Promise((resolve, reject) => {
  299. if (userInfo.type == 'WORKER') {
  300. api
  301. .post('/pg/order/base/status/count')
  302. .then(res => {
  303. if (res.data && res.data.djd + res.data.fwz > 0) {
  304. uni.setTabBarBadge({
  305. index: 1,
  306. text: String(res.data.djd + res.data.fwz)
  307. })
  308. } else {
  309. uni.removeTabBarBadge({
  310. index: 1
  311. })
  312. }
  313. resolve(res.data.djd + res.data.fwz)
  314. })
  315. .catch(error => {
  316. resolve(0)
  317. })
  318. } else {
  319. resolve(0)
  320. }
  321. })
  322. }
  323. const getUUID = function () {
  324. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
  325. return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16)
  326. })
  327. }
  328. const createName = function (name, s = '.') {
  329. const date = Date.now()
  330. const uuid = getUUID()
  331. const fileSuffix = name.substring(name.lastIndexOf(s) + 1)
  332. return `${date}${uuid}.${fileSuffix}`
  333. }
  334. const blobToFile = function (blobUrl) {
  335. return new Promise((r, j) => {
  336. const xhr = new XMLHttpRequest()
  337. xhr.open('GET', blobUrl, true)
  338. xhr.responseType = 'blob'
  339. xhr.onload = function () {
  340. if (xhr.status === 200) {
  341. const blobData = xhr.response
  342. const file = new File([blobData], createName(blobData.type, '/'), {
  343. type: blobData.type
  344. })
  345. r(file)
  346. } else {
  347. j(xhr.statusText)
  348. }
  349. }
  350. xhr.send()
  351. })
  352. }
  353. // 全链接图片上传
  354. export const uploadImgFull = async function (file) {
  355. console.log(file)
  356. uni.showLoading({
  357. mask: true
  358. })
  359. // #ifdef H5
  360. let formData = new FormData()
  361. formData.append('file', await blobToFile(file))
  362. // #endif
  363. return new Promise((resolve, reject) => {
  364. // #ifdef H5
  365. axios2
  366. .post(process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + '/common/upload', formData, {
  367. headers: {
  368. 'Content-Type': 'multipart/form-data',
  369. 'x-token': store.state.user.token
  370. }
  371. })
  372. .then(res => {
  373. uni.hideLoading()
  374. resolve(res.data.data)
  375. })
  376. // #endif
  377. // #ifdef MP-WEIXIN
  378. uni.uploadFile({
  379. url: process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + '/common/upload',
  380. header: {
  381. 'Content-Type': 'multipart/form-data',
  382. 'x-token': store.state.user.token
  383. },
  384. name: 'file',
  385. filePath: file,
  386. success(res) {
  387. uni.hideLoading()
  388. resolve(JSON.parse(res.data).data)
  389. },
  390. fail(err) {
  391. reject(err)
  392. },
  393. complete(res) {
  394. uni.hideLoading()
  395. }
  396. })
  397. // #endif
  398. })
  399. }
  400. // 图片上传
  401. export const uploadImg = async function (file) {
  402. console.log(file)
  403. uni.showLoading({
  404. mask: true
  405. })
  406. // 获取oss配置
  407. const par = await axios({
  408. url: '/common/oss/config',
  409. method: 'get'
  410. })
  411. .then(res => {
  412. return res.data
  413. })
  414. .catch(err => {
  415. uni.hideLoading()
  416. })
  417. const fileKey = par.dir + createName(file.name)
  418. return new Promise((resolve, reject) => {
  419. uni.uploadFile({
  420. url: par.host,
  421. // header: {
  422. // "Content-Type": 'multipart/form-data',
  423. // },
  424. name: 'file',
  425. formData: {
  426. ...par,
  427. name: file.name,
  428. key: fileKey
  429. },
  430. filePath: file.path,
  431. success(res) {
  432. resolve({
  433. url: fileKey
  434. })
  435. },
  436. fail(err) {
  437. reject(err)
  438. },
  439. complete(res) {
  440. uni.hideLoading()
  441. }
  442. })
  443. })
  444. }
  445. // 图片上传
  446. export const uploadBlobImg = async function (file) {
  447. console.log(file)
  448. uni.showLoading({
  449. mask: true
  450. })
  451. // 获取oss配置
  452. const par = await axios({
  453. url: '/common/oss/config',
  454. method: 'get'
  455. })
  456. .then(res => {
  457. return res.data
  458. })
  459. .catch(err => {
  460. uni.hideLoading()
  461. })
  462. const fileKey = par.dir + createName(file.name)
  463. return new Promise((resolve, reject) => {
  464. uni.uploadFile({
  465. url: par.host,
  466. // header: {
  467. // "Content-Type": 'multipart/form-data',
  468. // },
  469. name: 'file',
  470. formData: {
  471. ...par,
  472. name: file.name,
  473. key: fileKey
  474. },
  475. filePath: file.url,
  476. success(res) {
  477. resolve({
  478. url: fileKey
  479. })
  480. },
  481. fail(err) {
  482. reject(err)
  483. },
  484. complete(res) {
  485. uni.hideLoading()
  486. }
  487. })
  488. })
  489. }
  490. export const getArea = function (str) {
  491. let area = {}
  492. let index11 = 0
  493. let index1 = str.indexOf('省')
  494. if (index1 == -1) {
  495. index11 = str.indexOf('自治区')
  496. if (index11 != -1) {
  497. area.Province = str.substring(0, index11 + 3)
  498. } else {
  499. area.Province = str.substring(0, 0)
  500. }
  501. } else {
  502. area.Province = str.substring(0, index1 + 1)
  503. }
  504. let index2 = str.indexOf('市')
  505. if (index11 == -1) {
  506. area.City = str.substring(index11 + 1, index2 + 1)
  507. } else {
  508. if (index11 == 0) {
  509. area.City = str.substring(index1 + 1, index2 + 1)
  510. } else {
  511. area.City = str.substring(index11 + 3, index2 + 1)
  512. }
  513. }
  514. let index3 = str.lastIndexOf('区')
  515. if (index3 == -1) {
  516. index3 = str.indexOf('县')
  517. area.Country = str.substring(index2 + 1, index3 + 1)
  518. } else {
  519. area.Country = str.substring(index2 + 1, index3 + 1)
  520. }
  521. return area
  522. }
  523. // 图片上传
  524. export const uploadImgs = async function (file) {
  525. uni.showLoading({
  526. title: '上传中',
  527. mask: true
  528. })
  529. // 获取oss配置
  530. const par = await axios({
  531. url: '/common/oss/config',
  532. method: 'get'
  533. })
  534. .then(res => {
  535. return res.data
  536. })
  537. .catch(err => {
  538. uni.hideLoading()
  539. })
  540. const fileKey = par.dir + createName(file.name)
  541. return new Promise((resolve, reject) => {
  542. uni.uploadFile({
  543. url: par.host,
  544. // header: {
  545. // "Content-Type": 'multipart/form-data',
  546. // },
  547. name: 'file',
  548. formData: {
  549. ...par,
  550. name: file.name,
  551. key: fileKey
  552. },
  553. filePath: file.path,
  554. success(res) {
  555. resolve({
  556. url: fileKey
  557. })
  558. },
  559. fail(err) {
  560. reject(err)
  561. },
  562. complete(res) {
  563. uni.hideLoading()
  564. }
  565. })
  566. })
  567. }
  568. export const matchFileSuffixType = function (fileName) {
  569. // 后缀获取
  570. var suffix = ''
  571. // 获取类型结果
  572. var result = ''
  573. try {
  574. var flieArr = fileName.split('.')
  575. suffix = flieArr[flieArr.length - 1]
  576. } catch (err) {
  577. suffix = ''
  578. }
  579. // fileName无后缀返回 false
  580. if (!suffix) {
  581. result = false
  582. return result
  583. }
  584. // 图片格式
  585. var imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp']
  586. // 进行图片匹配
  587. result = imglist.some(function (item) {
  588. return item == suffix
  589. })
  590. if (result) {
  591. result = 'image'
  592. return result
  593. }
  594. // 匹配txt
  595. var txtlist = ['txt']
  596. result = txtlist.some(function (item) {
  597. return item == suffix
  598. })
  599. if (result) {
  600. result = 'txt'
  601. return result
  602. }
  603. // 匹配 excel
  604. var excelist = ['xls', 'xlsx']
  605. result = excelist.some(function (item) {
  606. return item == suffix
  607. })
  608. if (result) {
  609. result = 'excel'
  610. return result
  611. }
  612. // 匹配 word
  613. var wordlist = ['doc', 'docx']
  614. result = wordlist.some(function (item) {
  615. return item == suffix
  616. })
  617. if (result) {
  618. result = 'word'
  619. return result
  620. }
  621. // 匹配 pdf
  622. var pdflist = ['pdf']
  623. result = pdflist.some(function (item) {
  624. return item == suffix
  625. })
  626. if (result) {
  627. result = 'pdf'
  628. return result
  629. }
  630. // 匹配 ppt
  631. var pptlist = ['ppt', 'pptx']
  632. result = pptlist.some(function (item) {
  633. return item == suffix
  634. })
  635. if (result) {
  636. result = 'ppt'
  637. return result
  638. }
  639. // 匹配 视频
  640. var videolist = ['mp4', 'm2v', 'mkv']
  641. result = videolist.some(function (item) {
  642. return item == suffix
  643. })
  644. if (result) {
  645. result = 'video'
  646. return result
  647. }
  648. // 匹配 音频
  649. var radiolist = ['mp3', 'wav', 'wmv']
  650. result = radiolist.some(function (item) {
  651. return item == suffix
  652. })
  653. if (result) {
  654. result = 'radio'
  655. return result
  656. }
  657. // 其他 文件类型
  658. result = 'other'
  659. return result
  660. }
  661. // 时间格式化
  662. export const formatterDate = (date, fmt) => {
  663. let nowDate = {
  664. yyyy: date.getFullYear(), // 年
  665. MM: date.getMonth() + 1, // 月份
  666. dd: date.getDate() //日
  667. }
  668. if (/(y+)/.test(fmt)) {
  669. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  670. }
  671. for (var k in nowDate) {
  672. if (new RegExp('(' + k + ')').test(fmt)) {
  673. fmt = fmt.replace(
  674. RegExp.$1,
  675. RegExp.$1.length == 1 ? nowDate[k] : ('00' + nowDate[k]).substr(('' + nowDate[k]).length)
  676. )
  677. }
  678. }
  679. return fmt
  680. }
  681. /**
  682. * 比较时间是否在范围内
  683. * @param {Object} stime
  684. * @param {Object} etime
  685. * @return {Boolean}
  686. */
  687. export const compareTime = function (stime, etime) {
  688. function tranDate(time) {
  689. return new Date(time.replace(/-/g, '/')).getTime()
  690. }
  691. let startTime = tranDate(stime)
  692. let endTime = tranDate(etime)
  693. let nowTime = new Date().getTime()
  694. if (nowTime < startTime || nowTime > endTime) {
  695. return false
  696. }
  697. return true
  698. }
  699. /*
  700. *时间戳转化日期方法
  701. *@params val 时间戳,必传;
  702. *@params type 转化类型,非必传,默认返回年月日加时间,等于ymd时,返回年月日,等于hms返回时间
  703. */
  704. export const timeToDate = function (val, type) {
  705. if (!val) {
  706. throw new Error('val ')
  707. }
  708. var date = new Date(val * 1000),
  709. Y = date.getFullYear(),
  710. M = date.getMonth() + 1,
  711. D = date.getDate(),
  712. H = date.getHours(),
  713. m = date.getMinutes(),
  714. s = date.getSeconds()
  715. M = M < 10 ? '0' + M : M
  716. D = D < 10 ? '0' + D : D
  717. H = H < 10 ? '0' + H : H
  718. m = m < 10 ? '0' + m : m
  719. s = s < 10 ? '0' + s : s
  720. if (!type) {
  721. return `${Y}-${M}-${D} ${H}:${m}:${s}`
  722. } else if (type === 'ymd') {
  723. return `${Y}-${M}-${D}`
  724. } else if (type === 'hms') {
  725. return `${H}:${m}:${s}`
  726. }
  727. }
  728. var appModuleJsonGuding = null
  729. export const selectionChange = async function () {
  730. var index
  731. try {
  732. ;['pages/index/index', 'pages/workorder/index', 'pages/goods/index', 'pages/mine/index'].map((item, index_) => {
  733. if (!!~window.location.href.indexOf(item)) {
  734. index = index_
  735. throw new Error(``)
  736. }
  737. })
  738. } catch (err) {
  739. var doc = document.getElementsByClassName('uni-tabbar-bottom')
  740. if (doc && doc.length) {
  741. if (!appModuleJsonGuding) {
  742. try {
  743. doc[0].innerHTML = ''
  744. var { appModuleJson } = (await getUserInfo()) || {}
  745. if (appModuleJson) {
  746. appModuleJsonGuding = JSON.parse(appModuleJson)
  747. } else {
  748. appModuleJsonGuding = [
  749. { type: 'home', name: '首页', sort: 0 },
  750. { type: 'order', name: '工单', sort: 1 },
  751. { type: 'shop', name: '商城', sort: 2 },
  752. { type: 'my', name: '我的', sort: 3 }
  753. ]
  754. }
  755. } catch (error) {
  756. console.log(error)
  757. }
  758. }
  759. doc[0].innerHTML = (function () {
  760. var tabs = {
  761. home(item) {
  762. return `<div class="uni-tabbar__item" onclick="(function(){navToPage({url: '/pages/index/index'+window.location.search})})()">
  763. <div class="uni-tabbar__bd" style="height: 50px;">
  764. <div class="uni-tabbar__icon" style="width: 24px; height: 24px;">
  765. <img src="${process.env.VUE_APP_BASE_PATH}static/tabBar/icon_1${index == 0 ? '_cur' : ''}.png">
  766. </div>
  767. <div class="uni-tabbar__label" style="color: ${
  768. index == 0 ? 'rgb(61, 143, 253)' : 'rgb(122, 126, 131)'
  769. }; font-size: 10px; line-height: normal; margin-top: 3px;">
  770. ${item.name}
  771. </div>
  772. </div>
  773. </div>`
  774. },
  775. order(item) {
  776. return `<div class="uni-tabbar__item" onclick="(function(){navToPage({url: '/pages/workorder/index'+window.location.search+'&type=0&isWb=0'})})()">
  777. <div class="uni-tabbar__bd" style="height: 50px;">
  778. <div class="uni-tabbar__icon" style="width: 24px; height: 24px;">
  779. <img src="${process.env.VUE_APP_BASE_PATH}static/tabBar/icon_2${index == 1 ? '_cur' : ''}.png">
  780. </div>
  781. <div class="uni-tabbar__label" style="color: ${
  782. index == 1 ? 'rgb(61, 143, 253)' : 'rgb(122, 126, 131)'
  783. }; font-size: 10px; line-height: normal; margin-top: 3px;">
  784. ${item.name}
  785. </div>
  786. </div>
  787. </div>`
  788. },
  789. // shop(item) {
  790. // return `<div class="uni-tabbar__item" onclick="(function(){navToPage({url: '/pages/goods/index'+window.location.search})})()">
  791. // <div class="uni-tabbar__bd" style="height: 50px;">
  792. // <div class="uni-tabbar__icon" style="width: 24px; height: 24px;">
  793. // <img src="${process.env.VUE_APP_BASE_PATH}static/tabBar/icon_3${index == 2 ? '_cur' : ''}.png">
  794. // </div>
  795. // <div class="uni-tabbar__label" style="color: ${
  796. // index == 2 ? 'rgb(61, 143, 253)' : 'rgb(122, 126, 131)'
  797. // }; font-size: 10px; line-height: normal; margin-top: 3px;">
  798. // ${item.name}
  799. // </div>
  800. // </div>
  801. // </div>`
  802. // },
  803. my(item) {
  804. return `<div class="uni-tabbar__item" onclick="(function(){navToPage({url: '/pages/mine/index'+window.location.search})})()">
  805. <div class="uni-tabbar__bd" style="height: 50px;">
  806. <div class="uni-tabbar__icon" style="width: 24px; height: 24px;">
  807. <img src="${process.env.VUE_APP_BASE_PATH}static/tabBar/icon_4${index == 3 ? '_cur' : ''}.png">
  808. </div>
  809. <div class="uni-tabbar__label" style="color: ${
  810. index == 3 ? 'rgb(61, 143, 253)' : 'rgb(122, 126, 131)'
  811. }; font-size: 10px; line-height: normal; margin-top: 3px;">
  812. ${item.name}
  813. </div>
  814. </div>
  815. </div>`
  816. }
  817. }
  818. return `<div class="uni-tabbar" style="background-color: rgb(255, 255, 255); backdrop-filter: none;">
  819. <div class="uni-tabbar-border" style="background-color: rgba(0, 0, 0, 0.33);"></div>
  820. ${(appModuleJsonGuding || [])
  821. .sort((a, b) => a.sort - b.sort)
  822. .map(item => {
  823. return tabs?.[item.type]?.(item) || ''
  824. })
  825. .join('')}
  826. </div>
  827. <div class="uni-placeholder" style="height: 50px;"></div>`
  828. })()
  829. }
  830. }
  831. }
  832. // 微信支付直调
  833. export const onBridgeReady = function (data, successful, cancel, failure) {
  834. WeixinJSBridge.invoke(
  835. 'getBrandWCPayRequest',
  836. {
  837. // 以下6个支付参数通过蓝兔支付的jsapi接口获取
  838. // **************************
  839. appId: store.state.user.appId, //公众号appid
  840. timeStamp: data.timeStamp, //时间戳
  841. nonceStr: data.nonceStr, //随机字符串
  842. package: data.payPackage || data.package, //订单详情扩展字符串
  843. signType: 'MD5', //签名方式
  844. paySign: data.paySign
  845. },
  846. function (res) {
  847. console.log(JSON.stringify(res))
  848. // 支付成功
  849. if (res.err_msg == 'get_brand_wcpay_request:ok') {
  850. successful(res)
  851. }
  852. // 支付过程中用户取消
  853. if (res.err_msg == 'get_brand_wcpay_request:cancel') {
  854. cancel(res)
  855. }
  856. // 支付失败
  857. if (res.err_msg == 'get_brand_wcpay_request:fail') {
  858. failure(res)
  859. }
  860. /**
  861. * 其它
  862. * 1、请检查预支付会话标识prepay_id是否已失效
  863. * 2、请求的appid与下单接口的appid是否一致
  864. * */
  865. if (res.err_msg == '调用支付JSAPI缺少参数:total_fee') {
  866. failure(res)
  867. }
  868. }
  869. )
  870. }
  871. // 判断是否符合微信环境支付
  872. export const weixinPay = function (data, successful, cancel, failure) {
  873. if (typeof WeixinJSBridge == 'undefined') {
  874. if (document.addEventListener) {
  875. document.addEventListener(
  876. 'WeixinJSBridgeReady',
  877. function () {
  878. onBridgeReady(data, successful, cancel, failure)
  879. },
  880. false
  881. )
  882. } else if (document.attachEvent) {
  883. document.attachEvent('WeixinJSBridgeReady', function () {
  884. onBridgeReady(data, successful, cancel, failure)
  885. })
  886. document.attachEvent('onWeixinJSBridgeReady', function () {
  887. onBridgeReady(data, successful, cancel, failure)
  888. })
  889. }
  890. } else {
  891. onBridgeReady(data, successful, cancel, failure)
  892. }
  893. }
  894. // 微信授权验证配置
  895. export const wxConfig = function (configInfo, userInfo, cb) {
  896. let url = ''
  897. const systemInfo = uni.getSystemInfoSync()
  898. if (systemInfo.platform === 'android') {
  899. // 安卓平台
  900. url = window.location.href.split('#')[0] //获取到的url是当前页面的域名
  901. } else if (systemInfo.platform === 'ios') {
  902. // iOS平台
  903. url = getStorage('realAuthUrl')
  904. }
  905. api
  906. .post('/user/jsapi/sign', {
  907. url
  908. })
  909. .then(res => {
  910. const data = res.data
  911. if (data) {
  912. wx.config({
  913. debug: false, // 开启调试模式
  914. appId: data.appId, // 必填,企业号的唯一标识
  915. timestamp: data.timestamp, // 必填,生成签名的时间戳
  916. nonceStr: data.nonceStr, // 必填,生成签名的随机串
  917. signature: data.signature, // 必填,签名
  918. beta: true,
  919. jsApiList: [
  920. // 必填,需要使用的JS接口列表
  921. 'scanQRCode',
  922. 'checkJsApi',
  923. 'updateAppMessageShareData',
  924. 'updateTimelineShareData',
  925. 'onMenuShareTimeline',
  926. 'onMenuShareAppMessage',
  927. 'onMenuShareQQ',
  928. 'chooseInvoiceTitle',
  929. 'getLocation',
  930. 'openLocation'
  931. ]
  932. })
  933. wx.checkJsApi({
  934. jsApiList: ['getLocation'],
  935. success: function (res) {
  936. if (res.checkResult.getLocation == false) {
  937. alert('你的微信版本太低,不支持微信JS接口,请升级到最新的微信版本!')
  938. return
  939. }
  940. },
  941. fail: function (res) {
  942. console.log('checkJsApi fail=' + JSON.stringify(res))
  943. }
  944. })
  945. wx.ready(() => {
  946. cb?.()
  947. if (configInfo && userInfo) {
  948. wxShare({
  949. configInfo,
  950. userInfo
  951. })
  952. }
  953. })
  954. wx.error(function (res) {
  955. cb?.()
  956. // alert('出错了:' + res.errMsg) //wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。
  957. })
  958. } else {
  959. // alert('获取配置信息返回为空')
  960. }
  961. })
  962. }
  963. // 微信扫码
  964. export const wxScanCode = function (scanType = ['qrCode', 'barCode']) {
  965. return new Promise((resolve, reject) => {
  966. wx.scanQRCode({
  967. needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
  968. scanType: scanType,
  969. success: res => {
  970. console.log(res)
  971. var result = res.resultStr // 当 needResult 为 1 时,扫码返回的结果
  972. var resultArr = result.split(',') // 扫描结果以逗号分割数组
  973. var codeVal = resultArr[resultArr.length - 1] // 获取数组最后一个元素,也就是最终的内容
  974. resolve(codeVal)
  975. },
  976. fail: res => {
  977. reject('')
  978. alert('wx.scanQRCode失败')
  979. }
  980. })
  981. })
  982. }
  983. export const wxShare = function (options = {}) {
  984. if (!options) return
  985. const { configInfo, userInfo, title, desc, link, imgUrl } = options
  986. var appid = getQueryVariable('appid') || getQueryVariable('appId')
  987. wx.updateAppMessageShareData({
  988. title: title || `${userInfo.nickName}向你推荐了「${configInfo.minAppName}」`, // 分享标题
  989. desc: desc || '点击查看', // 分享描述
  990. link:
  991. link ||
  992. `${process.env.VUE_APP_HREF}/pages/index/index?appid=${appid}&serviceId=${userInfo.userId}&isAuthorization=1`, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
  993. imgUrl: imgUrl || `${configInfo.minLogo3}`, // 分享图标
  994. success: function () {
  995. // 设置成功
  996. },
  997. fail: function (err) {
  998. // alert(JSON.stringify(err))
  999. }
  1000. })
  1001. wx.updateTimelineShareData({
  1002. title: title || `${userInfo.nickName}向你推荐了「${configInfo.minAppName}」`, // 分享标题
  1003. desc: desc || '点击查看', // 分享描述
  1004. link:
  1005. link ||
  1006. `${process.env.VUE_APP_HREF}/pages/index/index?appid=${appid}&serviceId=${userInfo.userId}&isAuthorization=1`, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
  1007. imgUrl: imgUrl || `${configInfo.minLogo3}`, // 分享图标
  1008. success: function () {
  1009. // 设置成功
  1010. },
  1011. fail: function (err) {
  1012. // alert(JSON.stringify(err))
  1013. }
  1014. })
  1015. }
  1016. export default {
  1017. getQueryVariable,
  1018. webLogin,
  1019. getUserInfo,
  1020. getConfigInfo,
  1021. getTemplateInfo,
  1022. getNoticeNum,
  1023. getOrderNum,
  1024. uploadImgFull,
  1025. uploadImg,
  1026. getArea,
  1027. uploadImgs,
  1028. matchFileSuffixType,
  1029. formatterDate,
  1030. compareTime,
  1031. timeToDate,
  1032. selectionChange,
  1033. weixinPay,
  1034. wxConfig,
  1035. wxScanCode,
  1036. wxShare
  1037. }