socket.js 33 KB

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