socket.js 33 KB

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