socket.js 26 KB

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