index.js 9.71 KB
import homeApi from '~/api/module/home.js'
import commonApi from '~/api/module/common.js'
import {
  systemApi
} from '~/api/index'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    navStyle : "background-color: transparent;",
    animationData: {},
    bannerUrl: '',
    walletObj: {},
    specialSaleArr: [],
    tab: [{
      id: '1',
      label: '我能兑换'
    }, {
      id: '',
      label: '全部'
    }, {
      id: '2',
      label: '100积分以下'
    }, {
      id: '3',
      label: '100-200积分'
    }, {
      id: '4',
      label: '200-300积分'
    }],
    subTab: [],
    activeTab: 1,
    frontendCategoryId: '',
    goodsList: [],
    count: 1
  },

  navbarReady() {
    wx.nextTick(() => {
      this.startAnimation()
    })
  },
  // 顶部公告动画
  startAnimation: function() {
    const query = wx.createSelectorQuery()
    query.select('.text-container').boundingClientRect()
    query.select('.text').boundingClientRect()
    query.exec((res) => {
      const containerWidth = res[0]?.width
      const textWidth = res[1]?.width
      // 只有文字宽度超过容器宽度时才滚动
      if (textWidth > containerWidth) {
        const animation = wx.createAnimation({
          duration: (textWidth / 30) * 1000, // 根据文字长度调整滚动时间
          timingFunction: 'linear',
          delay: 0
        })
        animation.translateX(-textWidth).step()
        this.setData({
          animationData: animation.export()
        })
        // 设置循环
        setTimeout(() => {
          this.resetAnimation();
        }, (textWidth / 30) * 1000)
      }
    })
  },
  
  resetAnimation: function() {
    const animation = wx.createAnimation({
      duration: 0,
      timingFunction: 'linear',
      delay: 0
    })
    animation.translateX(0).step()
    this.setData({
      animationData: animation.export()
    })
    setTimeout(() => {
      this.startAnimation()
    }, 50)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const userInfo = wx.p.storage.get('userInfo')
    this.setData({userInfo})
    wx.p.router.getRouterParams(options).then(params => {
      this.setData({loginPageFlag: params?.loginPageFlag}, () => {
        this.getPointsWallet()
      })
    }).catch(err => {
      console.error('参数获取失败:', err)
    })
  },

  // 获取积分会配置
  getHomeData() {
    homeApi.getHomeConfigData({miniType: 1}).then(res => {
      res?.specialEvents?.forEach(item => {
        item?.specialEventGoodsList?.forEach(val => {
          val.id = val.goodsId
        })
      })
      this.setData({
        bannerUrl: res?.mallBannerList[0]?.bannerUrl,
        specialSaleArr: res.specialEvents
      })
    })
  },

  // 获取积分钱包数据
  getPointsWallet() {
    let { loginPageFlag, userInfo } = this.data
    // 获取当前积分数量
    commonApi.getPointsSummary({staffPhone: userInfo?.phone, channelSource: userInfo?.channelSource, merchantId: userInfo?.merchantId}).then(r => {
      if (r?.code == 0) {
        this.setData({
          walletObj: {name: r?.data?.staffName || userInfo?.nickName, phone: r?.data?.staffPhone || userInfo?.phone, scoreSource: userInfo?.channelSource, currentScore: r?.data?.currentScore || 0}
        })
        // 获取钱包数据
        commonApi.getPointsWalletData({
          phone: userInfo?.phone,
          name: r?.data?.staffName || userInfo?.phone,
          scoreSource: userInfo?.channelSource
        }).then(res => {
          let { code, data, message } = res
          if (code == 0) {
            if (data && Object.keys(data)?.length) { // 有数据返回说明已开通钱包
              // 替换昵称
              this.replaceNickName(data)
            } else {
              if (!loginPageFlag) return // 只有通过登录页面进入首页弹出一次
              // 未开通弹出开通钱包弹窗
              this.setData({
                showEnableWallet: true,
                loginPageFlag: false,
                copyWalletObj: {name: r?.data?.staffName || userInfo?.nickName, phone: r?.data?.staffPhone || userInfo?.phone, scoreSource: userInfo?.channelSource}
              })
            }
          } else {
            wx.p.wxApi.showToast(message)
          }
        })
      } else {
        wx.p.wxApi.showToast(r.message)
      }
    })
  },

  replaceNickName(data) {
    let { userInfo } = this.data
    commonApi.replaceWalletName({
      nickName: data?.name,
      phone: data?.phone,
      scoreSource: data?.scoreSource
    }).then(res => {
      let { code, message } = res
      if (code == 0) {
        wx.p.storage.set('userInfo', {...userInfo, nickName: data?.name}) // 更新storage中的nickName
      } else {
        wx.p.wxApi.showToast(message)
      }
    })
  },

  // 获取前端分类
  getCategory() {
    homeApi.getHomeCategoryList({}).then(res => {
      res?.forEach(val => {
        val.label = val.categoryName
      })
      res?.unshift({
        id: '',
        label: '全部分类'
      })
      this.setData({
        subTab: res || []
      })
    })
  },

  // 获取商品数据
  getGoodsList() {
    let { pageNum, goodsList, goodsSkuName, frontendCategoryId, activeTab } = this.data
    let userInfo = wx.p.storage.get('userInfo')
    let params = {
      pageNum,
      pageSize: 10,
      goodsSkuName,
      frontendCategoryId,
      businessType: 1
    }
    if (activeTab == 1) { // 我能兑换
      params.canExchange = 1,
      params.staffPhone = userInfo?.phone
      params.staffPlatform = userInfo?.channelSource
      params.merchantNo = userInfo?.merchantId
    } else if (activeTab) { // 积分区间
      params.storeStart = activeTab == 2 ? 0 : activeTab == 3 ? 100 : activeTab == 4 ? 200 : ''
      params.storeEnd = activeTab == 2 ? 99 : activeTab == 3 ? 200 : activeTab == 4 ? 300 : ''
    }
    homeApi.getGoodsStockroomList(params).then(res => {
      this.setData({
        goodsList: pageNum == 1 ? res?.list || [] : [...goodsList, ...res?.list],
        pages: res.pages,
        triggered: false
      })
    })
  },

  scrollonReachBottom() {
    let { pages, pageNum } = this.data
      // 判断当前页是否是末页
      if (pages == pageNum) return
      this.setData({
        pageNum: pageNum + 1
      })
      this.getGoodsList()
  },

  // 跳转积分中心
  handleToPointCenter() {
    wx.p.router.go('/packageIndex/pages/integral/index/index')
  },
  // 查看公告政策详情
  async policyDetail() {
    let v = await systemApi.getImageVersion()
    wx.p.router.jumpH5(`https://img01.glsx.com.cn/weapp/resource/miniprogram/points-mall/html/policy.html?v=${v}`)
  },
  // 跳转专场
  handleSpecialSale(e) {
    let { target } = e.currentTarget.dataset
    wx.p.router.go('/packageIndex/pages/SpecialSale/SpecialSale', target)
  },
  toIntegral(){
    wx.p.router.go('/packageIndex/pages/integral/index/index')
  },
  // 商品搜素
  handleSearch(e) {
    this.setData({
      goodsSkuName: e.detail,
      goodsList: [],
      pageNum: 1
    }, () => {
      this.getGoodsList()
    })
  },

  // 切换分类筛选
  changeTab(e) {
    this.setData({
      activeTab: e.detail.activeTab,
      frontendCategoryId: e.detail?.activeSubTab,
      goodsList: [],
      pageNum: 1
    }, () => {
      this.getGoodsList()
    })
  },
  closeSku() {
    this.setData({
      showSku: false
    })
  },
  // 加入购物车
  handleAddToCart(e) {
    let value = e.detail
    let { userInfo } = this.data
    const PARAMS = {
      goodsId: value.id,
      sellQty: 1,
      goodsSource: value.goodsSource,
      scoreSource: userInfo?.channelSource,
      merchantId: userInfo?.merchantId
    }
    // if (value.goodsSource == 1) {
    //   if (!value.goodsStock) return wx.p.wxApi.showToast('暂无库存')
    //   cartApi.addToCart(PARAMS).then(res => {
    //     wx.p.wxApi.showToast('加入购物车成功')
    //   })
    // } else {
      // 获取商品详情
      this.getDetail(value)
    // }
  },
  getDetail(options) {
    homeApi.getGoodsDetailInfo({id: options.id, businessType: 1}).then(res => {
      // if (res && res.specificationResponses?.length) {
      //   this.toGetSpecString(res, res.startQty)
      // }
      if (res && res.platformGlGoodsSpecifications?.length) {
        let item = res.platformGlGoodsSpecifications[0] || {}
        res.goodsStock = item.stock
        res.specificationData = item.specificationData
        this.setData({
          activeSku: item.specificationData
        })
      }
      this.setData({
        detailInfo: res || {},
        showSku: true
      })
    })
  },
  getWalletData() {
    let { userInfo } = this.data
    // 获取当前积分数量
    commonApi.getPointsSummary({staffPhone: userInfo?.phone, channelSource: userInfo?.channelSource, merchantId: userInfo?.merchantId}).then(r => {
      if (r?.code == 0) {
        this.setData({
          walletObj: {name: r?.data?.staffName || userInfo?.nickName, phone: r?.data?.staffPhone || userInfo?.phone, scoreSource: userInfo?.channelSource, currentScore: r?.data?.currentScore || 0}
        })
      } else {
        wx.p.wxApi.showToast(r.message)
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getWalletData()
    this.getGoodsList()
    this.getCategory()
    this.getHomeData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  refreshPage() {
    this.setData({
      pageNum: 1,
      goodsSkuName: '',
      frontendCategoryId: '',
      activeTab: ''
    })
    this.onLoad()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onReachBottom() {
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
})