socket.js 32 KB

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