socket.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  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
  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 newRoom(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 result = await util.request(api.exitRoom, {
  678. businessId: roomId
  679. }, 'POST', 'application/json');
  680. this.socketSendMessage('stopCall', {
  681. from: 2
  682. })
  683. this.stopCall();
  684. this.socketStop();
  685. wx.redirectTo({
  686. url: '/pages/roomManger/roomManger',
  687. });
  688. },
  689. async exit() {
  690. // this.stopCall()
  691. getApp().globalData.rtcParams = []
  692. getApp().globalData.pusher = ''
  693. this.socketStop && this.socketStop()
  694. this.role = 'leader'
  695. let base = this.base
  696. let socketOptions = await this.socketStart({
  697. sceneId: this.mcode
  698. })
  699. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  700. this.base = base
  701. wx.nextTick(() => {
  702. setTimeout(() => {
  703. this.setData({
  704. url,
  705. loadUrl: true,
  706. socketOptions,
  707. showCommodityCtrl: false,
  708. hideWebView: false,
  709. reload: true
  710. })
  711. this.joinUrl()
  712. }, 500)
  713. })
  714. },
  715. clearDebuger() {
  716. this.setData({
  717. debugerInfo: ''
  718. })
  719. },
  720. async mic({
  721. data
  722. }) {
  723. if (Number(data.user.isAllowMic) === 1) {
  724. let noMute = getApp().globalData.voiceProps.noMute
  725. // debugger
  726. // noMute true 静音
  727. // enableTalk false 静音
  728. // if (!!getApp().globalData.voiceProps.force === !!noMute)
  729. // return
  730. // if (!getApp().globalData.voiceProps.force && (!this.data.socketOptions.voiceStatus || noMute)) return;
  731. if (!this.data.socketOptions.voiceStatus) {
  732. let voiceStatus = await this.authorizeRecord()
  733. if (voiceStatus) {
  734. this.data.socketOptions.voiceStatus = 1
  735. noMute = false
  736. } else {
  737. noMute = true
  738. }
  739. } else {
  740. noMute = !noMute
  741. }
  742. getApp().globalData.voiceProps.noMute = noMute
  743. this.socketSendMessage('changeVoiceStatus', {
  744. status: noMute ? 0 : 2,
  745. user: data.user
  746. })
  747. getApp().setVoiceProps({
  748. noMute
  749. })
  750. wx.showToast({
  751. title: `已${noMute ? '关闭' : '开启'}麦克风`,
  752. })
  753. }
  754. },
  755. closeMic() {
  756. getApp().globalData.voiceProps.noMute = true
  757. this.socketSendMessage('changeVoiceStatus', {
  758. status: 0,
  759. })
  760. getApp().setVoiceProps({
  761. noMute: true
  762. })
  763. },
  764. openMic() {
  765. getApp().globalData.voiceProps.noMute = false
  766. this.socketSendMessage('changeVoiceStatus', {
  767. status: 2,
  768. })
  769. getApp().setVoiceProps({
  770. noMute: false
  771. })
  772. },
  773. callPhone() {
  774. wx.makePhoneCall({
  775. phoneNumber: this.data.contractPhone,
  776. })
  777. this.setData({
  778. showContact: false
  779. })
  780. },
  781. /**
  782. * 用户点击右上角分享
  783. */
  784. onShareAppMessage: function (res) {
  785. let {
  786. id,
  787. newPicUrl
  788. } = this.data
  789. if (res.from === 'button') {
  790. this.setData({
  791. sendShare: false
  792. })
  793. return {
  794. title: '【好友推荐】一起来云逛吧',
  795. imageUrl: newPicUrl,
  796. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=true&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`,
  797. }
  798. } else {
  799. return {
  800. imageUrl: newPicUrl,
  801. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=false`,
  802. }
  803. }
  804. },
  805. /**
  806. * 生命周期函数--监听页面卸载
  807. */
  808. onUnload: function () {
  809. console.log('on onUnload')
  810. // this.socketSendMessage('stopCall', {})
  811. // this.stopCall()
  812. this.socketStop && this.socketStop()
  813. getApp().globalData.pusher = ''
  814. },
  815. cart(data) {
  816. this.setData({
  817. showCommodityCtrl: data.data
  818. })
  819. },
  820. share() {
  821. console.log('**********')
  822. // console.log(!!this.data.mamy)
  823. const companyName = `指房宝(杭州)科技有限公司`
  824. const vrLink = `/pages/webview/index`
  825. const img_url = this.data.newPicUrl || 'http://video.cgaii.com/new4dage/images/images/home_2_a.jpg'
  826. const shareImg = img_url
  827. this.count = this.count || 0
  828. if (this.data.many && this.data.shareStatus == 1) {
  829. //开启一起逛时候的分享
  830. 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}`)
  831. console.log(this.data.socketOptions)
  832. wx.navigateTo({
  833. 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}`,
  834. })
  835. } else {
  836. 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}`);
  837. wx.navigateTo({
  838. 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}`,
  839. })
  840. }
  841. },
  842. back(data) {
  843. if (data.sender !== 'h5') return;
  844. wx.switchTab({
  845. url: '/pages/index/index'
  846. })
  847. this.setData({
  848. showCommodityCtrl: false
  849. })
  850. },
  851. service() {
  852. this.setData({
  853. showContact: true,
  854. showCommodity: false,
  855. showCoupon: false
  856. })
  857. },
  858. invite(data) {
  859. if (data.sender !== 'h5') return;
  860. this.setData({
  861. sendShare: true,
  862. count: ++this.data.count
  863. })
  864. },
  865. coupon(data) {
  866. if (data.sender !== 'h5') return;
  867. this.setData({
  868. showContact: false,
  869. showCommodity: false,
  870. showCoupon: true
  871. })
  872. },
  873. liveGotoGood(ev) {
  874. let id = ev.currentTarget.dataset.item.goodsId
  875. wx.navigateTo({
  876. url: '/pages/goods/goods?id=' + id,
  877. })
  878. },
  879. gotoGoodsDOM(event) {
  880. this.gotoGoods(event.currentTarget.dataset.item.hotIdList[0])
  881. },
  882. gotoGoodsSocket(data) {
  883. this.gotoGoods(data.data)
  884. },
  885. gotoGoods(id) {
  886. console.log('---', id)
  887. this.socketSendMessage('clientSyncAction', {
  888. type: 'openTag',
  889. data: id
  890. })
  891. this.setData({
  892. showCommodity: false
  893. })
  894. this.joinUrl()
  895. },
  896. addCard(event) {
  897. wx.navigateTo({
  898. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=addCard',
  899. })
  900. },
  901. buyGoods(event) {
  902. wx.navigateTo({
  903. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=buyGoods',
  904. })
  905. },
  906. showCommodityFn() {
  907. this.setData({
  908. showCommodity: true,
  909. showContact: false,
  910. showCoupon: false
  911. })
  912. this.joinUrl()
  913. },
  914. hideComodity() {
  915. this.setData({
  916. showCommodity: false
  917. })
  918. this.joinUrl()
  919. },
  920. hideCoupon() {
  921. this.setData({
  922. showCoupon: !this.data.showCoupon
  923. })
  924. },
  925. async receive(ev) {
  926. let item = ev.target.dataset.item
  927. try {
  928. // wx.showToast({
  929. // title: '领取优惠卷',
  930. // })
  931. // return;
  932. if (item.hasReceived || item.number <= item.receiveNumber) return;
  933. let res = await util.request(api.CouponExchange, {
  934. couponId: item.id
  935. })
  936. if (res.code === 0) {
  937. wx.showToast({
  938. title: '已成功领取',
  939. success: () => {
  940. this.setData({
  941. showCoupon: false
  942. })
  943. wx.nextTick(() => {
  944. this.setData({
  945. coupons: this.data.coupons.map(citem => {
  946. return {
  947. ...citem,
  948. hasReceived: citem.id === item.id ? true : citem.hasReceived
  949. }
  950. }),
  951. showCoupon: true
  952. })
  953. })
  954. }
  955. })
  956. } else if (res.errno === 401) {
  957. getApp().setLoginProps(false)
  958. } else {
  959. wx.showToast({
  960. title: res.msg,
  961. })
  962. }
  963. } catch (e) {
  964. console.error(e)
  965. wx.showToast({
  966. icon: 'none',
  967. title: '领取失败',
  968. })
  969. }
  970. },
  971. async getCouponList(id) {
  972. const success = (res) => {
  973. this.setData({
  974. coupons: res.data.list.map(item => {
  975. item.typeMoney = item.typeMoney.toString()
  976. item.fontSize = item.typeMoney.length === 3 ? '90rpx' :
  977. item.typeMoney.length === 4 ? '70rpx' : '130rpx'
  978. return item
  979. })
  980. })
  981. this.loadConponSuccess = true
  982. this.readySendCouponCtrl()
  983. }
  984. let res = await util.request(api.BrandCouponList, {
  985. brandId: id,
  986. pageNum: 1,
  987. pageSize: 10000
  988. }, 'GET')
  989. console.log(res)
  990. if (res.code === 0) {
  991. success(res)
  992. } else {
  993. let res = await util.request(api.UNBrandCouponList, {
  994. brandId: id,
  995. pageNum: 1,
  996. pageSize: 10000
  997. }, 'GET')
  998. success(res)
  999. }
  1000. },
  1001. ready() {
  1002. this.wssSuccess = true
  1003. this.readySendCouponCtrl()
  1004. },
  1005. readySendCouponCtrl() {
  1006. if (this.wssSuccess && this.loadConponSuccess) {
  1007. this.loadConponSuccess = false
  1008. this.socketSendMessage('clientSyncAction', {
  1009. type: 'showCoupon',
  1010. data: this.data.coupons.length > 0
  1011. })
  1012. }
  1013. },
  1014. getBrand: function (id, code) {
  1015. this.getGoodsCount(code, id)
  1016. return;
  1017. },
  1018. getGoodsCount(code, id) {
  1019. util.request(api.GoodsNumCount, {
  1020. isDelete: 0,
  1021. isOnSale: 1,
  1022. brandId: id
  1023. }, 'GET')
  1024. .then(res => {
  1025. if (res.errno === 0) {
  1026. this.setData({
  1027. goodsCount: res.data
  1028. })
  1029. }
  1030. this.getCouponList(id)
  1031. })
  1032. },
  1033. getGoodsList(id, category_id) {
  1034. var that = this;
  1035. if (!(this.data.navList && this.data.navList.length)) {
  1036. that.navDatas = {}
  1037. let navDatas = this.data.navList = this.data.comtypes
  1038. // util.request(api.GoodsCategory, { id: category_id })
  1039. // .then(function (res) {
  1040. // if (res.errno == 0) {
  1041. // let navDatas = res.data.brotherCategory
  1042. // that.setData({
  1043. // navList: navDatas,
  1044. // currTypeId: category_id
  1045. // });
  1046. that.navDatas = {}
  1047. navDatas.forEach(item => {
  1048. util.request(api.GoodsList, {
  1049. brandId: id,
  1050. categoryId: item.category_id,
  1051. page: that.data.page,
  1052. size: that.data.size
  1053. })
  1054. .then(res => {
  1055. if (res.errno === 0) {
  1056. that.navDatas[item.category_id] = res.data.goodsList
  1057. }
  1058. })
  1059. })
  1060. // }
  1061. // })
  1062. }
  1063. if (that.navDatas[category_id]) {
  1064. if (!isIos) {
  1065. let showCommodity = that.data.showCommodity
  1066. that.setData({
  1067. showCommodity: false
  1068. })
  1069. setTimeout(() => {
  1070. wx.nextTick(() => {
  1071. that.setData({
  1072. goodsList: that.navDatas[category_id],
  1073. currTypeId: category_id,
  1074. showCommodity: showCommodity
  1075. });
  1076. })
  1077. }, 500)
  1078. } else {
  1079. that.setData({
  1080. goodsList: that.navDatas[category_id],
  1081. currTypeId: category_id,
  1082. });
  1083. }
  1084. } else {
  1085. console.error('诱惑去啦')
  1086. util.request(api.GoodsList, {
  1087. brandId: id,
  1088. categoryId: category_id,
  1089. page: that.data.page,
  1090. size: that.data.size
  1091. })
  1092. .then(function (res) {
  1093. if (res.errno === 0) {
  1094. that.setData({
  1095. goodsList: res.data.goodsList,
  1096. currTypeId: category_id
  1097. });
  1098. // this.data.navList
  1099. }
  1100. });
  1101. }
  1102. },
  1103. getBrandDetail: function (id, type, cb) {
  1104. util.request(api.BrandDetail, {
  1105. id: id,
  1106. type: type,
  1107. }).then((res) => {
  1108. let base = res.data.brand.sceneUrl
  1109. // let base = 'http://192.168.0.112:8080/shop.html?m=t-7Uqj9Fq&origin=fashilong'
  1110. if (res.errno === 0) {
  1111. let url = base + "&sid=" + id
  1112. this.setData({
  1113. id: id,
  1114. newPicUrl: res.data.brand.appListPicUrl,
  1115. sceneNum: res.data.brand.sceneNum,
  1116. canShow: res.data.brand.canShow,
  1117. contractPhone: res.data.brand.contractPhone
  1118. })
  1119. if (this.data.many === void 0) {
  1120. this.data.many = !!res.data.brand.canShow
  1121. }
  1122. this.setData({
  1123. // peopleCount: this.data.many ? manyCount : 5,
  1124. peopleCount: manyCount
  1125. })
  1126. if (!res.data.brand.canShow) {
  1127. this.role = 'customer'
  1128. } else if (!this.options.join) {
  1129. this.role = 'leader'
  1130. }
  1131. cb(url, urlToJson(url).m, )
  1132. }
  1133. });
  1134. },
  1135. selectType(ev) {
  1136. this.getGoodsList(this.options.id, ev.target.dataset.item.category_id)
  1137. },
  1138. hideCS() {
  1139. this.setData({
  1140. showCommodity: false,
  1141. showCoupon: false,
  1142. showContact: false
  1143. })
  1144. },
  1145. hideContact() {
  1146. this.setData({
  1147. showContact: false
  1148. })
  1149. },
  1150. calcShare() {
  1151. // this.exit()
  1152. this.setData({
  1153. sendShare: false
  1154. })
  1155. },
  1156. contactKf() {
  1157. let keys = Object.keys(this.navDatas)
  1158. let goodsId = this.navDatas[keys[0]][0].id
  1159. let user = wx.getStorageSync('userinfoDetail')
  1160. util.request(api.AddTalkCount, {
  1161. goodsId,
  1162. viewId: user && user.userId || '',
  1163. sceneNum: this.data.sceneNum
  1164. }, 'get')
  1165. this.hideAlert && this.hideAlert()
  1166. this.hideContact && this.hideContact()
  1167. },
  1168. onHide() {
  1169. this.socketSendMessage('changeOnlineStatus', {
  1170. status: 0
  1171. })
  1172. this.pauseVideo = true
  1173. this.joinUrl()
  1174. }
  1175. }