socket.js 33 KB

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