socket.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  1. const {
  2. io
  3. } = require('./socket.io-v4.msgpack.js');
  4. var user = require('./services/user.js');
  5. const api = require('/config/api.js');
  6. const util = require('/utils/util.js');
  7. const UNLOGIN = 'NO_LOGIN'
  8. const btoa = require('./utils/btoa')
  9. const manyCount = 50
  10. import remote from './config.js'
  11. var app = getApp();
  12. var isIos = false
  13. wx.getSystemInfo({
  14. success: function (res) {
  15. isIos = res.platform == "ios"
  16. }
  17. })
  18. const debounce = (fn, wait) => {
  19. let callback = fn;
  20. let timerId = null;
  21. function debounced() {
  22. let context = this;
  23. let args = arguments;
  24. clearTimeout(timerId);
  25. timerId = setTimeout(function () {
  26. callback.apply(context, args);
  27. }, wait);
  28. }
  29. return debounced;
  30. }
  31. let urlToJson = (url = window.location.href) => { // 箭头函数默认传值为当前页面url
  32. let obj = {},
  33. index = url.indexOf('?'), // 看url有没有参数
  34. params = url.substr(index + 1); // 截取url参数部分 id = 1 & type = 2
  35. if (index != -1) { // 有参数时
  36. let parr = params.split('&'); // 将参数分割成数组 ["id = 1 ", " type = 2"]
  37. for (let i of parr) { // 遍历数组
  38. let arr = i.split('='); // 1) i id = 1 arr = [id, 1] 2)i type = 2 arr = [type, 2]
  39. obj[arr[0]] = arr[1]; // obj[arr[0]] = id, obj.id = 1 obj[arr[0]] = type, obj.type = 2
  40. }
  41. }
  42. return obj;
  43. }
  44. export default {
  45. joinUrl() {
  46. const url = true ? this.data.url.replace('shop.html', 'test-shop.html') : this.data.url;
  47. let options = {
  48. API_BASE_URL: api.API_BASE_URL,
  49. "url": url,
  50. // "url": 'http://192.168.0.112:8080',
  51. "reload": this.data.reload,
  52. "token": wx.getStorageSync('token'),
  53. "code": this.mcode,
  54. "brandId": this.options.id,
  55. "open": this.data.showCommodity,
  56. "pauseVideo": this.pauseVideo,
  57. "bottom": this.data.bottom || 0,
  58. socket: {
  59. socketHost: remote.socketHost,
  60. path: '/fsl-node',
  61. options: {
  62. ...this.data.socketOptions,
  63. // nickname: encodeURI(encodeURI(this.data.socketOptions.nickname))
  64. nickname: encodeURIComponent(encodeURIComponent(this.data.socketOptions.nickname))
  65. }
  66. }
  67. }
  68. // let base = 'http://127.0.0.1:5500/index.html'
  69. // let base = remote.viewHost + '/shop-container/shop.html'
  70. let sponsor = !!this.data.canShow
  71. if (this.data.join && !this.options.join) {
  72. sponsor = false
  73. }
  74. // 33是从我的房间出来的
  75. if (Number(this.data.type) === 33) {
  76. sponsor = true;
  77. }
  78. // debugger
  79. // remote.viewHost
  80. let hostUrl
  81. if (options.url.indexOf('www.4dkankan.com') != -1) {
  82. hostUrl = 'https://www.4dkankan.com/shop-container-zfb/'
  83. } else if (options.url.indexOf('test.4dkankan.com') != -1) {
  84. hostUrl = 'https://test.4dkankan.com/shop-container-zfb/'
  85. } else {
  86. // hostUrl = 'https://zfb.4dkankan.com/shop-container/'
  87. // hostUrl = remote.viewHost + '/shop-container/'
  88. hostUrl = remote.viewHost + '/shop-container-v4/'
  89. }
  90. // let base = remote.viewHost + '/shop-container/fashilong.html?env=' + remote.env + '&sponsor=' + sponsor + '&many=' + this.data.many
  91. let base = hostUrl + 'fashilong.html?time=' + Date.now() + '&env=' + remote.env + '&sponsor=' + sponsor + '&many=' + this.data.many
  92. // let base = remote.viewHost + '/shop.html'
  93. this.data.reload = false
  94. this.data.showCommodity = false
  95. options.url = options.url + '&vlog';
  96. if (!this.data.webviewUrl) {
  97. console.log(base)
  98. this.setData({
  99. 'webviewUrl': base + '#' + JSON.stringify(options)
  100. })
  101. } else {
  102. this.socketSendMessage('clientSyncAction', {
  103. sender: 'h5',
  104. type: 'hashChange',
  105. data: options
  106. })
  107. }
  108. },
  109. onShow() {
  110. this.setData({
  111. isIos,
  112. showComtypesAllTab: false
  113. })
  114. if (this.socketSendMessage) {
  115. this.pauseVideo = false
  116. this.joinUrl()
  117. this.socketSendMessage('changeOnlineStatus', {
  118. status: true
  119. })
  120. }
  121. },
  122. changeShowComtypesAllTab(ev) {
  123. this.setData({
  124. showCommodity: false
  125. })
  126. setTimeout(() => {
  127. this.setData({
  128. showComtypesAllTab: ev.currentTarget.dataset.show,
  129. showCommodity: true
  130. })
  131. }, 100)
  132. },
  133. async authorizeRecord() {
  134. let isAuth = await new Promise((r, j) => {
  135. wx.authorize({
  136. scope: 'scope.record',
  137. success: () => r(true),
  138. fail: () => r(false)
  139. })
  140. })
  141. if (isAuth) return true
  142. let res = await new Promise(r => {
  143. wx.showModal({
  144. title: '提示',
  145. content: '您未授权录音,说话功能将无法使用',
  146. showCancel: true,
  147. confirmText: "授权",
  148. confirmColor: "#52a2d8",
  149. success: res => r(res),
  150. fail: () => r(false)
  151. })
  152. })
  153. if (!res || res.cancel) return;
  154. isAuth = await new Promise((r) => {
  155. wx.openSetting({
  156. success: res => r(res.authSetting['scope.record']),
  157. fail: () => r(false)
  158. })
  159. })
  160. return isAuth
  161. },
  162. // 获取录音权限状态
  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: true,
  313. userLimitNum: capacities
  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: true
  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. async newRoom(data) {
  631. if (data.roomId) return;
  632. this.stopCall()
  633. getApp().globalData.rtcParams = []
  634. getApp().globalData.pusher = ''
  635. if (this.data.join && !this.options.join) {
  636. wx.switchTab({
  637. url: '/pages/index/index',
  638. })
  639. return;
  640. }
  641. this.role = this.data.canShow ? 'leader' : 'customer'
  642. let options = await this.getSocketOptions(this.mcode)
  643. this.socketSendMessage('clientSyncAction', {
  644. type: 'newRoom',
  645. data: options
  646. })
  647. setTimeout(async () => {
  648. this.wssSuccess = false
  649. this.socketStop && this.socketStop()
  650. this.data.many = !!this.data.canShow
  651. this.setData({
  652. // peopleCount: this.data.many ? manyCount : 5
  653. peopleCount: manyCount
  654. })
  655. let base = this.base
  656. let socketOptions = await this.socketStart({
  657. options
  658. })
  659. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  660. this.base = base
  661. this.setData({
  662. url,
  663. socketOptions,
  664. })
  665. this.joinUrl()
  666. this.setData({
  667. socketOptions
  668. })
  669. this.loadConponSuccess = true
  670. this.readySendCouponCtrl()
  671. }, 300)
  672. },
  673. async exit() {
  674. // this.stopCall()
  675. getApp().globalData.rtcParams = []
  676. getApp().globalData.pusher = ''
  677. this.socketStop && this.socketStop()
  678. this.role = 'leader'
  679. let base = this.base
  680. let socketOptions = await this.socketStart({
  681. sceneId: this.mcode
  682. })
  683. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  684. this.base = base
  685. wx.nextTick(() => {
  686. setTimeout(() => {
  687. this.setData({
  688. url,
  689. loadUrl: true,
  690. socketOptions,
  691. showCommodityCtrl: false,
  692. hideWebView: false,
  693. reload: true
  694. })
  695. this.joinUrl()
  696. }, 500)
  697. })
  698. },
  699. clearDebuger() {
  700. this.setData({
  701. debugerInfo: ''
  702. })
  703. },
  704. async mic({
  705. data
  706. }) {
  707. if (Number(data.user.isAllowMic) === 1) {
  708. let noMute = getApp().globalData.voiceProps.noMute
  709. // debugger
  710. // noMute true 静音
  711. // enableTalk false 静音
  712. // if (!!getApp().globalData.voiceProps.force === !!noMute)
  713. // return
  714. // if (!getApp().globalData.voiceProps.force && (!this.data.socketOptions.voiceStatus || noMute)) return;
  715. if (!this.data.socketOptions.voiceStatus) {
  716. let voiceStatus = await this.authorizeRecord()
  717. if (voiceStatus) {
  718. this.data.socketOptions.voiceStatus = 1
  719. noMute = false
  720. } else {
  721. noMute = true
  722. }
  723. } else {
  724. noMute = !noMute
  725. }
  726. getApp().globalData.voiceProps.noMute = noMute
  727. this.socketSendMessage('changeVoiceStatus', {
  728. status: noMute ? 0 : 2,
  729. user: data.user
  730. })
  731. getApp().setVoiceProps({
  732. noMute
  733. })
  734. wx.showToast({
  735. title: `已${noMute ? '关闭' : '开启'}麦克风`,
  736. })
  737. }
  738. },
  739. callPhone() {
  740. wx.makePhoneCall({
  741. phoneNumber: this.data.contractPhone,
  742. })
  743. this.setData({
  744. showContact: false
  745. })
  746. },
  747. /**
  748. * 用户点击右上角分享
  749. */
  750. onShareAppMessage: function (res) {
  751. let {
  752. id,
  753. newPicUrl
  754. } = this.data
  755. if (res.from === 'button') {
  756. this.setData({
  757. sendShare: false
  758. })
  759. return {
  760. title: '【好友推荐】一起来云逛吧',
  761. imageUrl: newPicUrl,
  762. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=true&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`,
  763. }
  764. } else {
  765. return {
  766. imageUrl: newPicUrl,
  767. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=false`,
  768. }
  769. }
  770. },
  771. /**
  772. * 生命周期函数--监听页面卸载
  773. */
  774. onUnload: function () {
  775. console.log('on onUnload')
  776. // this.socketSendMessage('stopCall', {})
  777. // this.stopCall()
  778. this.socketStop()
  779. getApp().globalData.pusher = ''
  780. },
  781. cart(data) {
  782. this.setData({
  783. showCommodityCtrl: data.data
  784. })
  785. },
  786. share() {
  787. console.log('**********')
  788. // console.log(!!this.data.mamy)
  789. const companyName = `指房宝(杭州)科技有限公司`
  790. const vrLink = `/pages/webview/index`
  791. const img_url = this.data.newPicUrl || 'http://video.cgaii.com/new4dage/images/images/home_2_a.jpg'
  792. const shareImg = img_url
  793. this.count = this.count || 0
  794. if (this.data.many && this.data.shareStatus == 1) {
  795. //开启一起逛时候的分享
  796. 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}`)
  797. console.log(this.data.socketOptions)
  798. wx.navigateTo({
  799. 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}`,
  800. })
  801. } else {
  802. 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}`);
  803. wx.navigateTo({
  804. 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}`,
  805. })
  806. }
  807. },
  808. back(data) {
  809. if (data.sender !== 'h5') return;
  810. wx.switchTab({
  811. url: '/pages/index/index'
  812. })
  813. this.setData({
  814. showCommodityCtrl: false
  815. })
  816. },
  817. service() {
  818. this.setData({
  819. showContact: true,
  820. showCommodity: false,
  821. showCoupon: false
  822. })
  823. },
  824. invite(data) {
  825. if (data.sender !== 'h5') return;
  826. this.setData({
  827. sendShare: true,
  828. count: ++this.data.count
  829. })
  830. },
  831. coupon(data) {
  832. if (data.sender !== 'h5') return;
  833. this.setData({
  834. showContact: false,
  835. showCommodity: false,
  836. showCoupon: true
  837. })
  838. },
  839. liveGotoGood(ev) {
  840. let id = ev.currentTarget.dataset.item.goodsId
  841. wx.navigateTo({
  842. url: '/pages/goods/goods?id=' + id,
  843. })
  844. },
  845. gotoGoodsDOM(event) {
  846. this.gotoGoods(event.currentTarget.dataset.item.hotIdList[0])
  847. },
  848. gotoGoodsSocket(data) {
  849. this.gotoGoods(data.data)
  850. },
  851. gotoGoods(id) {
  852. console.log('---', id)
  853. this.socketSendMessage('clientSyncAction', {
  854. type: 'openTag',
  855. data: id
  856. })
  857. this.setData({
  858. showCommodity: false
  859. })
  860. this.joinUrl()
  861. },
  862. addCard(event) {
  863. wx.navigateTo({
  864. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=addCard',
  865. })
  866. },
  867. buyGoods(event) {
  868. wx.navigateTo({
  869. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=buyGoods',
  870. })
  871. },
  872. showCommodityFn() {
  873. this.setData({
  874. showCommodity: true,
  875. showContact: false,
  876. showCoupon: false
  877. })
  878. this.joinUrl()
  879. },
  880. hideComodity() {
  881. this.setData({
  882. showCommodity: false
  883. })
  884. this.joinUrl()
  885. },
  886. hideCoupon() {
  887. this.setData({
  888. showCoupon: !this.data.showCoupon
  889. })
  890. },
  891. async receive(ev) {
  892. let item = ev.target.dataset.item
  893. try {
  894. // wx.showToast({
  895. // title: '领取优惠卷',
  896. // })
  897. // return;
  898. if (item.hasReceived || item.number <= item.receiveNumber) return;
  899. let res = await util.request(api.CouponExchange, {
  900. couponId: item.id
  901. })
  902. if (res.code === 0) {
  903. wx.showToast({
  904. title: '已成功领取',
  905. success: () => {
  906. this.setData({
  907. showCoupon: false
  908. })
  909. wx.nextTick(() => {
  910. this.setData({
  911. coupons: this.data.coupons.map(citem => {
  912. return {
  913. ...citem,
  914. hasReceived: citem.id === item.id ? true : citem.hasReceived
  915. }
  916. }),
  917. showCoupon: true
  918. })
  919. })
  920. }
  921. })
  922. } else if (res.errno === 401) {
  923. getApp().setLoginProps(false)
  924. } else {
  925. wx.showToast({
  926. title: res.msg,
  927. })
  928. }
  929. } catch (e) {
  930. console.error(e)
  931. wx.showToast({
  932. icon: 'none',
  933. title: '领取失败',
  934. })
  935. }
  936. },
  937. async getCouponList(id) {
  938. const success = (res) => {
  939. this.setData({
  940. coupons: res.data.list.map(item => {
  941. item.typeMoney = item.typeMoney.toString()
  942. item.fontSize = item.typeMoney.length === 3 ? '90rpx' :
  943. item.typeMoney.length === 4 ? '70rpx' : '130rpx'
  944. return item
  945. })
  946. })
  947. this.loadConponSuccess = true
  948. this.readySendCouponCtrl()
  949. }
  950. let res = await util.request(api.BrandCouponList, {
  951. brandId: id,
  952. pageNum: 1,
  953. pageSize: 10000
  954. }, 'GET')
  955. console.log(res)
  956. if (res.code === 0) {
  957. success(res)
  958. } else {
  959. let res = await util.request(api.UNBrandCouponList, {
  960. brandId: id,
  961. pageNum: 1,
  962. pageSize: 10000
  963. }, 'GET')
  964. success(res)
  965. }
  966. },
  967. ready() {
  968. this.wssSuccess = true
  969. this.readySendCouponCtrl()
  970. },
  971. readySendCouponCtrl() {
  972. if (this.wssSuccess && this.loadConponSuccess) {
  973. this.loadConponSuccess = false
  974. this.socketSendMessage('clientSyncAction', {
  975. type: 'showCoupon',
  976. data: this.data.coupons.length > 0
  977. })
  978. }
  979. },
  980. getBrand: function (id, code) {
  981. this.getGoodsCount(code, id)
  982. return;
  983. let that = this;
  984. util.request(api.SueneCategory, {
  985. sceneNum: code
  986. }, 'GET').then(function (res) {
  987. if (res.code === 0) {
  988. const comtypes = res.list.map(item => {
  989. item.width = (item.name.length + (item.num.toString().length / 2) + 2) * 16
  990. return {
  991. ...item
  992. }
  993. })
  994. that.setData({
  995. comWidth: comtypes.reduce((a, b) => a + b.width + 10, 0),
  996. comtypes,
  997. thumComtypes: (!isIos && comtypes.length > 3) ? comtypes.slice(0, 3) : null,
  998. currTypeId: comtypes.length > 0 && comtypes[0].category_id
  999. });
  1000. wx.showToast({
  1001. title: 'currTypeId' + that.data.currTypeId.length,
  1002. })
  1003. that.data.currTypeId && that.getGoodsList(id, that.data.currTypeId);
  1004. }
  1005. });
  1006. },
  1007. getGoodsCount(code, id) {
  1008. util.request(api.GoodsNumCount, {
  1009. isDelete: 0,
  1010. isOnSale: 1,
  1011. brandId: id
  1012. }, 'GET')
  1013. .then(res => {
  1014. if (res.errno === 0) {
  1015. this.setData({
  1016. goodsCount: res.data
  1017. })
  1018. }
  1019. this.getCouponList(id)
  1020. })
  1021. },
  1022. getGoodsList(id, category_id) {
  1023. var that = this;
  1024. if (!(this.data.navList && this.data.navList.length)) {
  1025. that.navDatas = {}
  1026. let navDatas = this.data.navList = this.data.comtypes
  1027. // util.request(api.GoodsCategory, { id: category_id })
  1028. // .then(function (res) {
  1029. // if (res.errno == 0) {
  1030. // let navDatas = res.data.brotherCategory
  1031. // that.setData({
  1032. // navList: navDatas,
  1033. // currTypeId: category_id
  1034. // });
  1035. that.navDatas = {}
  1036. navDatas.forEach(item => {
  1037. util.request(api.GoodsList, {
  1038. brandId: id,
  1039. categoryId: item.category_id,
  1040. page: that.data.page,
  1041. size: that.data.size
  1042. })
  1043. .then(res => {
  1044. if (res.errno === 0) {
  1045. that.navDatas[item.category_id] = res.data.goodsList
  1046. }
  1047. })
  1048. })
  1049. // }
  1050. // })
  1051. }
  1052. if (that.navDatas[category_id]) {
  1053. if (!isIos) {
  1054. let showCommodity = that.data.showCommodity
  1055. that.setData({
  1056. showCommodity: false
  1057. })
  1058. setTimeout(() => {
  1059. wx.nextTick(() => {
  1060. that.setData({
  1061. goodsList: that.navDatas[category_id],
  1062. currTypeId: category_id,
  1063. showCommodity: showCommodity
  1064. });
  1065. })
  1066. }, 500)
  1067. } else {
  1068. that.setData({
  1069. goodsList: that.navDatas[category_id],
  1070. currTypeId: category_id,
  1071. });
  1072. }
  1073. } else {
  1074. console.error('诱惑去啦')
  1075. util.request(api.GoodsList, {
  1076. brandId: id,
  1077. categoryId: category_id,
  1078. page: that.data.page,
  1079. size: that.data.size
  1080. })
  1081. .then(function (res) {
  1082. if (res.errno === 0) {
  1083. that.setData({
  1084. goodsList: res.data.goodsList,
  1085. currTypeId: category_id
  1086. });
  1087. // this.data.navList
  1088. }
  1089. });
  1090. }
  1091. },
  1092. getBrandDetail: function (id, type, cb) {
  1093. util.request(api.BrandDetail, {
  1094. id: id,
  1095. type: type,
  1096. }).then((res) => {
  1097. let base = res.data.brand.sceneUrl
  1098. // let base = 'http://192.168.0.112:8080/shop.html?m=t-7Uqj9Fq&origin=fashilong'
  1099. if (res.errno === 0) {
  1100. let url = base + "&sid=" + id
  1101. this.setData({
  1102. id: id,
  1103. newPicUrl: res.data.brand.appListPicUrl,
  1104. sceneNum: res.data.brand.sceneNum,
  1105. canShow: res.data.brand.canShow,
  1106. contractPhone: res.data.brand.contractPhone
  1107. })
  1108. if (this.data.many === void 0) {
  1109. this.data.many = !!res.data.brand.canShow
  1110. }
  1111. this.setData({
  1112. // peopleCount: this.data.many ? manyCount : 5,
  1113. peopleCount: manyCount
  1114. })
  1115. if (!res.data.brand.canShow) {
  1116. this.role = 'customer'
  1117. } else if (!this.options.join) {
  1118. this.role = 'leader'
  1119. }
  1120. cb(url, urlToJson(url).m, )
  1121. }
  1122. });
  1123. },
  1124. selectType(ev) {
  1125. this.getGoodsList(this.options.id, ev.target.dataset.item.category_id)
  1126. },
  1127. hideCS() {
  1128. this.setData({
  1129. showCommodity: false,
  1130. showCoupon: false,
  1131. showContact: false
  1132. })
  1133. },
  1134. hideContact() {
  1135. this.setData({
  1136. showContact: false
  1137. })
  1138. },
  1139. calcShare() {
  1140. // this.exit()
  1141. this.setData({
  1142. sendShare: false
  1143. })
  1144. },
  1145. contactKf() {
  1146. let keys = Object.keys(this.navDatas)
  1147. let goodsId = this.navDatas[keys[0]][0].id
  1148. let user = wx.getStorageSync('userinfoDetail')
  1149. util.request(api.AddTalkCount, {
  1150. goodsId,
  1151. viewId: user && user.userId || '',
  1152. sceneNum: this.data.sceneNum
  1153. }, 'get')
  1154. this.hideAlert && this.hideAlert()
  1155. this.hideContact && this.hideContact()
  1156. },
  1157. onHide() {
  1158. this.socketSendMessage('changeOnlineStatus', {
  1159. status: false
  1160. })
  1161. this.pauseVideo = true
  1162. this.joinUrl()
  1163. }
  1164. }