util.js 29 KB

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