socket.js 29 KB

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