socket.js 26 KB

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