app.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. //app.js
  2. const { formatUrl, throttle } = require('utils/util.js')
  3. const sys = wx.getSystemInfoSync()
  4. App({
  5. onLaunch: function (options) {
  6. this.globalData.options = options
  7. },
  8. onShow: function (options) {
  9. this.globalData.options = options
  10. },
  11. onHide: function (e) {
  12. },
  13. onError: function (e) {
  14. wx.showToast({
  15. title: '程序执行失败',
  16. icon: 'none'
  17. })
  18. },
  19. onPageNotFound: function (res) {
  20. wx.showToast({
  21. title: '没有找到页面',
  22. icon: 'none'
  23. })
  24. },
  25. /**
  26. * 初始化
  27. */
  28. init: function () {
  29. const accessToken = this.getGlobalAttributeValue('accessToken')
  30. const userInfo = this.getGlobalAttributeValue('userInfo')
  31. this.getWxUserInfoSetting((type, res) => {
  32. // if (type != 1 || !userInfo) {
  33. // this.redirectCtl({ url: 'wx_authority' }, 1)
  34. // return
  35. // }
  36. this.globalData.userInfo = userInfo
  37. wx.checkSession({
  38. success: res => {
  39. this.globalData.accessToken = accessToken
  40. this.navigatePermissionsCtl()
  41. },
  42. fail: res => {
  43. this.login()
  44. }
  45. })
  46. })
  47. // this.post('/api/user/checkToken').then(res => {
  48. // if (accessToken) {
  49. // this.globalData.accessToken = accessToken
  50. // }
  51. // if (userInfo) {
  52. // this.globalData.userInfo = userInfo
  53. // } else {
  54. // this.redirectCtl({ url: 'wx_authority' }, 1)
  55. // return
  56. // }
  57. // this.navigatePermissionsCtl()
  58. // }).catch(res => {
  59. // this.login()
  60. // })
  61. },
  62. /**
  63. * 获取微信code
  64. */
  65. getWxloginCode: function (cb) {
  66. wx.login({
  67. success: res => {
  68. if (cb) cb(res.code)
  69. },
  70. fail: res => {
  71. wx.showToast({
  72. title: '获取微信code失败',
  73. icon: 'none'
  74. })
  75. }
  76. })
  77. },
  78. /**
  79. * 获取微信用户信息
  80. */
  81. login: function () {
  82. const { appType } = this.globalData
  83. this.getWxloginCode(code => {
  84. this.post('/api/user/tlogin', { code, appType }).then(this.handleLogin).catch(e => {
  85. if (e.data.code == '888') {
  86. this.redirectCtl({ url: 'wx_authority' }, 1)
  87. }
  88. })
  89. })
  90. },
  91. /**
  92. * 获取登录数据
  93. */
  94. handleLogin: function (res) {
  95. const { postData } = this.globalData
  96. const { accessToken } = res.data
  97. if (accessToken) {
  98. this.globalData.accessToken = accessToken
  99. wx.setStorageSync('accessToken', accessToken)
  100. // 判断当前是否有接口报登录失效,存在失效的情况下 接着执行
  101. if (postData) {
  102. const { fn, param } = postData
  103. fn(...param)
  104. this.globalData.postData = null
  105. return
  106. }
  107. this.navigatePermissionsCtl()
  108. }
  109. },
  110. /**
  111. * 权限判断跳转
  112. */
  113. navigatePermissionsCtl: function () {
  114. const { options, tempOptions } = this.globalData
  115. const { query = {}, scene, path } = options || tempOptions
  116. let url = ''
  117. if (query && query.type > 1) {
  118. url = path ? path.split('/')[1] : 'homework_list'
  119. const method = { ...query, url, scene }
  120. this.reLaunchCtl && this.reLaunchCtl({ url, method }, true)
  121. this.globalData.options = tempOptions
  122. } else {
  123. this.redirectCtl({ url: 'homework_list' }, 1)
  124. // this.getVipList()
  125. }
  126. },
  127. /**
  128. * 重新获取孩子列表
  129. * */
  130. getVipList: function () {
  131. const accessToken = this.getGlobalAttributeValue('accessToken')
  132. const userIdCache = wx.getStorageSync('userId')
  133. this.post({ src: '/api/parents/parents/V2/getMyInfo', method: { accessToken }, type: 1 }).then(res => {
  134. const { childList, imgUrl, userId, userName, phone} = res.data
  135. if (userIdCache == userId) {
  136. const parentVipList = wx.getStorageSync(`parentVipList-${userId}`)
  137. const parentVipLiIdx = wx.getStorageSync(`parentVipLiIdx-${userId}`)
  138. const parentVipId = wx.getStorageSync(`parentVipId-${userId}`)
  139. const parentInfo = wx.getStorageSync(`parentInfo-${userId}`)
  140. this.globalData.authority = wx.getStorageSync('authority')
  141. // if (phone) {
  142. // this.redirectCtl && this.redirectCtl({ url: 'homework_list', method: { vipId: parentVipId } }, true)
  143. // } else {
  144. // this.redirectCtl({ url: 'phone', method: { vipId: parentVipId,isFrist:1} }, true)
  145. // }
  146. } else {
  147. this.globalData.userId = userId
  148. wx.setStorageSync('userId', userId)
  149. this.globalData.parentInfo = res.data
  150. wx.setStorageSync(`parentInfo-${userId}`, res.data)
  151. if (childList.length > 0) {
  152. let vipId = childList[0].vipId
  153. let authority = 1
  154. this.globalData.parentVipList = childList
  155. this.globalData.parentVipLiIdx = 0
  156. this.globalData.parentVipId = vipId
  157. wx.setStorageSync(`parentVipList-${userId}`, childList)
  158. wx.setStorageSync(`parentVipLiIdx-${userId}`, 0)
  159. wx.setStorageSync(`parentVipId-${userId}`, vipId)
  160. this.globalData.authority = authority
  161. wx.setStorageSync('authority', authority)
  162. if (phone) {
  163. this.redirectCtl && this.redirectCtl({ url: 'homework_list', method: {} }, true)
  164. } else {
  165. this.redirectCtl({ url: 'phone', method: {isFrist: 1 }}, true)
  166. }
  167. } else {
  168. wx.removeStorageSync(`parentVipList-${userId}`)
  169. wx.removeStorageSync(`parentVipLiIdx-${userId}`)
  170. wx.removeStorageSync(`parentVipId-${userId}`)
  171. let authority = 0
  172. this.globalData.authority = authority
  173. wx.setStorageSync('authority', authority)
  174. if (phone) {
  175. this.redirectCtl && this.redirectCtl({ url: 'homework_list', method: {} }, true)
  176. } else {
  177. this.redirectCtl({ url: 'phone', method: {isFrist: 1 }}, true)
  178. }
  179. }
  180. }
  181. })
  182. },
  183. /**
  184. * 首次登录并保存微信用户数据
  185. * */
  186. saveUserInfo: function (res, code) {
  187. const { appType } = this.globalData
  188. const { encryptedData, iv, signature, userInfo } = res
  189. const user = Object.assign(userInfo, { encryptedData, iv, signature })
  190. this.post('/api/user/newlogin', { code, appType, ...user }).then(res => {
  191. this.globalData.userInfo = user
  192. wx.setStorageSync('userInfo', user)
  193. this.handleLogin(res)
  194. })
  195. },
  196. /**
  197. * 微信授权接口封装
  198. */
  199. wxSetting: function ({ scope, text }) {
  200. const isEmptyObject = function (e) {
  201. var temp;
  202. for (temp in e)
  203. return !1;
  204. return !0
  205. }
  206. return new Promise((resolve, reject) => {
  207. wx.getSetting({
  208. success: res => {
  209. if (isEmptyObject(res.authSetting)) {
  210. resolve(Object.assign(res, { type: 1, text: `请手动点击${text}` }))
  211. } else if (res.authSetting[scope] === true) {
  212. resolve(Object.assign(res, { type: 2, text: `默认${text}成功` }))
  213. } else if (res.authSetting[scope] === false) {
  214. wx.showModal({
  215. content: `检测到您没打开${text},是否去设置打开?`,
  216. confirmText: "确认",
  217. cancelText: "取消",
  218. success: res => {
  219. if (res.confirm) {
  220. wx.openSetting({
  221. success: res => {
  222. if (res.authSetting[scope]) {
  223. resolve(Object.assign(res, { type: 3, text: `手动设置${text}成功` }))
  224. } else {
  225. reject(Object.assign(res, { type: 5, text: `没有手动设置${text}` }))
  226. }
  227. },
  228. fail: res => {
  229. reject(Object.assign(res, { type: 4, text: `打开手动设置${text}失败` }))
  230. }
  231. })
  232. } else {
  233. reject(Object.assign(res, { type: 3, text: `拒绝打开手动设置${text}` }))
  234. }
  235. },
  236. fail: res => {
  237. reject(Object.assign(res, { type: 2, text: `弹出${text}提示框失败` }))
  238. }
  239. })
  240. } else {
  241. wx.authorize({
  242. scope,
  243. success: res => {
  244. resolve(Object.assign(res, { type: 4, text: `自动获取${text}成功` }))
  245. },
  246. fail: res => {
  247. reject(Object.assign(res, { type: 6, text: `自动获取${text}失败` }))
  248. }
  249. })
  250. }
  251. },
  252. fail: res => {
  253. reject(res, { type: 1, text: `获取${text}失败` })
  254. }
  255. })
  256. })
  257. },
  258. /**
  259. * 获取微信用户信息授权
  260. */
  261. getWxUserInfoSetting: function (cb) {
  262. this.wxSetting({ scope: 'scope.userInfo', text: '微信用户信息授权' }).then((res) => {
  263. wx.setStorageSync('hasUserInfo', 1)
  264. if (typeof cb === 'function') cb(1, res)
  265. }).catch((res) => {
  266. wx.setStorageSync('hasUserInfo', 0)
  267. if (res.type != 6) {
  268. wx.showToast({
  269. title: res.text,
  270. icon: 'none'
  271. })
  272. }
  273. if (typeof cb === 'function') cb(0, res)
  274. setTimeout(() => {
  275. wx.navigateBack({
  276. delta: 1
  277. })
  278. }, 2000)
  279. })
  280. },
  281. /**
  282. * 获取微信定位授权
  283. */
  284. getWxUserLocationSetting: function (cb) {
  285. this.wxSetting({ scope: 'scope.userLocation', text: '微信用户定位授权' }).then((res) => {
  286. wx.setStorageSync('isPosition', 1)
  287. if (typeof cb === 'function') {
  288. cb(res)
  289. }
  290. }).catch((res) => {
  291. wx.setStorageSync('isPosition', 0)
  292. wx.showToast({
  293. title: res.text,
  294. icon: 'none'
  295. })
  296. setTimeout(() => {
  297. wx.navigateBack({
  298. delta: 1
  299. })
  300. }, 1200)
  301. })
  302. },
  303. /**
  304. * 获取全局属性值
  305. */
  306. getGlobalAttributeValue: function (e1, e2 = e1) {
  307. return typeof this.globalData[e1] !== 'undefined' && this.globalData[e1] !== null ? this.globalData[e1] : typeof wx.getStorageSync(e2) !== 'undefined' && wx.getStorageSync(e2) !== null ? wx.getStorageSync(e2) : null
  308. },
  309. /**
  310. * POST 封装
  311. * @param obj{Object} {src【请求后台路径】, method【拼接在路径的参数对象】, type【判断是否需要把参数拼接在路径后面】} = obj
  312. * @param data{Object} data【自定义传的参数数据】
  313. * @param head{Boolean} head[true【data参数类型为json对象】,false【data参数类型为json字符串】]
  314. */
  315. post: function (obj, data = {}, head, postData) {
  316. const { host, loginTime, wechatsys, phoneimei, phonesys, phonetype, version, platform, build } = this.globalData
  317. const accessToken = this.globalData.accessToken || wx.getStorageSync('accessToken')
  318. let url
  319. if (typeof obj === 'object') {
  320. const { src, method = {}, type } = obj
  321. url = formatUrl(host + src, type == 1 ? method : Object.assign({}, method, { accessToken }))
  322. } else if (typeof obj === 'string') {
  323. url = formatUrl(host + obj, { accessToken })
  324. } else {
  325. throw new Error('请正确填写访问后台接口路径')
  326. return
  327. }
  328. return new Promise((resolve, reject) => {
  329. wx.request({
  330. url,
  331. data,
  332. method: 'POST',
  333. header: head ? {
  334. wechatsys, phoneimei, phonesys, phonetype, version, platform, build,
  335. "Content-Type": "application/x-www-form-urlencoded"
  336. } : {
  337. wechatsys, phoneimei, phonesys, phonetype, version, platform, build,
  338. "Content-Type": "application/json"
  339. },
  340. success: e => {
  341. if (e.statusCode == 200 && e.errMsg == 'request:ok') {
  342. if (e.data.code == '999') {
  343. resolve(e.data)
  344. } else {
  345. if (url.indexOf('/api/user/checkToken') == -1) {
  346. wx.showToast({
  347. title: e.data.msg,
  348. icon: 'none'
  349. })
  350. }
  351. reject(e.data)
  352. }
  353. if (loginTime > 0) {
  354. this.globalData.loginTime = 0
  355. }
  356. } else if (e.statusCode == 401) {
  357. this.globalData.loginTime = loginTime + 1
  358. if (loginTime < 2) {
  359. console.log('55555')
  360. this.globalData.postData = postData || null
  361. this.login()
  362. }
  363. } else {
  364. reject(e)
  365. wx.showToast({
  366. title: '加载失败',
  367. icon: 'none'
  368. })
  369. }
  370. },
  371. fail: e => {
  372. reject(e)
  373. wx.showToast({
  374. title: '加载失败',
  375. icon: 'none'
  376. })
  377. },
  378. complete: e => {
  379. console.log({ url, data })
  380. console.log(e.data)
  381. }
  382. })
  383. })
  384. },
  385. /**
  386. * uploadFile 封装
  387. * @param obj{Object} {src【请求后台路径】, method【拼接在路径的参数对象】, type【判断是否需要把参数拼接在路径后面】} = obj
  388. * @param file{String} file【微信小程序生成的临时文件资源路径】
  389. * @param data{Object} data【自定义传的参数数据】
  390. * @param head{Boolean} head[true【data参数类型为json对象】,false【data参数类型为json字符串】]
  391. * @param progress{Function} progress【上传文件进度条回调函数方法】
  392. */
  393. uploadFile: function (obj, file, data = {}, head, progress, postData) {
  394. const { host, loginTime, wechatsys, phoneimei, phonesys, phonetype, version, platform, build } = this.globalData
  395. const accessToken = this.globalData.accessToken || wx.getStorageSync('accessToken')
  396. let url
  397. if (typeof obj === 'object') {
  398. const { src, method, type } = obj
  399. url = formatUrl(host + src, type == 1 ? method : Object.assign(method || {}, { accessToken }))
  400. } else if (typeof obj === 'string') {
  401. url = formatUrl(host + obj, { accessToken })
  402. } else {
  403. throw new Error('请正确填写访问后台接口路径')
  404. return
  405. }
  406. wx.showLoading({
  407. title: '上传中...',
  408. })
  409. let uploadTask
  410. return new Promise((resolve, reject) => {
  411. uploadTask = wx.uploadFile({
  412. url,
  413. filePath: file,
  414. name: 'files',
  415. formData: data,
  416. header: head ? {
  417. wechatsys, phoneimei, phonesys, phonetype, version, platform, build,
  418. "Content-Type": "application/x-www-form-urlencoded"
  419. } : {
  420. wechatsys, phoneimei, phonesys, phonetype, version, platform, build,
  421. "Content-Type": "application/json"
  422. },
  423. success: e => {
  424. if (e.statusCode == 200 && e.errMsg == 'uploadFile:ok') {
  425. resolve(e.data)
  426. if (loginTime > 0) {
  427. this.globalData.loginTime = 0
  428. }
  429. } else if (e.statusCode == 401) {
  430. this.globalData.loginTime = loginTime + 1
  431. if (loginTime < 2) {
  432. this.globalData.postData = postData || null
  433. this.login()
  434. }
  435. } else {
  436. reject(e)
  437. wx.showToast({
  438. title: '加载失败',
  439. icon: 'none'
  440. })
  441. }
  442. },
  443. fail(e) {
  444. reject(e)
  445. wx.showToast({
  446. title: '加载失败',
  447. icon: 'none'
  448. })
  449. },
  450. complete(e) {
  451. console.log({ url, data })
  452. console.log(e.data)
  453. wx.hideLoading()
  454. }
  455. })
  456. })
  457. uploadTask.onProgressUpdate((res) => {
  458. progress && progress(res)
  459. wx.showLoading({
  460. title: ` 已上传(${res.progress}%)`
  461. })
  462. if (res.progress == 100) {
  463. wx.hideLoading()
  464. }
  465. })
  466. },
  467. /**
  468. * reLaunch路由跳转
  469. */
  470. reLaunchCtl: function (e, type) {
  471. const { method, url, msg } = type ? e : e.currentTarget.dataset
  472. if (!url) {
  473. wx.showToast({
  474. title: msg || '暂未开放',
  475. icon: 'none'
  476. })
  477. return
  478. }
  479. let array = []
  480. if (method) {
  481. for (let i in method) {
  482. if (typeof data === 'object') {
  483. array.push(`${i}=${JSON.stringify(method[i])}`)
  484. } else {
  485. array.push(`${i}=${method[i]}`)
  486. }
  487. }
  488. }
  489. wx.reLaunch({
  490. url: `${getCurrentPages().length == 0 ? 'pages' : '..'}/${url}/${url}${array.length > 0 ? '?' + array.join('&') : ''}`,
  491. success: res => { },
  492. fail: res => {
  493. wx.showToast({
  494. title: '跳转失败',
  495. icon: 'none'
  496. })
  497. }
  498. })
  499. },
  500. /**
  501. * navigate路由跳转
  502. */
  503. navigateCtl: throttle(function (e, type) {
  504. const { method, url, msg } = type ? e : e.currentTarget.dataset
  505. if (!url) {
  506. wx.showToast({
  507. title: msg || '暂未开放',
  508. icon: 'none'
  509. })
  510. return
  511. }
  512. let array = []
  513. if (method) {
  514. for (let i in method) {
  515. // console.log(data)
  516. if (typeof data === 'object') {
  517. array.push(`${i}=${JSON.stringify(method[i])}`)
  518. } else {
  519. array.push(`${i}=${method[i]}`)
  520. }
  521. }
  522. }
  523. wx.navigateTo({
  524. url: `${getCurrentPages().length == 0 ? 'pages' : '..'}/${url}/${url}${array.length > 0 ? '?' + array.join('&') : ''}`,
  525. success: res => { },
  526. fail: res => {
  527. wx.showToast({
  528. title: '跳转失败',
  529. icon: 'none'
  530. })
  531. }
  532. })
  533. },500),
  534. /**
  535. * redirect路由跳转
  536. */
  537. redirectCtl: function (e, type) {
  538. const { method, url, msg } = type ? e : e.currentTarget.dataset
  539. if (!url) {
  540. wx.showToast({
  541. title: msg || '暂未开放',
  542. icon: 'none'
  543. })
  544. return
  545. }
  546. let array = []
  547. if (method) {
  548. for (let i in method) {
  549. if (typeof data === 'object') {
  550. array.push(`${i}=${JSON.stringify(method[i])}`)
  551. } else {
  552. array.push(`${i}=${method[i]}`)
  553. }
  554. }
  555. }
  556. wx.redirectTo({
  557. url: `${getCurrentPages().length == 0 ? 'pages' : '..'}/${url}/${url}${array.length > 0 ? '?' + array.join('&') : ''}`,
  558. success: res => { },
  559. fail: res => {
  560. wx.showToast({
  561. title: '跳转失败',
  562. icon: 'none'
  563. })
  564. }
  565. })
  566. },
  567. /**
  568. * 查看图片
  569. */
  570. viewImageCtl: function (e) {
  571. let { images, index, baseurl, url = 'img' } = e.currentTarget.dataset
  572. let array = images.map((val, key) => {
  573. return baseurl + val[url]
  574. })
  575. wx.previewImage({
  576. current: baseurl + images[index][url], // 当前显示图片的http链接
  577. urls: array // 需要预览的图片http链接列表
  578. })
  579. },
  580. /**
  581. * 分享控制层
  582. */
  583. sharePageDefaultCtl: function (){
  584. return {
  585. title: '私塾家',
  586. path: 'pages/index/index?type=1',
  587. success: res => {
  588. wx.showToast({
  589. title: '转发成功',
  590. icon: 'success'
  591. })
  592. },
  593. fail: res => {
  594. wx.showToast({
  595. title: '转发失败',
  596. icon: 'none'
  597. })
  598. }
  599. }
  600. },
  601. /**
  602. * 全局变量
  603. */
  604. globalData: {
  605. wechatsys: sys.version + ' ' + sys.SDKVersion,
  606. phoneimei: '',
  607. phonesys: sys.system,
  608. phonetype: sys.brand + ' ' + sys.model,
  609. version: '3.1.7',
  610. platform: '3',
  611. build: '3.1.7',
  612. appType: 6,
  613. initStatus: 0,
  614. loginTime: 0,
  615. // host: 'https://api.sharingschool.com/sz',
  616. // baseImgUrl: 'https://img.sharingschool.com/',
  617. thumbnail: '?x-oss-process=image/resize,m_fill,h_300,w_200',
  618. host: 'https://xt.sharingschool.com/sz',
  619. baseImgUrl: 'https://xtimg.sharingschool.com',
  620. // thumbnail: '!m300x200.png',
  621. // baseImgUrl: 'https://xt.sharingschool.com/upload',
  622. accessToken: null,
  623. parentVipList: null,
  624. parentVipLiIdx: null,
  625. parentVipId: null,
  626. parentInfo: null,
  627. appid: 'wx3805cdb5bcb8646a',
  628. userInfo: null,
  629. options: null,
  630. postData: null,
  631. tempOptions: { query: {}, path: 'pages/index/index', scene: 1001 }
  632. }
  633. })