socket.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. const {
  2. io
  3. } = require('./socket.io-v4.msgpack.js');
  4. var user = require('./services/user.js');
  5. const api = require('/config/api.js');
  6. const util = require('/utils/util.js');
  7. const UNLOGIN = 'NO_LOGIN'
  8. const btoa = require('./utils/btoa')
  9. const manyCount = 50
  10. import remote from './config.js'
  11. var app = getApp();
  12. var isIos = false
  13. wx.getSystemInfo({
  14. success: function (res) {
  15. isIos = res.platform == "ios"
  16. }
  17. })
  18. const debounce = (fn, wait) => {
  19. let callback = fn;
  20. let timerId = null;
  21. function debounced() {
  22. let context = this;
  23. let args = arguments;
  24. clearTimeout(timerId);
  25. timerId = setTimeout(function () {
  26. callback.apply(context, args);
  27. }, wait);
  28. }
  29. return debounced;
  30. }
  31. let urlToJson = (url = window.location.href) => { // 箭头函数默认传值为当前页面url
  32. let obj = {},
  33. index = url.indexOf('?'), // 看url有没有参数
  34. params = url.substr(index + 1); // 截取url参数部分 id = 1 & type = 2
  35. if (index != -1) { // 有参数时
  36. let parr = params.split('&'); // 将参数分割成数组 ["id = 1 ", " type = 2"]
  37. for (let i of parr) { // 遍历数组
  38. let arr = i.split('='); // 1) i id = 1 arr = [id, 1] 2)i type = 2 arr = [type, 2]
  39. obj[arr[0]] = arr[1]; // obj[arr[0]] = id, obj.id = 1 obj[arr[0]] = type, obj.type = 2
  40. }
  41. }
  42. return obj;
  43. }
  44. export default {
  45. joinUrl() {
  46. const url = true ? this.data.url.replace('shop.html', 'test-shop.html') : this.data.url;
  47. let options = {
  48. API_BASE_URL: api.API_BASE_URL,
  49. "url": url,
  50. // "url": 'http://192.168.0.112:8080',
  51. "reload": this.data.reload,
  52. "token": wx.getStorageSync('token'),
  53. "code": this.mcode,
  54. "brandId": this.options.id,
  55. "open": this.data.showCommodity,
  56. "pauseVideo": this.pauseVideo,
  57. "bottom": this.data.bottom || 0,
  58. socket: {
  59. socketHost: remote.socketHost,
  60. path: '/fsl-node',
  61. options: {
  62. ...this.data.socketOptions,
  63. // nickname: encodeURI(encodeURI(this.data.socketOptions.nickname))
  64. nickname: encodeURIComponent(encodeURIComponent(this.data.socketOptions.nickname))
  65. }
  66. }
  67. }
  68. // let base = 'http://127.0.0.1:5500/index.html'
  69. // let base = remote.viewHost + '/shop-container/shop.html'
  70. let sponsor = !!this.data.canShow
  71. if (this.data.join && !this.options.join) {
  72. sponsor = false
  73. }
  74. // 33是从我的房间出来的
  75. if (Number(this.data.type) === 33) {
  76. sponsor = true;
  77. }
  78. // debugger
  79. // remote.viewHost
  80. let hostUrl
  81. if (options.url.indexOf('www.4dkankan.com') != -1) {
  82. hostUrl = 'https://www.4dkankan.com/shop-container-zfb/'
  83. } else if (options.url.indexOf('test.4dkankan.com') != -1) {
  84. hostUrl = 'https://test.4dkankan.com/shop-container-zfb/'
  85. } else {
  86. // hostUrl = 'https://zfb.4dkankan.com/shop-container/'
  87. // hostUrl = remote.viewHost + '/shop-container/'
  88. hostUrl = remote.viewHost + '/shop-container-v4/'
  89. }
  90. // let base = remote.viewHost + '/shop-container/fashilong.html?env=' + remote.env + '&sponsor=' + sponsor + '&many=' + this.data.many
  91. let base = hostUrl + 'fashilong.html?time=' + Date.now() + '&env=' + remote.env + '&sponsor=' + sponsor + '&many=' + this.data.many
  92. // let base = remote.viewHost + '/shop.html'
  93. this.data.reload = false
  94. this.data.showCommodity = false
  95. options.url = options.url + '&vlog';
  96. if (!this.data.webviewUrl) {
  97. console.log(base)
  98. this.setData({
  99. 'webviewUrl': base + '#' + JSON.stringify(options)
  100. })
  101. } else {
  102. this.socketSendMessage('clientSyncAction', {
  103. sender: 'h5',
  104. type: 'hashChange',
  105. data: options
  106. })
  107. }
  108. },
  109. onShow() {
  110. this.setData({
  111. isIos,
  112. showComtypesAllTab: false
  113. })
  114. if (this.socketSendMessage) {
  115. this.pauseVideo = false
  116. this.joinUrl()
  117. this.socketSendMessage('changeOnlineStatus', {
  118. status: true
  119. })
  120. }
  121. },
  122. changeShowComtypesAllTab(ev) {
  123. this.setData({
  124. showCommodity: false
  125. })
  126. setTimeout(() => {
  127. this.setData({
  128. showComtypesAllTab: ev.currentTarget.dataset.show,
  129. showCommodity: true
  130. })
  131. }, 100)
  132. },
  133. async authorizeRecord() {
  134. let isAuth = await new Promise((r, j) => {
  135. wx.authorize({
  136. scope: 'scope.record',
  137. success: () => r(true),
  138. fail: () => r(false)
  139. })
  140. })
  141. if (isAuth) return true
  142. let res = await new Promise(r => {
  143. wx.showModal({
  144. title: '提示',
  145. content: '您未授权录音,说话功能将无法使用',
  146. showCancel: true,
  147. confirmText: "授权",
  148. confirmColor: "#52a2d8",
  149. success: res => r(res),
  150. fail: () => r(false)
  151. })
  152. })
  153. if (!res || res.cancel) return;
  154. isAuth = await new Promise((r) => {
  155. wx.openSetting({
  156. success: res => r(res.authSetting['scope.record']),
  157. fail: () => r(false)
  158. })
  159. })
  160. return isAuth
  161. },
  162. // 获取录音权限状态
  163. async getAuthorizeRecordStatus() {
  164. const isAuth = await new Promise((r, j) => {
  165. wx.authorize({
  166. scope: 'scope.record',
  167. success: () => r(true),
  168. fail: () => r(false)
  169. })
  170. })
  171. return Promise.resolve(isAuth)
  172. },
  173. async agetUserInfo() {
  174. const res = await util.request(api.UserInfo)
  175. if (res.errno === 401) {
  176. return {
  177. userId: UNLOGIN,
  178. avatar: ''
  179. }
  180. } else {
  181. const data = res.data
  182. data.region = data.city ? data.city.split(',') : []
  183. data.birthday = data.birthday || '1990-01-01'
  184. return data
  185. }
  186. },
  187. async getUserInfo() {
  188. let userInfo = wx.getStorageSync('userInfo');
  189. let token = wx.getStorageSync('token');
  190. if (userInfo && userInfo.userId && token) {
  191. let info = await this.agetUserInfo()
  192. return {
  193. ...userInfo,
  194. ...info,
  195. avatarUrl: info.avatar
  196. };
  197. } else {
  198. return {
  199. userId: UNLOGIN,
  200. avatar: ''
  201. }
  202. }
  203. // let detail
  204. // let isAuth = await new Promise((r, j) => {
  205. // wx.authorize({
  206. // scope: 'scope.userInfo',
  207. // success: () => r(true),
  208. // fail: () => r(false)
  209. // })
  210. // })
  211. // if (!isAuth) {
  212. // this.setData({userAuth: true})
  213. // detail = await new Promise(r => {
  214. // this.bindGetUserInfo = (e) => {
  215. // if (e.detail.userInfo) {
  216. // this.setData({userAuth: false})
  217. // console.log('gei', e.detail)
  218. // r(e.detail)
  219. // }
  220. // }
  221. // })
  222. // } else {
  223. // detail = await new Promise(r => {
  224. // wx.getUserInfo({
  225. // success: res => r(res),
  226. // fail: () => r(false)
  227. // })
  228. // })
  229. // }
  230. // try {
  231. // let res = await user.loginByWeixin(detail)
  232. // app.globalData.userInfo = res.data.userInfo;
  233. // app.globalData.token = res.data.token;
  234. // return res.data.userInfo
  235. // } catch(e) {
  236. // return false
  237. // }
  238. },
  239. login() {
  240. getApp().setLoginProps(false)
  241. },
  242. async getSocketOptions(sceneId, roomId) {
  243. //TODO
  244. console.log('this.data.type', this.data.type)
  245. // debugger;
  246. let result
  247. if (Number(this.data.type) === 33) {
  248. result = await util.request(api.enterRoom, {
  249. businessId: roomId
  250. }, 'POST', 'application/json')
  251. if (result.code !== 200) {
  252. wx.showModal({
  253. content: result.error,
  254. complete: () => {
  255. wx.navigateBack({
  256. url: '/pages/roomManger/roomManger',
  257. })
  258. }
  259. })
  260. return
  261. }
  262. }
  263. const capacities = !!result ? result.message.capacities : 50 // 房间限制人数
  264. const {
  265. isAnchor,
  266. assistant,
  267. } = !!result ? result.message : {}
  268. let userInfo = await this.getUserInfo()
  269. // console.log('---', userInfo)
  270. // this.setData({
  271. // userInfoa: userInfo.nickname.split('').join(' ')
  272. // })
  273. userInfo.nickname = userInfo.nickname.replace(/[^\u4E00-\u9FA5A-Za-z0-9]/g, '')
  274. if (userInfo.nickname == "") {
  275. userInfo.nickname = "口"
  276. }
  277. // this.role !== 'leader'
  278. let roomType
  279. if ((!this.data.canShow && !this.data.join) || (this.data.join && !this.options.join)) {
  280. // roomType = '1v1'
  281. if (this.options.roomId) {
  282. this.role = 'leader'
  283. }
  284. console.log('**************')
  285. console.log(this.options)
  286. }
  287. let isAllowMic // 真正MIC权, 房主与 授权一个 要在房间isAllowMic开启
  288. if (Number(isAnchor) === 1) {
  289. this.role = "leader"
  290. isAllowMic = 1
  291. } else {
  292. this.role = 'customer'
  293. isAllowMic = 0
  294. }
  295. if (assistant && assistant.userId && assistant.userId == userInfo.userId) {
  296. this.role = 'assistant'
  297. }
  298. console.log('进入房间角色,', this.role);
  299. const isAuthMic = await this.getAuthorizeRecordStatus();
  300. console.log('当前用户录音权限状态', isAuthMic)
  301. return {
  302. role: this.role,
  303. userId: userInfo.userId,
  304. // roomType,
  305. avatar: userInfo.avatarUrl,
  306. nickname: userInfo.nickname,
  307. voiceStatus: getApp().globalData.voiceProps.noMute ? 0 : 2,
  308. isAuthMic: isAuthMic ? 1 : 0,
  309. isAllowMic: isAllowMic,
  310. roomId: roomId,
  311. sceneNumber: sceneId,
  312. onlineStatus: true,
  313. userLimitNum: capacities
  314. }
  315. },
  316. async socketStart({
  317. sceneId,
  318. roomId,
  319. options
  320. }) {
  321. if (!options) {
  322. options = await this.getSocketOptions(sceneId, roomId)
  323. }
  324. console.log('小程序参数', options)
  325. if (!options.roomId) {
  326. return
  327. }
  328. let socket = io(remote.socketHost, {
  329. path: '/fsl-node',
  330. transport: ['websocket'],
  331. query: {
  332. ...options,
  333. isClient: true,
  334. from: 2
  335. }
  336. })
  337. console.error('新建socket Room', options.roomId)
  338. this.setData({
  339. socketStatus: 0
  340. })
  341. socket.on('connect', () => this.setData({
  342. socketStatus: 1
  343. }))
  344. socket.on('connect_error', () => this.setData({
  345. socketStatus: -1
  346. }))
  347. socket.on('connect_timeout', () => this.setData({
  348. socketStatus: -1
  349. }))
  350. socket.on('disconnect', () => this.setData({
  351. socketStatus: -1
  352. }))
  353. socket.on('reconnect', () => {
  354. // wx.showToast({
  355. // title: '重连',
  356. // })
  357. this.setData({
  358. socketStatus: this.data.socketStatus
  359. })
  360. let noMute = getApp().globalData.voiceProps.noMute
  361. this.socketSendMessage('changeVoiceStatus', {
  362. status: noMute ? 0 : 2
  363. })
  364. this.socketSendMessage('changeOnlineStatus', {
  365. status: true
  366. })
  367. })
  368. socket.on('reconnect_failed', () => this.setData({
  369. socketStatus: -1
  370. }))
  371. socket.on('error', () => this.setData({
  372. socketStatus: -1
  373. }))
  374. socket.on('roomIn', config => {
  375. let enableTalk = config.roomsConfig.enableTalk !== false
  376. let noMute = getApp().globalData.voiceProps.noMute
  377. getApp().globalData.voiceProps.force = enableTalk
  378. if (!enableTalk && !noMute) {
  379. if (this.role !== 'leader') {
  380. // this.mic()
  381. }
  382. }
  383. })
  384. this.socketSendMessage = (event, obj) => {
  385. console.error('发送 socket Room', options.roomId, event, obj)
  386. socket.emit(event, obj)
  387. }
  388. socket.on('clientSyncAction', (data) => {
  389. console.log('调用', data.type, '方法', data)
  390. if (this[data.type]) {
  391. this[data.type](data)
  392. } else if (data.type == 'wx-subscribe') {
  393. this.getUrlCode(data.data)
  394. } else {
  395. console.error('没有', data.type, '方法')
  396. }
  397. })
  398. socket.on('action', (data) => {
  399. if (data.type === 'navigateToGoods') {
  400. this.navigateToGoodsAction(data.data)
  401. }
  402. })
  403. socket.on('changeRoomEnableTalk', config => {
  404. if (this.role !== 'leader') {
  405. this.changeRoomEnableTalk(config)
  406. }
  407. })
  408. socket.on('startCall', this.startCall.bind(this))
  409. socket.on('stopCall', (data) => {
  410. console.log('on stopCall')
  411. this.stopCall(data)
  412. })
  413. this.handleSomeOneInRoom = this.handleSomeOneInRoom.bind(this)
  414. // socket.on('someOneInRoom', debounce(this.handleSomeOneInRoom, 100))
  415. socket.on('someOneInRoom', debounce(this.handleSomeOneInRoom, 100))
  416. socket.on('someOneLeaveRoom', (user, data) => {
  417. this.handleSomeOneLeave(user)
  418. })
  419. socket.on('roomClose', (data) => {
  420. console.log('on roomClose')
  421. this.stopCall(data)
  422. })
  423. socket.on('autoReJoin', (data) => {
  424. console.log('on autoReJoin')
  425. if ('roomId' in data) {
  426. options.roomId = Number(data.roomId)
  427. }
  428. })
  429. socket.on("beKicked", data => {
  430. if (data.userId && data.roomId) {
  431. const socketOptions = this.data.socketOptions
  432. const userId = data.userId
  433. const roomId = data.roomId
  434. // debugger
  435. if (socketOptions.userId == userId && this.options.roomId == roomId) {
  436. wx.showToast({
  437. title: '您已被踢出房间!',
  438. icon: 'none',
  439. complete: () => {
  440. setTimeout(() => {
  441. this.socketStop();
  442. wx.redirectTo({
  443. url: '/pages/roomManger/roomManger',
  444. });
  445. }, 1000)
  446. }
  447. })
  448. }
  449. }
  450. });
  451. this.socketStop = () => {
  452. if (socket) {
  453. socket.close()
  454. console.error('断开 并滞空 socket Room', options.roomId)
  455. this.setData({
  456. socketStatus: 2
  457. })
  458. socket = null
  459. }
  460. }
  461. return options
  462. },
  463. getUrlCode(url) {
  464. this.socketSendMessage('clientSyncAction', {
  465. sender: 'wx',
  466. type: 'wx-subscribe-result',
  467. data: 3020
  468. })
  469. // wx.request({
  470. // url: url, //仅为示例,并非真实的接口地址
  471. // method: 'get',
  472. // success: (res) => {
  473. // let code = -1
  474. // if (typeof res.data.code != 'undefined') {
  475. // code = res.data.code
  476. // }
  477. // this.socketSendMessage('clientSyncAction', {
  478. // sender: 'wx',
  479. // type: 'wx-subscribe-result',
  480. // data: code
  481. // })
  482. // },
  483. // fail: (err) => {
  484. // console.log(err)
  485. // }
  486. // })
  487. },
  488. changeRoomEnableTalk(data) {
  489. console.log(data)
  490. let noMute = getApp().globalData.voiceProps.noMute
  491. getApp().globalData.voiceProps.force = data.enableTalk
  492. // noMute true 静音
  493. // enableTalk false 静音
  494. if (!!data.enableTalk === !!noMute) {
  495. this.mic()
  496. }
  497. },
  498. navigateToGoods({
  499. data
  500. }) {
  501. // wx.showToast({
  502. // title: JSON.stringify(data).substr(40)
  503. // })
  504. this.navigateToGoodsAction(data)
  505. },
  506. navigateToGoodsAction(id) {
  507. wx.navigateTo({
  508. url: '/pages/goods/goods?id=' + id,
  509. })
  510. },
  511. getUrl(url, socketOptions, isJoin) {
  512. url += '&room_id=' + socketOptions.roomId + '&user_id=' + socketOptions.userId + '&origin=fashilong'
  513. if (isJoin) {
  514. url += '&role=' + this.role + '&shopping'
  515. } else {
  516. url += '&role=' + this.role
  517. }
  518. console.error(url)
  519. console.log(isJoin)
  520. return url
  521. },
  522. navigateToMiniProgram(data) {
  523. wx.showModal({
  524. title: '温馨提示',
  525. content: '即将跳到其他小程序,是否继续?',
  526. showCancel: true, //是否显示取消按钮
  527. cancelText: "取消", //默认是“取消”
  528. confirmText: "确定", //默认是“确定”
  529. success: function (res) {
  530. if (res.cancel) {
  531. //点击取消,wx.navigateBack
  532. } else {
  533. wx.navigateToMiniProgram(data.data)
  534. }
  535. },
  536. fail: function (res) {
  537. //接口调用失败的回调函数,wx.navigateBack
  538. },
  539. complete: function (res) {
  540. //接口调用结束的回调函数(调用成功、失败都会执行)
  541. },
  542. })
  543. },
  544. async handleSomeOneInRoom(data) {
  545. if (data && data.user) {
  546. console.log('handleSomeOneInRoom', data)
  547. this.startCall(data)
  548. }
  549. },
  550. async startCall(data) {
  551. //TODO 触发三次
  552. console.log('startCall-data', data)
  553. // if( this.role =='leader'){
  554. this.setData({
  555. shareStatus: 1
  556. })
  557. if (!data) return;
  558. this.setData({
  559. surplus: this.data.peopleCount - data.roomsPerson.length
  560. })
  561. //undefined是未授权,状态为3
  562. let voiceStatus
  563. if (!this.isAuthorizeRecord) {
  564. const unAuth = await this.authorizeRecord();
  565. if (typeof unAuth === 'undefined') {
  566. // debugger
  567. voiceStatus = 3
  568. } else {
  569. voiceStatus = Number(unAuth)
  570. }
  571. }
  572. //限制只有主持人才可以开麦
  573. // if (this.role == 'leader') {
  574. // if (!this.isAuthorizeRecord) {
  575. // const voiceStatus = Number(await this.authorizeRecord())
  576. // this.isAuthorizeRecord = true
  577. // // getApp().setVoiceProps({
  578. // // noMute: !voiceStatus
  579. // // })
  580. // // console.log(getApp().globalData.voiceProps.noMute)
  581. // // this.socketSendMessage('changeVoiceStatus', {
  582. // // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  583. // // })
  584. // // this.data.socketOptions.voiceStatus = 1
  585. // // this.socketSendMessage('changeVoiceStatus', {status: noMute ? 0 : 2})
  586. // }
  587. // }
  588. const socketOptions = this.data.socketOptions
  589. getApp().globalData.roomId = socketOptions.roomId
  590. const user = data.roomsPerson.find(user => user.userId == socketOptions.userId)
  591. if (!user) {
  592. return
  593. }
  594. //屏蔽有人进来才开麦克风
  595. // if (data.roomsPerson.length <= 1) {
  596. // return
  597. // }
  598. user.noMute = getApp().globalData.voiceProps.noMute
  599. getApp().setVoiceProps({
  600. ...user,
  601. action: 'startCall'
  602. })
  603. // this.socketSendMessage('changeVoiceStatus', {
  604. // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  605. // })
  606. // }
  607. },
  608. stopCall() {
  609. console.error('stopCall')
  610. this.setData({
  611. shareStatus: 0
  612. })
  613. getApp().setVoiceProps({
  614. noMute: false,
  615. action: 'stopCall'
  616. })
  617. if (this.runManager) {
  618. // this.recorderManager.stop()
  619. this.runManager = false
  620. }
  621. },
  622. handleSomeOneLeave(data) {
  623. if (data.roomsPerson.length <= 1) {
  624. // this.stopCall()
  625. }
  626. this.setData({
  627. surplus: this.data.peopleCount - data.roomsPerson.length
  628. })
  629. },
  630. async newRoom(data) {
  631. if (data.roomId) return;
  632. this.stopCall()
  633. getApp().globalData.rtcParams = []
  634. getApp().globalData.pusher = ''
  635. if (this.data.join && !this.options.join) {
  636. wx.switchTab({
  637. url: '/pages/index/index',
  638. })
  639. return;
  640. }
  641. this.role = this.data.canShow ? 'leader' : 'customer'
  642. let options = await this.getSocketOptions(this.mcode)
  643. this.socketSendMessage('clientSyncAction', {
  644. type: 'newRoom',
  645. data: options
  646. })
  647. setTimeout(async () => {
  648. this.wssSuccess = false
  649. this.socketStop && this.socketStop()
  650. this.data.many = !!this.data.canShow
  651. this.setData({
  652. // peopleCount: this.data.many ? manyCount : 5
  653. peopleCount: manyCount
  654. })
  655. let base = this.base
  656. let socketOptions = await this.socketStart({
  657. options
  658. })
  659. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  660. this.base = base
  661. this.setData({
  662. url,
  663. socketOptions,
  664. })
  665. this.joinUrl()
  666. this.setData({
  667. socketOptions
  668. })
  669. this.loadConponSuccess = true
  670. this.readySendCouponCtrl()
  671. }, 300)
  672. },
  673. async exit() {
  674. // this.stopCall()
  675. getApp().globalData.rtcParams = []
  676. getApp().globalData.pusher = ''
  677. this.socketStop && this.socketStop()
  678. this.role = 'leader'
  679. let base = this.base
  680. let socketOptions = await this.socketStart({
  681. sceneId: this.mcode
  682. })
  683. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  684. this.base = base
  685. wx.nextTick(() => {
  686. setTimeout(() => {
  687. this.setData({
  688. url,
  689. loadUrl: true,
  690. socketOptions,
  691. showCommodityCtrl: false,
  692. hideWebView: false,
  693. reload: true
  694. })
  695. this.joinUrl()
  696. }, 500)
  697. })
  698. },
  699. clearDebuger() {
  700. this.setData({
  701. debugerInfo: ''
  702. })
  703. },
  704. async mic({
  705. data
  706. }) {
  707. if (Number(data.user.isAllowMic) === 1) {
  708. let noMute = getApp().globalData.voiceProps.noMute
  709. // debugger
  710. // noMute true 静音
  711. // enableTalk false 静音
  712. // if (!!getApp().globalData.voiceProps.force === !!noMute)
  713. // return
  714. // if (!getApp().globalData.voiceProps.force && (!this.data.socketOptions.voiceStatus || noMute)) return;
  715. if (!this.data.socketOptions.voiceStatus) {
  716. let voiceStatus = await this.authorizeRecord()
  717. if (voiceStatus) {
  718. this.data.socketOptions.voiceStatus = 1
  719. noMute = false
  720. } else {
  721. noMute = true
  722. }
  723. } else {
  724. noMute = !noMute
  725. }
  726. getApp().globalData.voiceProps.noMute = noMute
  727. this.socketSendMessage('changeVoiceStatus', {
  728. status: noMute ? 0 : 2,
  729. })
  730. getApp().setVoiceProps({
  731. noMute
  732. })
  733. wx.showToast({
  734. title: `已${noMute ? '关闭' : '开启'}麦克风`,
  735. })
  736. }
  737. },
  738. callPhone() {
  739. wx.makePhoneCall({
  740. phoneNumber: this.data.contractPhone,
  741. })
  742. this.setData({
  743. showContact: false
  744. })
  745. },
  746. /**
  747. * 用户点击右上角分享
  748. */
  749. onShareAppMessage: function (res) {
  750. let {
  751. id,
  752. newPicUrl
  753. } = this.data
  754. if (res.from === 'button') {
  755. this.setData({
  756. sendShare: false
  757. })
  758. return {
  759. title: '【好友推荐】一起来云逛吧',
  760. imageUrl: newPicUrl,
  761. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=true&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`,
  762. }
  763. } else {
  764. return {
  765. imageUrl: newPicUrl,
  766. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=false`,
  767. }
  768. }
  769. },
  770. /**
  771. * 生命周期函数--监听页面卸载
  772. */
  773. onUnload: function () {
  774. console.log('on onUnload')
  775. // this.socketSendMessage('stopCall', {})
  776. // this.stopCall()
  777. this.socketStop()
  778. getApp().globalData.pusher = ''
  779. },
  780. cart(data) {
  781. this.setData({
  782. showCommodityCtrl: data.data
  783. })
  784. },
  785. share() {
  786. console.log('**********')
  787. // console.log(!!this.data.mamy)
  788. const companyName = `指房宝(杭州)科技有限公司`
  789. const vrLink = `/pages/webview/index`
  790. const img_url = this.data.newPicUrl || 'http://video.cgaii.com/new4dage/images/images/home_2_a.jpg'
  791. const shareImg = img_url
  792. this.count = this.count || 0
  793. if (this.data.many && this.data.shareStatus == 1) {
  794. //开启一起逛时候的分享
  795. 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}`)
  796. console.log(this.data.socketOptions)
  797. wx.navigateTo({
  798. 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}`,
  799. })
  800. } else {
  801. 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}`);
  802. wx.navigateTo({
  803. 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}`,
  804. })
  805. }
  806. },
  807. back(data) {
  808. if (data.sender !== 'h5') return;
  809. wx.switchTab({
  810. url: '/pages/index/index'
  811. })
  812. this.setData({
  813. showCommodityCtrl: false
  814. })
  815. },
  816. service() {
  817. this.setData({
  818. showContact: true,
  819. showCommodity: false,
  820. showCoupon: false
  821. })
  822. },
  823. invite(data) {
  824. if (data.sender !== 'h5') return;
  825. this.setData({
  826. sendShare: true,
  827. count: ++this.data.count
  828. })
  829. },
  830. coupon(data) {
  831. if (data.sender !== 'h5') return;
  832. this.setData({
  833. showContact: false,
  834. showCommodity: false,
  835. showCoupon: true
  836. })
  837. },
  838. liveGotoGood(ev) {
  839. let id = ev.currentTarget.dataset.item.goodsId
  840. wx.navigateTo({
  841. url: '/pages/goods/goods?id=' + id,
  842. })
  843. },
  844. gotoGoodsDOM(event) {
  845. this.gotoGoods(event.currentTarget.dataset.item.hotIdList[0])
  846. },
  847. gotoGoodsSocket(data) {
  848. this.gotoGoods(data.data)
  849. },
  850. gotoGoods(id) {
  851. console.log('---', id)
  852. this.socketSendMessage('clientSyncAction', {
  853. type: 'openTag',
  854. data: id
  855. })
  856. this.setData({
  857. showCommodity: false
  858. })
  859. this.joinUrl()
  860. },
  861. addCard(event) {
  862. wx.navigateTo({
  863. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=addCard',
  864. })
  865. },
  866. buyGoods(event) {
  867. wx.navigateTo({
  868. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=buyGoods',
  869. })
  870. },
  871. showCommodityFn() {
  872. this.setData({
  873. showCommodity: true,
  874. showContact: false,
  875. showCoupon: false
  876. })
  877. this.joinUrl()
  878. },
  879. hideComodity() {
  880. this.setData({
  881. showCommodity: false
  882. })
  883. this.joinUrl()
  884. },
  885. hideCoupon() {
  886. this.setData({
  887. showCoupon: !this.data.showCoupon
  888. })
  889. },
  890. async receive(ev) {
  891. let item = ev.target.dataset.item
  892. try {
  893. // wx.showToast({
  894. // title: '领取优惠卷',
  895. // })
  896. // return;
  897. if (item.hasReceived || item.number <= item.receiveNumber) return;
  898. let res = await util.request(api.CouponExchange, {
  899. couponId: item.id
  900. })
  901. if (res.code === 0) {
  902. wx.showToast({
  903. title: '已成功领取',
  904. success: () => {
  905. this.setData({
  906. showCoupon: false
  907. })
  908. wx.nextTick(() => {
  909. this.setData({
  910. coupons: this.data.coupons.map(citem => {
  911. return {
  912. ...citem,
  913. hasReceived: citem.id === item.id ? true : citem.hasReceived
  914. }
  915. }),
  916. showCoupon: true
  917. })
  918. })
  919. }
  920. })
  921. } else if (res.errno === 401) {
  922. getApp().setLoginProps(false)
  923. } else {
  924. wx.showToast({
  925. title: res.msg,
  926. })
  927. }
  928. } catch (e) {
  929. console.error(e)
  930. wx.showToast({
  931. icon: 'none',
  932. title: '领取失败',
  933. })
  934. }
  935. },
  936. async getCouponList(id) {
  937. const success = (res) => {
  938. this.setData({
  939. coupons: res.data.list.map(item => {
  940. item.typeMoney = item.typeMoney.toString()
  941. item.fontSize = item.typeMoney.length === 3 ? '90rpx' :
  942. item.typeMoney.length === 4 ? '70rpx' : '130rpx'
  943. return item
  944. })
  945. })
  946. this.loadConponSuccess = true
  947. this.readySendCouponCtrl()
  948. }
  949. let res = await util.request(api.BrandCouponList, {
  950. brandId: id,
  951. pageNum: 1,
  952. pageSize: 10000
  953. }, 'GET')
  954. console.log(res)
  955. if (res.code === 0) {
  956. success(res)
  957. } else {
  958. let res = await util.request(api.UNBrandCouponList, {
  959. brandId: id,
  960. pageNum: 1,
  961. pageSize: 10000
  962. }, 'GET')
  963. success(res)
  964. }
  965. },
  966. ready() {
  967. this.wssSuccess = true
  968. this.readySendCouponCtrl()
  969. },
  970. readySendCouponCtrl() {
  971. if (this.wssSuccess && this.loadConponSuccess) {
  972. this.loadConponSuccess = false
  973. this.socketSendMessage('clientSyncAction', {
  974. type: 'showCoupon',
  975. data: this.data.coupons.length > 0
  976. })
  977. }
  978. },
  979. getBrand: function (id, code) {
  980. this.getGoodsCount(code, id)
  981. return;
  982. let that = this;
  983. util.request(api.SueneCategory, {
  984. sceneNum: code
  985. }, 'GET').then(function (res) {
  986. if (res.code === 0) {
  987. const comtypes = res.list.map(item => {
  988. item.width = (item.name.length + (item.num.toString().length / 2) + 2) * 16
  989. return {
  990. ...item
  991. }
  992. })
  993. that.setData({
  994. comWidth: comtypes.reduce((a, b) => a + b.width + 10, 0),
  995. comtypes,
  996. thumComtypes: (!isIos && comtypes.length > 3) ? comtypes.slice(0, 3) : null,
  997. currTypeId: comtypes.length > 0 && comtypes[0].category_id
  998. });
  999. wx.showToast({
  1000. title: 'currTypeId' + that.data.currTypeId.length,
  1001. })
  1002. that.data.currTypeId && that.getGoodsList(id, that.data.currTypeId);
  1003. }
  1004. });
  1005. },
  1006. getGoodsCount(code, id) {
  1007. util.request(api.GoodsNumCount, {
  1008. isDelete: 0,
  1009. isOnSale: 1,
  1010. brandId: id
  1011. }, 'GET')
  1012. .then(res => {
  1013. if (res.errno === 0) {
  1014. this.setData({
  1015. goodsCount: res.data
  1016. })
  1017. }
  1018. this.getCouponList(id)
  1019. })
  1020. },
  1021. getGoodsList(id, category_id) {
  1022. var that = this;
  1023. if (!(this.data.navList && this.data.navList.length)) {
  1024. that.navDatas = {}
  1025. let navDatas = this.data.navList = this.data.comtypes
  1026. // util.request(api.GoodsCategory, { id: category_id })
  1027. // .then(function (res) {
  1028. // if (res.errno == 0) {
  1029. // let navDatas = res.data.brotherCategory
  1030. // that.setData({
  1031. // navList: navDatas,
  1032. // currTypeId: category_id
  1033. // });
  1034. that.navDatas = {}
  1035. navDatas.forEach(item => {
  1036. util.request(api.GoodsList, {
  1037. brandId: id,
  1038. categoryId: item.category_id,
  1039. page: that.data.page,
  1040. size: that.data.size
  1041. })
  1042. .then(res => {
  1043. if (res.errno === 0) {
  1044. that.navDatas[item.category_id] = res.data.goodsList
  1045. }
  1046. })
  1047. })
  1048. // }
  1049. // })
  1050. }
  1051. if (that.navDatas[category_id]) {
  1052. if (!isIos) {
  1053. let showCommodity = that.data.showCommodity
  1054. that.setData({
  1055. showCommodity: false
  1056. })
  1057. setTimeout(() => {
  1058. wx.nextTick(() => {
  1059. that.setData({
  1060. goodsList: that.navDatas[category_id],
  1061. currTypeId: category_id,
  1062. showCommodity: showCommodity
  1063. });
  1064. })
  1065. }, 500)
  1066. } else {
  1067. that.setData({
  1068. goodsList: that.navDatas[category_id],
  1069. currTypeId: category_id,
  1070. });
  1071. }
  1072. } else {
  1073. console.error('诱惑去啦')
  1074. util.request(api.GoodsList, {
  1075. brandId: id,
  1076. categoryId: category_id,
  1077. page: that.data.page,
  1078. size: that.data.size
  1079. })
  1080. .then(function (res) {
  1081. if (res.errno === 0) {
  1082. that.setData({
  1083. goodsList: res.data.goodsList,
  1084. currTypeId: category_id
  1085. });
  1086. // this.data.navList
  1087. }
  1088. });
  1089. }
  1090. },
  1091. getBrandDetail: function (id, type, cb) {
  1092. util.request(api.BrandDetail, {
  1093. id: id,
  1094. type: type,
  1095. }).then((res) => {
  1096. let base = res.data.brand.sceneUrl
  1097. // let base = 'http://192.168.0.112:8080/shop.html?m=t-7Uqj9Fq&origin=fashilong'
  1098. if (res.errno === 0) {
  1099. let url = base + "&sid=" + id
  1100. this.setData({
  1101. id: id,
  1102. newPicUrl: res.data.brand.appListPicUrl,
  1103. sceneNum: res.data.brand.sceneNum,
  1104. canShow: res.data.brand.canShow,
  1105. contractPhone: res.data.brand.contractPhone
  1106. })
  1107. if (this.data.many === void 0) {
  1108. this.data.many = !!res.data.brand.canShow
  1109. }
  1110. this.setData({
  1111. // peopleCount: this.data.many ? manyCount : 5,
  1112. peopleCount: manyCount
  1113. })
  1114. if (!res.data.brand.canShow) {
  1115. this.role = 'customer'
  1116. } else if (!this.options.join) {
  1117. this.role = 'leader'
  1118. }
  1119. cb(url, urlToJson(url).m, )
  1120. }
  1121. });
  1122. },
  1123. selectType(ev) {
  1124. this.getGoodsList(this.options.id, ev.target.dataset.item.category_id)
  1125. },
  1126. hideCS() {
  1127. this.setData({
  1128. showCommodity: false,
  1129. showCoupon: false,
  1130. showContact: false
  1131. })
  1132. },
  1133. hideContact() {
  1134. this.setData({
  1135. showContact: false
  1136. })
  1137. },
  1138. calcShare() {
  1139. // this.exit()
  1140. this.setData({
  1141. sendShare: false
  1142. })
  1143. },
  1144. contactKf() {
  1145. let keys = Object.keys(this.navDatas)
  1146. let goodsId = this.navDatas[keys[0]][0].id
  1147. let user = wx.getStorageSync('userinfoDetail')
  1148. util.request(api.AddTalkCount, {
  1149. goodsId,
  1150. viewId: user && user.userId || '',
  1151. sceneNum: this.data.sceneNum
  1152. }, 'get')
  1153. this.hideAlert && this.hideAlert()
  1154. this.hideContact && this.hideContact()
  1155. },
  1156. onHide() {
  1157. this.socketSendMessage('changeOnlineStatus', {
  1158. status: false
  1159. })
  1160. this.pauseVideo = true
  1161. this.joinUrl()
  1162. }
  1163. }