socket.js 26 KB

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