socket.js 32 KB

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