socket.js 26 KB

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