litian
2024-03-05 a81a1a31ce7ee003e0006168e4d4e57da97c2bb6
pages/home/home.js
@@ -1,53 +1,149 @@
import { fetchHome } from '../../services/home/home';
import { fetchGoodsList } from '../../services/good/fetchGoods';
import Toast from 'tdesign-miniprogram/toast/index';
import moment from 'moment'
import { setSessionGuid } from "../../assets/js/userAction"
const app = getApp()
Page({
  data: {
    imgSrcs: [],
    tabList: [],
    goodsList: [],
    goodsListLoadStatus: 0,
    isWhite: false,
    backUrl: null,
    userInfo: {},
    tabList: [], //目录
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: { type: 'dots' },
    swiperImageProps: { mode: 'scaleToFill' },
    bannerList: [],
    current: 1,//轮播图参数
    autoplay: true, //轮播图参数
    duration: '500',//轮播图参数
    interval: 5000,//轮播图参数
    navigation: { type: 'dots' },//轮播图参数
    bannerList: [], //轮播图列表
    specialSubjectList: [],//专题讨论
    activeItem: 0,//精选课程默认选中
    courseTypeList: [],//精选课程分类
    courseList: [],
    bookTypeList: [],//图书类型
    activeItem1: 0,
    booksList: [],
    readBookList: [], //数字阅读
    textbookList: [], //数字教材
    rankingList: [],//排行榜
    shoppingCartGetId: []
  },
  goodListPagination: {
    index: 0,
    num: 20,
  },
  privateData: {
    tabIndex: 0,
  },
  onShow() {
    this.getTabBar().init();
    this.loadHomePage();
    this.getBannerList()
  },
  onLoad() {
  onLoad(options) {
    if (options.backUrl) {
      let backUrl = JSON.parse(decodeURIComponent(options.backUrl));
      if (backUrl.options) {
        for (let key in backUrl.options) {
          const value = backUrl.options[key]
          backUrl.backUrl += `${key}=${value}&`
        }
      }
      this.setData({
        backUrl: backUrl.backUrl
      })
    }
    this.getTestLoginInfo()
    this.init();
  },
  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },
  onPullDownRefresh() {
    this.init();
  },
  init() {
    this.loadHomePage();
    this.getSubjectList();
    this.getCourseTypeListList();
    this.getBookTypeList();
    this.getReadBookList();
    this.getTextbookListList();
    this.getRankingList();
    this.getShoppingCartList()
  },
  // 获取测试登录时的token
  getTestLoginInfo() {
    const token = wx.getStorageSync(app.config.tokenKey)
    if (!token) {
      wx.login({
        success: (res) => {
          wx.getUserInfo({
            success: (infoRes) => {
              app.MG.identity.checkWeChatAppAccount({
                code: res.code,
                appCode: app.config.appRefCode,
                encryptedData: infoRes.encryptedData,
                iv: infoRes.iv
              }).then(loginRes => {
                if (!loginRes) {
                  // wx.navigateTo({
                  //   url: "/pages/index/bindInfo/index?code=" + res.code,
                  // });
                } else {
                  wx.login({
                    success: (res) => {
                      app.MG.identity.loginByWeChatAppCode({
                        code: res.code,
                        appRefCode: app.config.appRefCode,
                        platform: "weChatApp",
                        encryptedData: infoRes.encryptedData,
                        iv: infoRes.iv
                      }).then(res => {
                        if (res && res.status == "Ok") {
                          wx.setStorageSync(app.config.tokenKey, res.token);
                          setSessionGuid()
                          this.getCurrentUserInfo()
                        }
                      })
                    },
                  })
                }
              })
            }
          })
        },
      })
    }
  },
  getCurrentUserInfo() {
    app.MG.identity.getCurrentAppUser().then(res => {
      console.log(res, "userInfo");
      // 用户信息优先级:教师认证 > 微信 > 学生(注册时默认)
      if (res) {
        let defaultUser = {};
        let WeChatInfo = res.infoList.find((item) => item.type === "WeChat");
        let phoneNumber = res.secretList.find(i => i.type == 'MobilePhone')
        if (WeChatInfo) {
          defaultUser = {
            nickName: WeChatInfo.name,
            avatarUrl: WeChatInfo.icon,
            weChatId: WeChatInfo.id
          }
        }
        if (phoneNumber) {
          defaultUser.phoneNumber = phoneNumber.credential
        }
        this.setData({
          userInfo: defaultUser,
        })
        wx.setStorageSync(app.config.userInfoKey, JSON.stringify(this.data.userInfo));
      }
      if (this.data.backUrl) {
        wx.navigateTo({
          url: this.data.backUrl,
        })
      } else {
        wx.switchTab({
          url: '/pages/home/home'
        })
      }
    });
  },
  getBannerList() {
    const list = []
@@ -69,87 +165,354 @@
    })
    console.log('轮播图', this.data.bannerList);
  },
  loadHomePage() {
    wx.stopPullDownRefresh();
    this.setData({
      pageLoading: true,
    });
    fetchHome().then(({ swiper, tabList }) => {
    fetchHome().then(({ tabList }) => {
      this.setData({
        tabList,
        imgSrcs: swiper,
        pageLoading: false,
      });
      this.loadGoodsList(true);
    });
  },
  tabChangeHandle(e) {
    this.privateData.tabIndex = e.detail;
    this.loadGoodsList(true);
  //点击目录
  toPages(item) {
    let info = item.target.dataset.info
    if (info.url) {
      if (info.text == "图书服务") {
        wx.switchTab({
          url: info.url
        })
      } else {
        wx.navigateTo({
          url: info.url
        })
      }
    } else {
      wx.showToast({
        title: "建设中",
        icon: 'none',
        duration: 2000
      })
    }
  },
  onReTry() {
    this.loadGoodsList();
  },
  async loadGoodsList(fresh = false) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
  //专题讨论
  getSubjectList() {
    const obj = {
      storeInfo: "jsek_seminar",
      path: 'jsek_homepageSeminar',
      coverSize: {
        width: 400
      },
      paging: {
        start: 0,
        size: 4
      },
      fields: {
        liveTime: [],
        lecturer: [],
        startTime: [],
        jsek_link: []
      }
    }
    app.MG.store.getProductList(obj).then((res) => {
      res.datas.forEach((item) => {
        item.liveTime = item.liveTime ? moment(item.liveTime).format("MM-DD HH:mm:ss") : '';
        item.startTime = item.startTime ? moment(item.startTime).format("MM-DD HH:mm:ss") : '';
        item.price = item.price ? item.price.toFixed(2) : item.price;
      });
    }
    this.setData({ goodsListLoadStatus: 1 });
    const pageSize = this.goodListPagination.num;
    let pageIndex = this.privateData.tabIndex * pageSize + this.goodListPagination.index + 1;
    if (fresh) {
      pageIndex = 0;
    }
    try {
      const nextList = await fetchGoodsList(pageIndex, pageSize);
      this.setData({
        goodsList: fresh ? nextList : this.data.goodsList.concat(nextList),
        goodsListLoadStatus: 0,
      });
        specialSubjectList: res.datas
      })
    })
  },
      this.goodListPagination.index = pageIndex;
      this.goodListPagination.num = pageSize;
    } catch (err) {
      this.setData({ goodsListLoadStatus: 3 });
  //精选课程分类
  getCourseTypeListList() {
    const data = {
      path: 'jsek_homepageDigitalCourses',
      filterList: [],
      queryType: '\\',
      searchList: [],
      size: '20',
      start: '0',
      storeRefCode: app.config.digitalCourses,
      sort: { type: 'Asc', field: 'LinkOrder' }
    }
    app.MG.store.getStoreChannelList(data).then((res) => {
      if (res.datas && res.datas.length > 0) {
        let dataList = [];
        dataList.push(...res.datas)
        this.setData({
          courseTypeList: dataList,
          activeItem: 0
        })
        this.getCourseList(res.datas[0])
      }
    })
  },
  //精选课程列表
  getCourseList(item) {
    const obj = {
      storeInfo: "app.config.goodsStore",
      path: item.pathList + '\\' + item.id,
      coverSize: {
        width: 260
      },
      paging: {
        start: 0,
        size: 4
      },
      fields: {
        courseLeader: [],
        affiliatedUnit: [],
        publishingUnit: [],
        classHours: []
      }
    }
    app.MG.store.getProductList(obj).then((res) => {
      res.datas.forEach((item) => {
        item.price = item.price ? item.price.toFixed(2) : item.price;
      });
      this.setData({
        courseList: res.datas
      })
    })
  },
  tabChangeHandle(item) {
    let info = this.data.courseTypeList[item.detail.value]
    this.getCourseList(info)
  },
  //图书服务分类
  getBookTypeList() {
    const data = {
      path: 'jsek_homepageBookService',
      filterList: [],
      queryType: '\\',
      searchList: [],
      size: '20',
      start: '0',
      storeRefCode: app.config.goodsStore,
      sort: { type: 'Asc', field: 'LinkOrder' }
    }
    app.MG.store.getStoreChannelList(data).then((res) => {
      if (res.datas && res.datas.length > 0) {
        let dataList = [];
        dataList.push(...res.datas)
        this.setData({
          bookTypeList: dataList,
          activeItem1: 0
        })
        this.getBooksList(dataList[0])
      }
    })
  },
  //图书服务列表
  getBooksList(item) {
    const obj = {
      storeInfo: app.config.goodsStore,
      path: item.pathList + '\\' + item.id,
      queryType: '*',
      coverSize: {
        width: 150
      },
      paging: {
        start: 0,
        size: 6
      },
      fields: {
        author: []
      }
    }
    app.MG.store.getProductList(obj).then((res) => {
      this.setData({
        booksList: res.datas,
      })
    })
  },
  //图书服务
  tabBookClick(item) {
    let info = this.data.bookTypeList[item.detail.value]
    console.log(info, 123)
    this.getBooksList(info)
  },
  //数字阅读
  getReadBookList() {
    const obj = {
      storeInfo: app.config.digitalTextbooks,
      path: 'jsek_homepageDigitalTextbooks',
      coverSize: {
        width: 150
      },
      paging: {
        start: 0,
        size: 3
      },
      fields: {
        author: []
      }
    }
    app.MG.store.getProductList(obj).then((res) => {
      this.setData({
        readBookList: res.datas
      })
    })
  },
  //数字教材
  getTextbookListList() {
    const obj = {
      storeInfo: app.config.digitalTextbooks,
      path: 'jsek_homepageDigitalTextbooks',
      coverSize: {
        width: 150
      },
      paging: {
        start: 0,
        size: 6
      },
      fields: {
        author: [],
      }
    }
    app.MG.store.getProductList(obj).then((res) => {
      this.setData({
        textbookList: res.datas
      })
    })
  },
  //获取排行榜
  getRankingList() {
    const obj = {
      storeInfo: app.config.goodsStore,
      path: '*',
      queryType: '*',
      coverSize: {
        width: 150
      },
      paging: {
        start: 0,
        size: 10
      },
      fields: {
        author: [],
      },
      filterList: [
        {
          value: 'Normal',
          field: 'state'
        }
      ],
      sort: {
        Name: 'Asc',
        BaseType: ''
  goodListClickHandle(e) {
    const { index } = e.detail;
    const { spuId } = this.data.goodsList[index];
      }
    }
    app.MG.store.getProductList(obj).then((res) => {
      this.setData({
        rankingList: res.datas
      })
    })
  },
  // 跳转图书详情
  goDetail(e) {
    const { book } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${spuId}`,
      url: `/pages/bookServices/detail/index?id=${book.id}&name=${book.name}`,
    });
  },
  getShoppingCartList() {
    let query = {
      start: 0,
      size: 999,
      filterList: [],
      searchList: []
    }
    app.MG.store.getShoppingCartProductList(query).then((res) => {
      let idList = [];
      res.datas.forEach((item) => {
        idList.push(item.saleMethod.id)
      })
      this.setData({
        shoppingCartGetId: idList
      })
    })
  },
  addCart(e) {
    const { info } = e.currentTarget.dataset;
    console.log(info)
    if (wx.getStorageSync(app.config.tokenKey)) {
      let query = {
        start: 0,
        size: 999,
        filterList: [],
        searchList: []
      }
      try {
        if (
          this.data.shoppingCartGetId.includes(
            info.defaultSaleMethodId
          )
        ) {
          wx.showToast({
            title: "该书已在购物车,请勿重复添加空",
            icon: 'none',
            duration: 1000
          })
        } else {
          let query = {
            requests: [
              {
                saleMethodId: info.defaultSaleMethodId,
                storeEventId: null,
                agentCode: '电子书'
              }
            ]
          }
          const addRes = app.MG.store.addShoppingCart(query)
          if (addRes) {
            wx.showToast({
              title: "添加成功",
              icon: 'success',
              duration: 1000
            })
          }
          this.getShoppingCartList()
        }
      } catch (error) {
        console.error('出错了:', error)
      }
    }
  goodListAddCartHandle() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击加入购物车',
    });
  },
  onMoreGuide(e) {
    let type = e.currentTarget.dataset.info
    console.log(e, 1)
    if (type == "tushufuwu") {
      wx.navigateTo({
        url: '/pages/bookServices/list/index'
      })
    } else {
      wx.showToast({
        title: "建设中",
        icon: 'none',
        duration: 2000
      })
    }
  },
  navToSearchPage() {
    wx.navigateTo({ url: '/pages/goods/search/index' });
  },
  navToActivityDetail({ detail }) {
  onPageScroll(e) {
    this.setData({
      isWhite: e.scrollTop > 50 ? true : false
    })
    const data = this.data.bannerList[detail.index]
    console.log('跳转', data.link);
    // const { index: promotionID = 0 } = detail || {};
    // wx.navigateTo({
    //   url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
    // });
  },
  }
});