socket.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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. const that = this
  433. if (data.userId && data.roomId) {
  434. const socketOptions = this.data.socketOptions
  435. const userId = data.userId
  436. const roomId = data.roomId
  437. // debugger
  438. if (socketOptions.userId == userId && this.options.roomId == roomId) {
  439. wx.showToast({
  440. title: '您已被踢出房间!',
  441. icon: 'none',
  442. complete: () => {
  443. setTimeout(() => {
  444. that.socketStop();
  445. wx.switchTab({
  446. url: '/pages/index/index',
  447. })
  448. }, 1000)
  449. }
  450. })
  451. }
  452. }
  453. });
  454. this.socketStop = () => {
  455. if (socket) {
  456. socket.close()
  457. console.error('断开 并滞空 socket Room', options.roomId)
  458. this.setData({
  459. socketStatus: 2
  460. })
  461. socket = null
  462. }
  463. }
  464. return options
  465. },
  466. getUrlCode(url) {
  467. this.socketSendMessage('clientSyncAction', {
  468. sender: 'wx',
  469. type: 'wx-subscribe-result',
  470. data: 3020
  471. })
  472. // wx.request({
  473. // url: url, //仅为示例,并非真实的接口地址
  474. // method: 'get',
  475. // success: (res) => {
  476. // let code = -1
  477. // if (typeof res.data.code != 'undefined') {
  478. // code = res.data.code
  479. // }
  480. // this.socketSendMessage('clientSyncAction', {
  481. // sender: 'wx',
  482. // type: 'wx-subscribe-result',
  483. // data: code
  484. // })
  485. // },
  486. // fail: (err) => {
  487. // console.log(err)
  488. // }
  489. // })
  490. },
  491. changeRoomEnableTalk(data) {
  492. console.log(data)
  493. let noMute = getApp().globalData.voiceProps.noMute
  494. getApp().globalData.voiceProps.force = data.enableTalk
  495. // noMute true 静音
  496. // enableTalk false 静音
  497. if (!!data.enableTalk === !!noMute) {
  498. this.mic()
  499. }
  500. },
  501. navigateToGoods({
  502. data
  503. }) {
  504. // wx.showToast({
  505. // title: JSON.stringify(data).substr(40)
  506. // })
  507. this.navigateToGoodsAction(data)
  508. },
  509. navigateToGoodsAction(id) {
  510. wx.navigateTo({
  511. url: '/pages/goods/goods?id=' + id,
  512. })
  513. },
  514. getUrl(url, socketOptions, isJoin) {
  515. url += '&room_id=' + socketOptions.roomId + '&user_id=' + socketOptions.userId + '&origin=fashilong'
  516. if (isJoin) {
  517. url += '&role=' + this.role + '&shopping'
  518. } else {
  519. url += '&role=' + this.role
  520. }
  521. console.error(url)
  522. console.log(isJoin)
  523. return url
  524. },
  525. navigateToMiniProgram(data) {
  526. wx.showModal({
  527. title: '温馨提示',
  528. content: '即将跳到其他小程序,是否继续?',
  529. showCancel: true, //是否显示取消按钮
  530. cancelText: "取消", //默认是“取消”
  531. confirmText: "确定", //默认是“确定”
  532. success: function (res) {
  533. if (res.cancel) {
  534. //点击取消,wx.navigateBack
  535. } else {
  536. wx.navigateToMiniProgram(data.data)
  537. }
  538. },
  539. fail: function (res) {
  540. //接口调用失败的回调函数,wx.navigateBack
  541. },
  542. complete: function (res) {
  543. //接口调用结束的回调函数(调用成功、失败都会执行)
  544. },
  545. })
  546. },
  547. async handleSomeOneInRoom(data) {
  548. if (data && data.user) {
  549. console.log('handleSomeOneInRoom', data)
  550. this.startCall(data)
  551. }
  552. },
  553. async startCall(data) {
  554. //TODO 触发三次
  555. console.log('startCall-data', data)
  556. // if( this.role =='leader'){
  557. this.setData({
  558. shareStatus: 1
  559. })
  560. if (!data) return;
  561. this.setData({
  562. surplus: this.data.peopleCount - data.roomsPerson.length
  563. })
  564. //undefined是未授权,状态为3
  565. let voiceStatus
  566. if (!this.isAuthorizeRecord) {
  567. const unAuth = await this.authorizeRecord();
  568. if (typeof unAuth === 'undefined') {
  569. // debugger
  570. voiceStatus = 3
  571. } else {
  572. voiceStatus = Number(unAuth)
  573. }
  574. }
  575. //限制只有主持人才可以开麦
  576. // if (this.role == 'leader') {
  577. // if (!this.isAuthorizeRecord) {
  578. // const voiceStatus = Number(await this.authorizeRecord())
  579. // this.isAuthorizeRecord = true
  580. // // getApp().setVoiceProps({
  581. // // noMute: !voiceStatus
  582. // // })
  583. // // console.log(getApp().globalData.voiceProps.noMute)
  584. // // this.socketSendMessage('changeVoiceStatus', {
  585. // // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  586. // // })
  587. // // this.data.socketOptions.voiceStatus = 1
  588. // // this.socketSendMessage('changeVoiceStatus', {status: noMute ? 0 : 2})
  589. // }
  590. // }
  591. const socketOptions = this.data.socketOptions
  592. getApp().globalData.roomId = socketOptions.roomId
  593. const user = data.roomsPerson.find(user => user.userId == socketOptions.userId)
  594. if (!user) {
  595. return
  596. }
  597. //屏蔽有人进来才开麦克风
  598. // if (data.roomsPerson.length <= 1) {
  599. // return
  600. // }
  601. user.noMute = getApp().globalData.voiceProps.noMute
  602. getApp().setVoiceProps({
  603. ...user,
  604. action: 'startCall'
  605. })
  606. // this.socketSendMessage('changeVoiceStatus', {
  607. // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  608. // })
  609. // }
  610. },
  611. stopCall() {
  612. console.error('stopCall')
  613. this.setData({
  614. shareStatus: 0
  615. })
  616. getApp().setVoiceProps({
  617. noMute: false,
  618. action: 'stopCall'
  619. })
  620. if (this.runManager) {
  621. // this.recorderManager.stop()
  622. this.runManager = false
  623. }
  624. },
  625. handleSomeOneLeave(data) {
  626. if (data.roomsPerson.length <= 1) {
  627. // this.stopCall()
  628. }
  629. this.setData({
  630. surplus: this.data.peopleCount - data.roomsPerson.length
  631. })
  632. },
  633. //deprecated
  634. async newRoomBk(data) {
  635. if (data.roomId) return;
  636. this.stopCall()
  637. getApp().globalData.rtcParams = []
  638. getApp().globalData.pusher = ''
  639. if (this.data.join && !this.options.join) {
  640. wx.switchTab({
  641. url: '/pages/index/index',
  642. })
  643. return;
  644. }
  645. this.role = this.data.canShow ? 'leader' : 'customer'
  646. let options = await this.getSocketOptions(this.mcode)
  647. this.socketSendMessage('clientSyncAction', {
  648. type: 'newRoom',
  649. data: options
  650. })
  651. setTimeout(async () => {
  652. this.wssSuccess = false
  653. this.socketStop && this.socketStop()
  654. this.data.many = !!this.data.canShow
  655. this.setData({
  656. // peopleCount: this.data.many ? manyCount : 5
  657. peopleCount: manyCount
  658. })
  659. let base = this.base
  660. let socketOptions = await this.socketStart({
  661. options
  662. })
  663. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  664. this.base = base
  665. this.setData({
  666. url,
  667. socketOptions,
  668. })
  669. this.joinUrl()
  670. this.setData({
  671. socketOptions
  672. })
  673. this.loadConponSuccess = true
  674. this.readySendCouponCtrl()
  675. }, 300)
  676. },
  677. // 真正退出房间
  678. async exitRoom() {
  679. const roomId = this.data.socketOptions.roomId;
  680. const role = this.role;
  681. const result = await util.request(api.exitRoom, {
  682. businessId: roomId
  683. }, 'POST', 'application/json');
  684. this.socketSendMessage('stopCall', {
  685. from: 2
  686. })
  687. this.stopCall();
  688. this.socketStop();
  689. if (role === 'leader') {
  690. wx.redirectTo({
  691. url: '/pages/roomManger/roomManger',
  692. });
  693. } else {
  694. wx.switchTab({
  695. url: '/pages/index/index'
  696. });
  697. }
  698. },
  699. async exit() {
  700. // this.stopCall()
  701. getApp().globalData.rtcParams = []
  702. getApp().globalData.pusher = ''
  703. this.socketStop && this.socketStop()
  704. this.role = 'leader'
  705. let base = this.base
  706. let socketOptions = await this.socketStart({
  707. sceneId: this.mcode
  708. })
  709. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  710. this.base = base
  711. wx.nextTick(() => {
  712. setTimeout(() => {
  713. this.setData({
  714. url,
  715. loadUrl: true,
  716. socketOptions,
  717. showCommodityCtrl: false,
  718. hideWebView: false,
  719. reload: true
  720. })
  721. this.joinUrl()
  722. }, 500)
  723. })
  724. },
  725. clearDebuger() {
  726. this.setData({
  727. debugerInfo: ''
  728. })
  729. },
  730. async mic({
  731. data
  732. }) {
  733. if (Number(data.user.isAllowMic) === 1) {
  734. let noMute = getApp().globalData.voiceProps.noMute
  735. // debugger
  736. // noMute true 静音
  737. // enableTalk false 静音
  738. // if (!!getApp().globalData.voiceProps.force === !!noMute)
  739. // return
  740. // if (!getApp().globalData.voiceProps.force && (!this.data.socketOptions.voiceStatus || noMute)) return;
  741. if (!this.data.socketOptions.voiceStatus) {
  742. let voiceStatus = await this.authorizeRecord()
  743. if (voiceStatus) {
  744. this.data.socketOptions.voiceStatus = 1
  745. noMute = false
  746. } else {
  747. noMute = true
  748. }
  749. } else {
  750. noMute = !noMute
  751. }
  752. getApp().globalData.voiceProps.noMute = noMute
  753. this.socketSendMessage('changeVoiceStatus', {
  754. status: noMute ? 0 : 2,
  755. user: data.user
  756. })
  757. getApp().setVoiceProps({
  758. noMute
  759. })
  760. wx.showToast({
  761. title: `已${noMute ? '关闭' : '开启'}麦克风`,
  762. })
  763. }
  764. },
  765. closeMic() {
  766. getApp().globalData.voiceProps.noMute = true
  767. this.socketSendMessage('changeVoiceStatus', {
  768. status: 0,
  769. })
  770. getApp().setVoiceProps({
  771. noMute: true
  772. })
  773. },
  774. openMic() {
  775. getApp().globalData.voiceProps.noMute = false
  776. this.socketSendMessage('changeVoiceStatus', {
  777. status: 2,
  778. })
  779. getApp().setVoiceProps({
  780. noMute: false
  781. })
  782. },
  783. callPhone() {
  784. wx.makePhoneCall({
  785. phoneNumber: this.data.contractPhone,
  786. })
  787. this.setData({
  788. showContact: false
  789. })
  790. },
  791. /**
  792. * 用户点击右上角分享
  793. */
  794. onShareAppMessage: function (res) {
  795. let {
  796. id,
  797. newPicUrl
  798. } = this.data
  799. if (res.from === 'button') {
  800. this.setData({
  801. sendShare: false
  802. })
  803. return {
  804. title: '【好友推荐】一起来云逛吧',
  805. imageUrl: newPicUrl,
  806. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=true&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`,
  807. }
  808. } else {
  809. return {
  810. imageUrl: newPicUrl,
  811. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=false`,
  812. }
  813. }
  814. },
  815. /**
  816. * 生命周期函数--监听页面卸载
  817. */
  818. onUnload: function () {
  819. console.log('on onUnload')
  820. // this.socketSendMessage('stopCall', {})
  821. // this.stopCall()
  822. this.socketStop && this.socketStop()
  823. getApp().globalData.pusher = ''
  824. },
  825. cart(data) {
  826. this.setData({
  827. showCommodityCtrl: data.data
  828. })
  829. },
  830. share() {
  831. console.log('**********')
  832. // console.log(!!this.data.mamy)
  833. const companyName = `指房宝(杭州)科技有限公司`
  834. const vrLink = `/pages/webview/index`
  835. const img_url = this.data.newPicUrl || 'http://video.cgaii.com/new4dage/images/images/home_2_a.jpg'
  836. const shareImg = img_url
  837. this.count = this.count || 0
  838. if (this.data.many && this.data.shareStatus == 1) {
  839. //开启一起逛时候的分享
  840. 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}`)
  841. console.log(this.data.socketOptions)
  842. wx.navigateTo({
  843. 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}`,
  844. })
  845. } else {
  846. 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}`);
  847. wx.navigateTo({
  848. 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}`,
  849. })
  850. }
  851. },
  852. back(data) {
  853. if (data.sender !== 'h5') return;
  854. wx.switchTab({
  855. url: '/pages/index/index'
  856. })
  857. this.setData({
  858. showCommodityCtrl: false
  859. })
  860. },
  861. service() {
  862. this.setData({
  863. showContact: true,
  864. showCommodity: false,
  865. showCoupon: false
  866. })
  867. },
  868. invite(data) {
  869. if (data.sender !== 'h5') return;
  870. this.setData({
  871. sendShare: true,
  872. count: ++this.data.count
  873. })
  874. },
  875. coupon(data) {
  876. if (data.sender !== 'h5') return;
  877. this.setData({
  878. showContact: false,
  879. showCommodity: false,
  880. showCoupon: true
  881. })
  882. },
  883. liveGotoGood(ev) {
  884. let id = ev.currentTarget.dataset.item.goodsId
  885. wx.navigateTo({
  886. url: '/pages/goods/goods?id=' + id,
  887. })
  888. },
  889. gotoGoodsDOM(event) {
  890. this.gotoGoods(event.currentTarget.dataset.item.hotIdList[0])
  891. },
  892. gotoGoodsSocket(data) {
  893. this.gotoGoods(data.data)
  894. },
  895. gotoGoods(id) {
  896. console.log('---', id)
  897. this.socketSendMessage('clientSyncAction', {
  898. type: 'openTag',
  899. data: id
  900. })
  901. this.setData({
  902. showCommodity: false
  903. })
  904. this.joinUrl()
  905. },
  906. addCard(event) {
  907. wx.navigateTo({
  908. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=addCard',
  909. })
  910. },
  911. buyGoods(event) {
  912. wx.navigateTo({
  913. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=buyGoods',
  914. })
  915. },
  916. showCommodityFn() {
  917. this.setData({
  918. showCommodity: true,
  919. showContact: false,
  920. showCoupon: false
  921. })
  922. this.joinUrl()
  923. },
  924. hideComodity() {
  925. this.setData({
  926. showCommodity: false
  927. })
  928. this.joinUrl()
  929. },
  930. hideCoupon() {
  931. this.setData({
  932. showCoupon: !this.data.showCoupon
  933. })
  934. },
  935. async receive(ev) {
  936. let item = ev.target.dataset.item
  937. try {
  938. // wx.showToast({
  939. // title: '领取优惠卷',
  940. // })
  941. // return;
  942. if (item.hasReceived || item.number <= item.receiveNumber) return;
  943. let res = await util.request(api.CouponExchange, {
  944. couponId: item.id
  945. })
  946. if (res.code === 0) {
  947. wx.showToast({
  948. title: '已成功领取',
  949. success: () => {
  950. this.setData({
  951. showCoupon: false
  952. })
  953. wx.nextTick(() => {
  954. this.setData({
  955. coupons: this.data.coupons.map(citem => {
  956. return {
  957. ...citem,
  958. hasReceived: citem.id === item.id ? true : citem.hasReceived
  959. }
  960. }),
  961. showCoupon: true
  962. })
  963. })
  964. }
  965. })
  966. } else if (res.errno === 401) {
  967. getApp().setLoginProps(false)
  968. } else {
  969. wx.showToast({
  970. title: res.msg,
  971. })
  972. }
  973. } catch (e) {
  974. console.error(e)
  975. wx.showToast({
  976. icon: 'none',
  977. title: '领取失败',
  978. })
  979. }
  980. },
  981. async getCouponList(id) {
  982. const success = (res) => {
  983. this.setData({
  984. coupons: res.data.list.map(item => {
  985. item.typeMoney = item.typeMoney.toString()
  986. item.fontSize = item.typeMoney.length === 3 ? '90rpx' :
  987. item.typeMoney.length === 4 ? '70rpx' : '130rpx'
  988. return item
  989. })
  990. })
  991. this.loadConponSuccess = true
  992. this.readySendCouponCtrl()
  993. }
  994. let res = await util.request(api.BrandCouponList, {
  995. brandId: id,
  996. pageNum: 1,
  997. pageSize: 10000
  998. }, 'GET')
  999. console.log(res)
  1000. if (res.code === 0) {
  1001. success(res)
  1002. } else {
  1003. let res = await util.request(api.UNBrandCouponList, {
  1004. brandId: id,
  1005. pageNum: 1,
  1006. pageSize: 10000
  1007. }, 'GET')
  1008. success(res)
  1009. }
  1010. },
  1011. ready() {
  1012. this.wssSuccess = true
  1013. this.readySendCouponCtrl()
  1014. },
  1015. readySendCouponCtrl() {
  1016. if (this.wssSuccess && this.loadConponSuccess) {
  1017. this.loadConponSuccess = false
  1018. this.socketSendMessage('clientSyncAction', {
  1019. type: 'showCoupon',
  1020. data: this.data.coupons.length > 0
  1021. })
  1022. }
  1023. },
  1024. getBrand: function (id, code) {
  1025. this.getGoodsCount(code, id)
  1026. return;
  1027. },
  1028. getGoodsCount(code, id) {
  1029. util.request(api.GoodsNumCount, {
  1030. isDelete: 0,
  1031. isOnSale: 1,
  1032. brandId: id
  1033. }, 'GET')
  1034. .then(res => {
  1035. if (res.errno === 0) {
  1036. this.setData({
  1037. goodsCount: res.data
  1038. })
  1039. }
  1040. this.getCouponList(id)
  1041. })
  1042. },
  1043. getGoodsList(id, category_id) {
  1044. var that = this;
  1045. if (!(this.data.navList && this.data.navList.length)) {
  1046. that.navDatas = {}
  1047. let navDatas = this.data.navList = this.data.comtypes
  1048. // util.request(api.GoodsCategory, { id: category_id })
  1049. // .then(function (res) {
  1050. // if (res.errno == 0) {
  1051. // let navDatas = res.data.brotherCategory
  1052. // that.setData({
  1053. // navList: navDatas,
  1054. // currTypeId: category_id
  1055. // });
  1056. that.navDatas = {}
  1057. navDatas.forEach(item => {
  1058. util.request(api.GoodsList, {
  1059. brandId: id,
  1060. categoryId: item.category_id,
  1061. page: that.data.page,
  1062. size: that.data.size
  1063. })
  1064. .then(res => {
  1065. if (res.errno === 0) {
  1066. that.navDatas[item.category_id] = res.data.goodsList
  1067. }
  1068. })
  1069. })
  1070. // }
  1071. // })
  1072. }
  1073. if (that.navDatas[category_id]) {
  1074. if (!isIos) {
  1075. let showCommodity = that.data.showCommodity
  1076. that.setData({
  1077. showCommodity: false
  1078. })
  1079. setTimeout(() => {
  1080. wx.nextTick(() => {
  1081. that.setData({
  1082. goodsList: that.navDatas[category_id],
  1083. currTypeId: category_id,
  1084. showCommodity: showCommodity
  1085. });
  1086. })
  1087. }, 500)
  1088. } else {
  1089. that.setData({
  1090. goodsList: that.navDatas[category_id],
  1091. currTypeId: category_id,
  1092. });
  1093. }
  1094. } else {
  1095. console.error('诱惑去啦')
  1096. util.request(api.GoodsList, {
  1097. brandId: id,
  1098. categoryId: category_id,
  1099. page: that.data.page,
  1100. size: that.data.size
  1101. })
  1102. .then(function (res) {
  1103. if (res.errno === 0) {
  1104. that.setData({
  1105. goodsList: res.data.goodsList,
  1106. currTypeId: category_id
  1107. });
  1108. // this.data.navList
  1109. }
  1110. });
  1111. }
  1112. },
  1113. getBrandDetail: function (id, type, cb) {
  1114. util.request(api.BrandDetail, {
  1115. id: id,
  1116. type: type,
  1117. }).then((res) => {
  1118. let base = res.data.brand.sceneUrl
  1119. // let base = 'http://192.168.0.112:8080/shop.html?m=t-7Uqj9Fq&origin=fashilong'
  1120. if (res.errno === 0) {
  1121. let url = base + "&sid=" + id
  1122. this.setData({
  1123. id: id,
  1124. newPicUrl: res.data.brand.appListPicUrl,
  1125. sceneNum: res.data.brand.sceneNum,
  1126. canShow: res.data.brand.canShow,
  1127. contractPhone: res.data.brand.contractPhone
  1128. })
  1129. if (this.data.many === void 0) {
  1130. this.data.many = !!res.data.brand.canShow
  1131. }
  1132. this.setData({
  1133. // peopleCount: this.data.many ? manyCount : 5,
  1134. peopleCount: manyCount
  1135. })
  1136. if (!res.data.brand.canShow) {
  1137. this.role = 'customer'
  1138. } else if (!this.options.join) {
  1139. this.role = 'leader'
  1140. }
  1141. cb(url, urlToJson(url).m, )
  1142. }
  1143. });
  1144. },
  1145. selectType(ev) {
  1146. this.getGoodsList(this.options.id, ev.target.dataset.item.category_id)
  1147. },
  1148. hideCS() {
  1149. this.setData({
  1150. showCommodity: false,
  1151. showCoupon: false,
  1152. showContact: false
  1153. })
  1154. },
  1155. hideContact() {
  1156. this.setData({
  1157. showContact: false
  1158. })
  1159. },
  1160. calcShare() {
  1161. // this.exit()
  1162. this.setData({
  1163. sendShare: false
  1164. })
  1165. },
  1166. contactKf() {
  1167. let keys = Object.keys(this.navDatas)
  1168. let goodsId = this.navDatas[keys[0]][0].id
  1169. let user = wx.getStorageSync('userinfoDetail')
  1170. util.request(api.AddTalkCount, {
  1171. goodsId,
  1172. viewId: user && user.userId || '',
  1173. sceneNum: this.data.sceneNum
  1174. }, 'get')
  1175. this.hideAlert && this.hideAlert()
  1176. this.hideContact && this.hideContact()
  1177. },
  1178. onHide() {
  1179. this.socketSendMessage('changeOnlineStatus', {
  1180. status: 0
  1181. })
  1182. this.pauseVideo = true
  1183. this.joinUrl()
  1184. }
  1185. }