socket.js 26 KB

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