util.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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/sale/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, //订单详情扩展字符串
  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) {
  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. ]
  930. })
  931. wx.ready(() => {
  932. if (configInfo && userInfo) {
  933. wxShare({
  934. configInfo,
  935. userInfo
  936. })
  937. }
  938. })
  939. wx.error(function (res) {
  940. // alert('出错了:' + res.errMsg) //wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。
  941. })
  942. } else {
  943. // alert('获取配置信息返回为空')
  944. }
  945. })
  946. }
  947. // 微信扫码
  948. export const wxScanCode = function (scanType = ['qrCode', 'barCode']) {
  949. return new Promise((resolve, reject) => {
  950. wx.scanQRCode({
  951. needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
  952. scanType,
  953. success: res => {
  954. var result = res.resultStr // 当 needResult 为 1 时,扫码返回的结果
  955. var resultArr = result.split(',') // 扫描结果以逗号分割数组
  956. var codeVal = resultArr[resultArr.length - 1] // 获取数组最后一个元素,也就是最终的内容
  957. resolve(codeVal)
  958. },
  959. fail: res => {
  960. reject('')
  961. alert('wx.scanQRCode失败')
  962. }
  963. })
  964. })
  965. }
  966. export const wxShare = function (options = {}) {
  967. if (!options) return
  968. const { configInfo, userInfo, title, desc, link, imgUrl } = options
  969. var appid = getQueryVariable('appid') || getQueryVariable('appId')
  970. wx.updateAppMessageShareData({
  971. title: title || `${userInfo.nickName}向你推荐了「${configInfo.minAppName}」`, // 分享标题
  972. desc: desc || '点击查看', // 分享描述
  973. link:
  974. link ||
  975. `${process.env.VUE_APP_HREF}/pages/index/index?appid=${appid}&serviceId=${userInfo.userId}&isAuthorization=1`, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
  976. imgUrl: imgUrl || `${configInfo.minLogo3}`, // 分享图标
  977. success: function () {
  978. // 设置成功
  979. },
  980. fail: function (err) {
  981. // alert(JSON.stringify(err))
  982. }
  983. })
  984. wx.updateTimelineShareData({
  985. title: title || `${userInfo.nickName}向你推荐了「${configInfo.minAppName}」`, // 分享标题
  986. desc: desc || '点击查看', // 分享描述
  987. link:
  988. link ||
  989. `${process.env.VUE_APP_HREF}/pages/index/index?appid=${appid}&serviceId=${userInfo.userId}&isAuthorization=1`, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
  990. imgUrl: imgUrl || `${configInfo.minLogo3}`, // 分享图标
  991. success: function () {
  992. // 设置成功
  993. },
  994. fail: function (err) {
  995. // alert(JSON.stringify(err))
  996. }
  997. })
  998. }
  999. export default {
  1000. getQueryVariable,
  1001. webLogin,
  1002. getUserInfo,
  1003. getConfigInfo,
  1004. getTemplateInfo,
  1005. getNoticeNum,
  1006. getOrderNum,
  1007. uploadImgFull,
  1008. uploadImg,
  1009. getArea,
  1010. uploadImgs,
  1011. matchFileSuffixType,
  1012. formatterDate,
  1013. compareTime,
  1014. timeToDate,
  1015. selectionChange,
  1016. weixinPay,
  1017. wxConfig,
  1018. wxScanCode,
  1019. wxShare
  1020. }