app.js 20 KB

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