socket.js 26 KB

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