util.js 31 KB

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