socket.js 27 KB

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