socket.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  1. const { io } = require('./socket.io-v4.msgpack.js');
  2. var user = require('./services/user.js');
  3. const api = require('/config/api.js');
  4. const util = require('/utils/util.js');
  5. const UNLOGIN = 'NO_LOGIN'
  6. const btoa = require('./utils/btoa')
  7. const manyCount = 50
  8. import remote from './config.js'
  9. var app = getApp();
  10. var isIos = false
  11. wx.getSystemInfo({
  12. success: function (res) {
  13. isIos = res.platform == "ios"
  14. }
  15. })
  16. let urlToJson = (url = window.location.href) => { // 箭头函数默认传值为当前页面url
  17. let obj = {},
  18. index = url.indexOf('?'), // 看url有没有参数
  19. params = url.substr(index + 1); // 截取url参数部分 id = 1 & type = 2
  20. if (index != -1) { // 有参数时
  21. let parr = params.split('&'); // 将参数分割成数组 ["id = 1 ", " type = 2"]
  22. for (let i of parr) { // 遍历数组
  23. let arr = i.split('='); // 1) i id = 1 arr = [id, 1] 2)i type = 2 arr = [type, 2]
  24. obj[arr[0]] = arr[1]; // obj[arr[0]] = id, obj.id = 1 obj[arr[0]] = type, obj.type = 2
  25. }
  26. }
  27. return obj;
  28. }
  29. export default {
  30. joinUrl() {
  31. const url = true ? this.data.url.replace('shop.html', 'test-shop.html') : this.data.url;
  32. let options = {
  33. API_BASE_URL: api.API_BASE_URL,
  34. "url": url,
  35. // "url": 'http://192.168.0.112:8080',
  36. "reload": this.data.reload,
  37. "token": wx.getStorageSync('token'),
  38. "code": this.mcode,
  39. "brandId": this.options.id,
  40. "open": this.data.showCommodity,
  41. "pauseVideo": this.pauseVideo,
  42. "bottom": this.data.bottom || 0,
  43. socket: {
  44. socketHost: remote.socketHost,
  45. path: '/fsl-node',
  46. options: {
  47. ...this.data.socketOptions,
  48. // nickname: encodeURI(encodeURI(this.data.socketOptions.nickname))
  49. nickname: encodeURIComponent(encodeURIComponent(this.data.socketOptions.nickname))
  50. }
  51. }
  52. }
  53. // let base = 'http://127.0.0.1:5500/index.html'
  54. // let base = remote.viewHost + '/shop-container/shop.html'
  55. let sponsor = !!this.data.canShow
  56. if (this.data.join && !this.options.join) {
  57. sponsor = false
  58. }
  59. // remote.viewHost
  60. let hostUrl
  61. if (options.url.indexOf('www.4dkankan.com') != -1) {
  62. hostUrl = 'https://www.4dkankan.com/shop-container-zfb/'
  63. } else if (options.url.indexOf('test.4dkankan.com') != -1) {
  64. hostUrl = 'https://test.4dkankan.com/shop-container-zfb/'
  65. } else {
  66. // hostUrl = 'https://zfb.4dkankan.com/shop-container/'
  67. // hostUrl = remote.viewHost + '/shop-container/'
  68. hostUrl = remote.viewHost + '/shop-container-v4/'
  69. }
  70. // let base = remote.viewHost + '/shop-container/fashilong.html?env=' + remote.env + '&sponsor=' + sponsor + '&many=' + this.data.many
  71. let base = hostUrl + 'fashilong.html?time=' + Date.now() + '&env=' + remote.env + '&sponsor=' + sponsor + '&many=' + this.data.many
  72. // let base = remote.viewHost + '/shop.html'
  73. this.data.reload = false
  74. this.data.showCommodity = false
  75. options.url = options.url + '&vlog';
  76. if (!this.data.webviewUrl) {
  77. console.log(base)
  78. this.setData({
  79. 'webviewUrl': base + '#' + JSON.stringify(options)
  80. })
  81. } else {
  82. this.socketSendMessage('clientSyncAction', {
  83. sender: 'h5',
  84. type: 'hashChange',
  85. data: options
  86. })
  87. }
  88. },
  89. onShow() {
  90. this.setData({
  91. isIos,
  92. showComtypesAllTab: false
  93. })
  94. if (this.socketSendMessage) {
  95. this.pauseVideo = false
  96. this.joinUrl()
  97. this.socketSendMessage('changeOnlineStatus', {
  98. status: true
  99. })
  100. }
  101. },
  102. changeShowComtypesAllTab(ev) {
  103. this.setData({
  104. showCommodity: false
  105. })
  106. setTimeout(() => {
  107. this.setData({
  108. showComtypesAllTab: ev.currentTarget.dataset.show,
  109. showCommodity: true
  110. })
  111. }, 100)
  112. },
  113. async authorizeRecord() {
  114. let isAuth = await new Promise((r, j) => {
  115. wx.authorize({
  116. scope: 'scope.record',
  117. success: () => r(true),
  118. fail: () => r(false)
  119. })
  120. })
  121. if (isAuth) return true
  122. let res = await new Promise(r => {
  123. wx.showModal({
  124. title: '提示',
  125. content: '您未授权录音,说话功能将无法使用',
  126. showCancel: true,
  127. confirmText: "授权",
  128. confirmColor: "#52a2d8",
  129. success: res => r(res),
  130. fail: () => r(false)
  131. })
  132. })
  133. if (!res || res.cancel) return;
  134. isAuth = await new Promise((r) => {
  135. wx.openSetting({
  136. success: res => r(res.authSetting['scope.record']),
  137. fail: () => r(false)
  138. })
  139. })
  140. return isAuth
  141. },
  142. async agetUserInfo() {
  143. const res = await util.request(api.UserInfo)
  144. if (res.errno === 401) {
  145. return {
  146. userId: UNLOGIN,
  147. avatar: ''
  148. }
  149. } else {
  150. const data = res.data
  151. data.region = data.city ? data.city.split(',') : []
  152. data.birthday = data.birthday || '1990-01-01'
  153. return data
  154. }
  155. },
  156. async getUserInfo() {
  157. let userInfo = wx.getStorageSync('userInfo');
  158. let token = wx.getStorageSync('token');
  159. if (userInfo && userInfo.userId && token) {
  160. let info = await this.agetUserInfo()
  161. return {
  162. ...userInfo,
  163. ...info,
  164. avatarUrl: info.avatar
  165. };
  166. } else {
  167. return {
  168. userId: UNLOGIN,
  169. avatar: ''
  170. }
  171. }
  172. // let detail
  173. // let isAuth = await new Promise((r, j) => {
  174. // wx.authorize({
  175. // scope: 'scope.userInfo',
  176. // success: () => r(true),
  177. // fail: () => r(false)
  178. // })
  179. // })
  180. // if (!isAuth) {
  181. // this.setData({userAuth: true})
  182. // detail = await new Promise(r => {
  183. // this.bindGetUserInfo = (e) => {
  184. // if (e.detail.userInfo) {
  185. // this.setData({userAuth: false})
  186. // console.log('gei', e.detail)
  187. // r(e.detail)
  188. // }
  189. // }
  190. // })
  191. // } else {
  192. // detail = await new Promise(r => {
  193. // wx.getUserInfo({
  194. // success: res => r(res),
  195. // fail: () => r(false)
  196. // })
  197. // })
  198. // }
  199. // try {
  200. // let res = await user.loginByWeixin(detail)
  201. // app.globalData.userInfo = res.data.userInfo;
  202. // app.globalData.token = res.data.token;
  203. // return res.data.userInfo
  204. // } catch(e) {
  205. // return false
  206. // }
  207. },
  208. login() {
  209. getApp().setLoginProps(false)
  210. },
  211. async getSocketOptions(sceneId, roomId) {
  212. let room = roomId || (Number(Date.now().toString().slice(4)) + parseInt((Math.random() * 1000)))
  213. // let room = '147852'
  214. let userInfo = await this.getUserInfo()
  215. // console.log('---', userInfo)
  216. // this.setData({
  217. // userInfoa: userInfo.nickname.split('').join(' ')
  218. // })
  219. userInfo.nickname = userInfo.nickname.replace(/[^\u4E00-\u9FA5A-Za-z0-9]/g, '')
  220. if (userInfo.nickname == "") {
  221. userInfo.nickname = "口"
  222. }
  223. // this.role !== 'leader'
  224. let roomType
  225. if ((!this.data.canShow && !this.data.join) || (this.data.join && !this.options.join)) {
  226. roomType = '1v1'
  227. if (this.options.roomId) {
  228. this.role = 'leader'
  229. }
  230. console.log('**************')
  231. console.log(this.options)
  232. }
  233. // wx.showToast({
  234. // title: this.data.peopleCount.toString(),
  235. // })
  236. return {
  237. role: this.role || 'leader',
  238. userId: userInfo.userId,
  239. roomType,
  240. avatar: userInfo.avatarUrl,
  241. nickname: userInfo.nickname,
  242. voiceStatus: getApp().globalData.voiceProps.noMute ? 0 : 2,
  243. enableTalk: this.role === 'leader' ? true : undefined,
  244. roomId: room,
  245. sceneNumber: sceneId,
  246. onlineStatus: true,
  247. userLimitNum: this.data.peopleCount
  248. }
  249. },
  250. async socketStart({
  251. sceneId,
  252. roomId,
  253. options
  254. }) {
  255. if (!options) {
  256. options = await this.getSocketOptions(sceneId, roomId)
  257. }
  258. console.log('小程序参数', options)
  259. let socket = io(remote.socketHost, {
  260. path: '/fsl-node',
  261. transport: ['websocket'],
  262. query: {
  263. ...options,
  264. isClient: true,
  265. from: 2
  266. }
  267. })
  268. console.error('新建socket Room', options.roomId)
  269. this.setData({
  270. socketStatus: 0
  271. })
  272. socket.on('connect', () => this.setData({
  273. socketStatus: 1
  274. }))
  275. socket.on('connect_error', () => this.setData({
  276. socketStatus: -1
  277. }))
  278. socket.on('connect_timeout', () => this.setData({
  279. socketStatus: -1
  280. }))
  281. socket.on('disconnect', () => this.setData({
  282. socketStatus: -1
  283. }))
  284. socket.on('reconnect', () => {
  285. // wx.showToast({
  286. // title: '重连',
  287. // })
  288. this.setData({
  289. socketStatus: this.data.socketStatus
  290. })
  291. let noMute = getApp().globalData.voiceProps.noMute
  292. this.socketSendMessage('changeVoiceStatus', {
  293. status: noMute ? 0 : 2
  294. })
  295. this.socketSendMessage('changeOnlineStatus', {
  296. status: true
  297. })
  298. })
  299. socket.on('reconnect_failed', () => this.setData({
  300. socketStatus: -1
  301. }))
  302. socket.on('error', () => this.setData({
  303. socketStatus: -1
  304. }))
  305. socket.on('roomIn', config => {
  306. let enableTalk = config.roomsConfig.enableTalk !== false
  307. let noMute = getApp().globalData.voiceProps.noMute
  308. getApp().globalData.voiceProps.force = enableTalk
  309. if (!enableTalk && !noMute) {
  310. if (this.role !== 'leader') {
  311. // this.mic()
  312. }
  313. }
  314. })
  315. this.socketSendMessage = (event, obj) => {
  316. console.error('发送 socket Room', options.roomId, event, obj)
  317. socket.emit(event, obj)
  318. }
  319. socket.on('clientSyncAction', (data) => {
  320. console.log('调用', data.type, '方法', data)
  321. if (this[data.type]) {
  322. this[data.type](data)
  323. } else if (data.type == 'wx-subscribe') {
  324. this.getUrlCode(data.data)
  325. } else {
  326. console.error('没有', data.type, '方法')
  327. }
  328. })
  329. socket.on('action', (data) => {
  330. if (data.type === 'navigateToGoods') {
  331. this.navigateToGoodsAction(data.data)
  332. }
  333. })
  334. socket.on('changeRoomEnableTalk', config => {
  335. if (this.role !== 'leader') {
  336. this.changeRoomEnableTalk(config)
  337. }
  338. })
  339. socket.on('startCall', this.startCall.bind(this))
  340. socket.on('stopCall', (data) => {
  341. console.log('on stopCall')
  342. this.stopCall(data)
  343. })
  344. socket.on('someOneInRoom', this.startCall.bind(this))
  345. socket.on('someOneLeaveRoom', (user, data) => {
  346. this.handleSomeOneLeave(user)
  347. })
  348. socket.on('roomClose', (data) => {
  349. console.log('on roomClose')
  350. this.stopCall(data)
  351. })
  352. this.socketStop = () => {
  353. socket.close()
  354. console.error('断开 并滞空 socket Room', options.roomId)
  355. this.setData({
  356. socketStatus: 2
  357. })
  358. socket = null
  359. }
  360. return options
  361. },
  362. getUrlCode(url) {
  363. this.socketSendMessage('clientSyncAction', {
  364. sender: 'wx',
  365. type: 'wx-subscribe-result',
  366. data: 3020
  367. })
  368. // wx.request({
  369. // url: url, //仅为示例,并非真实的接口地址
  370. // method: 'get',
  371. // success: (res) => {
  372. // let code = -1
  373. // if (typeof res.data.code != 'undefined') {
  374. // code = res.data.code
  375. // }
  376. // this.socketSendMessage('clientSyncAction', {
  377. // sender: 'wx',
  378. // type: 'wx-subscribe-result',
  379. // data: code
  380. // })
  381. // },
  382. // fail: (err) => {
  383. // console.log(err)
  384. // }
  385. // })
  386. },
  387. changeRoomEnableTalk(data) {
  388. console.log(data)
  389. let noMute = getApp().globalData.voiceProps.noMute
  390. getApp().globalData.voiceProps.force = data.enableTalk
  391. // noMute true 静音
  392. // enableTalk false 静音
  393. if (!!data.enableTalk === !!noMute) {
  394. this.mic()
  395. }
  396. },
  397. navigateToGoods({
  398. data
  399. }) {
  400. // wx.showToast({
  401. // title: JSON.stringify(data).substr(40)
  402. // })
  403. this.navigateToGoodsAction(data)
  404. },
  405. navigateToGoodsAction(id) {
  406. wx.navigateTo({
  407. url: '/pages/goods/goods?id=' + id,
  408. })
  409. },
  410. getUrl(url, socketOptions, isJoin) {
  411. url += '&room_id=' + socketOptions.roomId + '&user_id=' + socketOptions.userId + '&origin=fashilong'
  412. if (isJoin) {
  413. url += '&role=' + this.role + '&shopping'
  414. } else {
  415. url += '&role=' + this.role
  416. }
  417. console.error(url)
  418. console.log(isJoin)
  419. return url
  420. },
  421. navigateToMiniProgram(data) {
  422. wx.showModal({
  423. title: '温馨提示',
  424. content: '即将跳到其他小程序,是否继续?',
  425. showCancel: true, //是否显示取消按钮
  426. cancelText: "取消", //默认是“取消”
  427. confirmText: "确定", //默认是“确定”
  428. success: function (res) {
  429. if (res.cancel) {
  430. //点击取消,wx.navigateBack
  431. } else {
  432. wx.navigateToMiniProgram(data.data)
  433. }
  434. },
  435. fail: function (res) {
  436. //接口调用失败的回调函数,wx.navigateBack
  437. },
  438. complete: function (res) {
  439. //接口调用结束的回调函数(调用成功、失败都会执行)
  440. },
  441. })
  442. },
  443. async startCall(data) {
  444. // if( this.role =='leader'){
  445. this.setData({
  446. shareStatus: 1
  447. })
  448. if (!data) return;
  449. this.setData({
  450. surplus: this.data.peopleCount - data.roomsPerson.length
  451. })
  452. //限制只有主持人才可以开麦
  453. if (this.role == 'leader') {
  454. if (!this.isAuthorizeRecord) {
  455. const voiceStatus = Number(await this.authorizeRecord())
  456. this.isAuthorizeRecord = true
  457. // getApp().setVoiceProps({
  458. // noMute: !voiceStatus
  459. // })
  460. // console.log(getApp().globalData.voiceProps.noMute)
  461. // this.socketSendMessage('changeVoiceStatus', {
  462. // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  463. // })
  464. // this.data.socketOptions.voiceStatus = 1
  465. // this.socketSendMessage('changeVoiceStatus', {status: noMute ? 0 : 2})
  466. }
  467. }
  468. const socketOptions = this.data.socketOptions
  469. getApp().globalData.roomId = socketOptions.roomId
  470. const user = data.roomsPerson.find(user => user.userId == socketOptions.userId)
  471. if (!user) {
  472. return
  473. }
  474. //屏蔽有人进来才开麦克风
  475. // if (data.roomsPerson.length <= 1) {
  476. // return
  477. // }
  478. user.noMute = getApp().globalData.voiceProps.noMute
  479. getApp().setVoiceProps({
  480. ...user,
  481. action: 'startCall'
  482. })
  483. // this.socketSendMessage('changeVoiceStatus', {
  484. // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  485. // })
  486. // }
  487. },
  488. stopCall() {
  489. console.error('stopCall')
  490. this.setData({
  491. shareStatus: 0
  492. })
  493. getApp().setVoiceProps({
  494. noMute: false,
  495. action: 'stopCall'
  496. })
  497. if (this.runManager) {
  498. // this.recorderManager.stop()
  499. this.runManager = false
  500. }
  501. },
  502. handleSomeOneLeave(data) {
  503. if (data.roomsPerson.length <= 1) {
  504. // this.stopCall()
  505. }
  506. this.setData({
  507. surplus: this.data.peopleCount - data.roomsPerson.length
  508. })
  509. },
  510. async newRoom(data) {
  511. if (data.roomId) return;
  512. this.stopCall()
  513. getApp().globalData.rtcParams = []
  514. getApp().globalData.pusher = ''
  515. if (this.data.join && !this.options.join) {
  516. wx.switchTab({
  517. url: '/pages/index/index',
  518. })
  519. return;
  520. }
  521. this.role = this.data.canShow ? 'leader' : 'customer'
  522. let options = await this.getSocketOptions(this.mcode)
  523. this.socketSendMessage('clientSyncAction', {
  524. type: 'newRoom',
  525. data: options
  526. })
  527. setTimeout(async () => {
  528. this.wssSuccess = false
  529. this.socketStop && this.socketStop()
  530. this.data.many = !!this.data.canShow
  531. this.setData({
  532. // peopleCount: this.data.many ? manyCount : 5
  533. peopleCount: manyCount
  534. })
  535. let base = this.base
  536. let socketOptions = await this.socketStart({
  537. options
  538. })
  539. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  540. this.base = base
  541. this.setData({
  542. url,
  543. socketOptions,
  544. })
  545. this.joinUrl()
  546. this.setData({
  547. socketOptions
  548. })
  549. this.loadConponSuccess = true
  550. this.readySendCouponCtrl()
  551. }, 300)
  552. },
  553. async exit() {
  554. this.stopCall()
  555. getApp().globalData.rtcParams = []
  556. getApp().globalData.pusher = ''
  557. this.socketStop && this.socketStop()
  558. this.role = 'leader'
  559. let base = this.base
  560. let socketOptions = await this.socketStart({
  561. sceneId: this.mcode
  562. })
  563. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  564. this.base = base
  565. wx.nextTick(() => {
  566. setTimeout(() => {
  567. this.setData({
  568. url,
  569. loadUrl: true,
  570. socketOptions,
  571. showCommodityCtrl: false,
  572. hideWebView: false,
  573. reload: true
  574. })
  575. this.joinUrl()
  576. }, 500)
  577. })
  578. },
  579. clearDebuger() {
  580. this.setData({
  581. debugerInfo: ''
  582. })
  583. },
  584. async mic() {
  585. let noMute = getApp().globalData.voiceProps.noMute
  586. // noMute true 静音
  587. // enableTalk false 静音
  588. // if (!!getApp().globalData.voiceProps.force === !!noMute)
  589. // return
  590. // if (!getApp().globalData.voiceProps.force && (!this.data.socketOptions.voiceStatus || noMute)) return;
  591. if (!this.data.socketOptions.voiceStatus) {
  592. let voiceStatus = await this.authorizeRecord()
  593. if (voiceStatus) {
  594. this.data.socketOptions.voiceStatus = 1
  595. noMute = false
  596. } else {
  597. noMute = true
  598. }
  599. } else {
  600. noMute = !noMute
  601. }
  602. getApp().globalData.voiceProps.noMute = noMute
  603. this.socketSendMessage('changeVoiceStatus', {
  604. status: noMute ? 0 : 2
  605. })
  606. getApp().setVoiceProps({
  607. noMute
  608. })
  609. wx.showToast({
  610. title: `已${noMute ? '关闭' : '开启'}麦克风`,
  611. })
  612. },
  613. callPhone() {
  614. wx.makePhoneCall({
  615. phoneNumber: this.data.contractPhone,
  616. })
  617. this.setData({
  618. showContact: false
  619. })
  620. },
  621. /**
  622. * 用户点击右上角分享
  623. */
  624. onShareAppMessage: function (res) {
  625. let {
  626. id,
  627. newPicUrl
  628. } = this.data
  629. if (res.from === 'button') {
  630. this.setData({
  631. sendShare: false
  632. })
  633. return {
  634. title: '【好友推荐】一起来云逛吧',
  635. imageUrl: newPicUrl,
  636. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=true&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`,
  637. }
  638. } else {
  639. return {
  640. imageUrl: newPicUrl,
  641. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=false`,
  642. }
  643. }
  644. },
  645. /**
  646. * 生命周期函数--监听页面卸载
  647. */
  648. onUnload: function () {
  649. console.log('on onUnload')
  650. this.socketSendMessage('stopCall', {})
  651. this.stopCall()
  652. this.socketStop()
  653. getApp().globalData.pusher = ''
  654. },
  655. cart(data) {
  656. this.setData({
  657. showCommodityCtrl: data.data
  658. })
  659. },
  660. share() {
  661. console.log('**********')
  662. // console.log(!!this.data.mamy)
  663. const companyName = `指房宝(杭州)科技有限公司`
  664. const vrLink = `/pages/webview/index`
  665. const img_url = this.data.newPicUrl || 'http://video.cgaii.com/new4dage/images/images/home_2_a.jpg'
  666. const shareImg = img_url
  667. this.count = this.count || 0
  668. if (this.data.many && this.data.shareStatus == 1) {
  669. //开启一起逛时候的分享
  670. console.log(`/pages/shareRoom/shareRoom?img_url=${btoa(img_url)}&vrLink=${btoa(vrLink)}&id=${this.data.id}&type=${this.data.type}&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`)
  671. console.log(this.data.socketOptions)
  672. wx.navigateTo({
  673. url: `/pages/shareRoom/shareRoom?img_url=${btoa(img_url)}&vrLink=${btoa(vrLink)}&id=${this.data.id}&type=${this.data.type}&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`,
  674. })
  675. } else {
  676. console.log(`/pages/shared/shared?img_url=${btoa(img_url)}&shareImg=${btoa(shareImg)}&companyName=${companyName}&vrLink=${btoa(vrLink)}&id=${this.data.id}&type=${this.data.type}`);
  677. wx.navigateTo({
  678. url: `/pages/shared/shared?img_url=${btoa(img_url)}&shareImg=${btoa(shareImg)}&companyName=${companyName}&vrLink=${btoa(vrLink)}&id=${this.data.id}&type=${this.data.type}`,
  679. })
  680. }
  681. },
  682. back(data) {
  683. if (data.sender !== 'h5') return;
  684. wx.switchTab({
  685. url: '/pages/index/index'
  686. })
  687. this.setData({
  688. showCommodityCtrl: false
  689. })
  690. },
  691. service() {
  692. this.setData({
  693. showContact: true,
  694. showCommodity: false,
  695. showCoupon: false
  696. })
  697. },
  698. invite(data) {
  699. if (data.sender !== 'h5') return;
  700. this.setData({
  701. sendShare: true,
  702. count: ++this.data.count
  703. })
  704. },
  705. coupon(data) {
  706. if (data.sender !== 'h5') return;
  707. this.setData({
  708. showContact: false,
  709. showCommodity: false,
  710. showCoupon: true
  711. })
  712. },
  713. liveGotoGood(ev) {
  714. let id = ev.currentTarget.dataset.item.goodsId
  715. wx.navigateTo({
  716. url: '/pages/goods/goods?id=' + id,
  717. })
  718. },
  719. gotoGoodsDOM(event) {
  720. this.gotoGoods(event.currentTarget.dataset.item.hotIdList[0])
  721. },
  722. gotoGoodsSocket(data) {
  723. this.gotoGoods(data.data)
  724. },
  725. gotoGoods(id) {
  726. console.log('---', id)
  727. this.socketSendMessage('clientSyncAction', {
  728. type: 'openTag',
  729. data: id
  730. })
  731. this.setData({
  732. showCommodity: false
  733. })
  734. this.joinUrl()
  735. },
  736. addCard(event) {
  737. wx.navigateTo({
  738. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=addCard',
  739. })
  740. },
  741. buyGoods(event) {
  742. wx.navigateTo({
  743. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=buyGoods',
  744. })
  745. },
  746. showCommodityFn() {
  747. this.setData({
  748. showCommodity: true,
  749. showContact: false,
  750. showCoupon: false
  751. })
  752. this.joinUrl()
  753. },
  754. hideComodity() {
  755. this.setData({
  756. showCommodity: false
  757. })
  758. this.joinUrl()
  759. },
  760. hideCoupon() {
  761. this.setData({
  762. showCoupon: !this.data.showCoupon
  763. })
  764. },
  765. async receive(ev) {
  766. let item = ev.target.dataset.item
  767. try {
  768. // wx.showToast({
  769. // title: '领取优惠卷',
  770. // })
  771. // return;
  772. if (item.hasReceived || item.number <= item.receiveNumber) return;
  773. let res = await util.request(api.CouponExchange, {
  774. couponId: item.id
  775. })
  776. if (res.code === 0) {
  777. wx.showToast({
  778. title: '已成功领取',
  779. success: () => {
  780. this.setData({
  781. showCoupon: false
  782. })
  783. wx.nextTick(() => {
  784. this.setData({
  785. coupons: this.data.coupons.map(citem => {
  786. return {
  787. ...citem,
  788. hasReceived: citem.id === item.id ? true : citem.hasReceived
  789. }
  790. }),
  791. showCoupon: true
  792. })
  793. })
  794. }
  795. })
  796. } else if (res.errno === 401) {
  797. getApp().setLoginProps(false)
  798. } else {
  799. wx.showToast({
  800. title: res.msg,
  801. })
  802. }
  803. } catch (e) {
  804. console.error(e)
  805. wx.showToast({
  806. icon: 'none',
  807. title: '领取失败',
  808. })
  809. }
  810. },
  811. async getCouponList(id) {
  812. const success = (res) => {
  813. this.setData({
  814. coupons: res.data.list.map(item => {
  815. item.typeMoney = item.typeMoney.toString()
  816. item.fontSize = item.typeMoney.length === 3 ? '90rpx' :
  817. item.typeMoney.length === 4 ? '70rpx' : '130rpx'
  818. return item
  819. })
  820. })
  821. this.loadConponSuccess = true
  822. this.readySendCouponCtrl()
  823. }
  824. let res = await util.request(api.BrandCouponList, {
  825. brandId: id,
  826. pageNum: 1,
  827. pageSize: 10000
  828. }, 'GET')
  829. console.log(res)
  830. if (res.code === 0) {
  831. success(res)
  832. } else {
  833. let res = await util.request(api.UNBrandCouponList, {
  834. brandId: id,
  835. pageNum: 1,
  836. pageSize: 10000
  837. }, 'GET')
  838. success(res)
  839. }
  840. },
  841. ready() {
  842. this.wssSuccess = true
  843. this.readySendCouponCtrl()
  844. },
  845. readySendCouponCtrl() {
  846. if (this.wssSuccess && this.loadConponSuccess) {
  847. this.loadConponSuccess = false
  848. this.socketSendMessage('clientSyncAction', {
  849. type: 'showCoupon',
  850. data: this.data.coupons.length > 0
  851. })
  852. }
  853. },
  854. getBrand: function (id, code) {
  855. this.getGoodsCount(code, id)
  856. return;
  857. let that = this;
  858. util.request(api.SueneCategory, {
  859. sceneNum: code
  860. }, 'GET').then(function (res) {
  861. if (res.code === 0) {
  862. const comtypes = res.list.map(item => {
  863. item.width = (item.name.length + (item.num.toString().length / 2) + 2) * 16
  864. return {
  865. ...item
  866. }
  867. })
  868. that.setData({
  869. comWidth: comtypes.reduce((a, b) => a + b.width + 10, 0),
  870. comtypes,
  871. thumComtypes: (!isIos && comtypes.length > 3) ? comtypes.slice(0, 3) : null,
  872. currTypeId: comtypes.length > 0 && comtypes[0].category_id
  873. });
  874. wx.showToast({
  875. title: 'currTypeId' + that.data.currTypeId.length,
  876. })
  877. that.data.currTypeId && that.getGoodsList(id, that.data.currTypeId);
  878. }
  879. });
  880. },
  881. getGoodsCount(code, id) {
  882. util.request(api.GoodsNumCount, {
  883. isDelete: 0,
  884. isOnSale: 1,
  885. brandId: id
  886. }, 'GET')
  887. .then(res => {
  888. if (res.code === 0) {
  889. this.setData({
  890. goodsCount: res.data
  891. })
  892. }
  893. this.getCouponList(id)
  894. })
  895. },
  896. getGoodsList(id, category_id) {
  897. var that = this;
  898. if (!(this.data.navList && this.data.navList.length)) {
  899. that.navDatas = {}
  900. let navDatas = this.data.navList = this.data.comtypes
  901. // util.request(api.GoodsCategory, { id: category_id })
  902. // .then(function (res) {
  903. // if (res.errno == 0) {
  904. // let navDatas = res.data.brotherCategory
  905. // that.setData({
  906. // navList: navDatas,
  907. // currTypeId: category_id
  908. // });
  909. that.navDatas = {}
  910. navDatas.forEach(item => {
  911. util.request(api.GoodsList, {
  912. brandId: id,
  913. categoryId: item.category_id,
  914. page: that.data.page,
  915. size: that.data.size
  916. })
  917. .then(res => {
  918. if (res.errno === 0) {
  919. that.navDatas[item.category_id] = res.data.goodsList
  920. }
  921. })
  922. })
  923. // }
  924. // })
  925. }
  926. if (that.navDatas[category_id]) {
  927. if (!isIos) {
  928. let showCommodity = that.data.showCommodity
  929. that.setData({
  930. showCommodity: false
  931. })
  932. setTimeout(() => {
  933. wx.nextTick(() => {
  934. that.setData({
  935. goodsList: that.navDatas[category_id],
  936. currTypeId: category_id,
  937. showCommodity: showCommodity
  938. });
  939. })
  940. }, 500)
  941. } else {
  942. that.setData({
  943. goodsList: that.navDatas[category_id],
  944. currTypeId: category_id,
  945. });
  946. }
  947. } else {
  948. console.error('诱惑去啦')
  949. util.request(api.GoodsList, {
  950. brandId: id,
  951. categoryId: category_id,
  952. page: that.data.page,
  953. size: that.data.size
  954. })
  955. .then(function (res) {
  956. if (res.errno === 0) {
  957. that.setData({
  958. goodsList: res.data.goodsList,
  959. currTypeId: category_id
  960. });
  961. // this.data.navList
  962. }
  963. });
  964. }
  965. },
  966. getBrandDetail: function (id, type, cb) {
  967. util.request(api.BrandDetail, {
  968. id: id,
  969. type: type,
  970. }).then((res) => {
  971. let base = res.data.brand.sceneUrl
  972. // let base = 'http://192.168.0.112:8080/shop.html?m=t-7Uqj9Fq&origin=fashilong'
  973. if (res.errno === 0) {
  974. let url = base + "&sid=" + id
  975. this.setData({
  976. id: id,
  977. newPicUrl: res.data.brand.appListPicUrl,
  978. sceneNum: res.data.brand.sceneNum,
  979. canShow: res.data.brand.canShow,
  980. contractPhone: res.data.brand.contractPhone
  981. })
  982. if (this.data.many === void 0) {
  983. this.data.many = !!res.data.brand.canShow
  984. }
  985. this.setData({
  986. // peopleCount: this.data.many ? manyCount : 5,
  987. peopleCount: manyCount
  988. })
  989. if (!res.data.brand.canShow) {
  990. this.role = 'customer'
  991. } else if (!this.options.join) {
  992. this.role = 'leader'
  993. }
  994. cb(url, urlToJson(url).m, )
  995. }
  996. });
  997. },
  998. selectType(ev) {
  999. this.getGoodsList(this.options.id, ev.target.dataset.item.category_id)
  1000. },
  1001. hideCS() {
  1002. this.setData({
  1003. showCommodity: false,
  1004. showCoupon: false,
  1005. showContact: false
  1006. })
  1007. },
  1008. hideContact() {
  1009. this.setData({
  1010. showContact: false
  1011. })
  1012. },
  1013. calcShare() {
  1014. // this.exit()
  1015. this.setData({
  1016. sendShare: false
  1017. })
  1018. },
  1019. contactKf() {
  1020. let keys = Object.keys(this.navDatas)
  1021. let goodsId = this.navDatas[keys[0]][0].id
  1022. let user = wx.getStorageSync('userinfoDetail')
  1023. util.request(api.AddTalkCount, {
  1024. goodsId,
  1025. viewId: user && user.userId || '',
  1026. sceneNum: this.data.sceneNum
  1027. }, 'get')
  1028. this.hideAlert && this.hideAlert()
  1029. this.hideContact && this.hideContact()
  1030. },
  1031. onHide() {
  1032. this.socketSendMessage('changeOnlineStatus', {
  1033. status: false
  1034. })
  1035. this.pauseVideo = true
  1036. this.joinUrl()
  1037. }
  1038. }