yiming
2024-06-18 4c46ea24641b5c1e18c55eb86477d0e0bc444580
pages/digitalCourses/digitalCoursesDetails/index.js
@@ -1,18 +1,104 @@
// pages/digitalCourses/digitalCoursesDetails/index.js
const app = getApp()
import Toast from "tdesign-miniprogram/toast";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    scrollJudge: true,
    loading: true,
    digitalsData: [],
    tabValue: 0,
    learnResourceIcon: {
      name: "/static/images/digitalTextbooks/shengshu-t@2x.png",
    },
    learnResourceClickIcon: {
      name: "/static/images/digitalTextbooks/zhengshu-t-click@3x.png",
    },
    briefIcon: {
      name: "/static/images/digitalTextbooks/jibenxinxi-t@2x.png",
    },
    briefIconClick: {
      name: "/static/images/digitalTextbooks/jibenxinxi-t-click@3x.png",
    },
    courseLearning: {
      name: "/static/images/digitalCourses/jiaoxueziyuan@2x.png"
    },
    courseLearningClick: {
      name: "/static/images/digitalCourses/jiaoxueziyuan.png"
    },
    learningNotes: {
      name: "/static/images/digitalCourses/biji/icon@2x.png"
    },
    learningNotesClick: {
      name: "/static/images/bookService/detail/biji-click-icon.png",
    },
    onlineQuestioning: {
      name: "/static/images/digitalCourses/tiwen@2x.png"
    },
    onlineQuestioningClick: {
      name: "/static/images/digitalCourses/tiwen-click@2x.png"
    },
    dialogBox: false
  },
  formatDate(dateString) {
    if (!dateString) {
      return "";
    }
    const match = dateString.match(
      /^(\d{4})\/(\d{1,2})\/(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/
    );
    if (!match) {
      throw new Error("Invalid date format");
    }
    const [, year, month, day, hours, minutes, seconds] = match;
    const date = new Date(
      parseInt(year, 10),
      parseInt(month, 10) - 1,
      parseInt(day, 10),
      parseInt(hours, 10),
      parseInt(minutes, 10),
      parseInt(seconds, 10)
    );
    if (isNaN(date.getTime())) {
      throw new Error("Invalid date");
    }
    // 由于小程序环境可能不支持 Intl.DateTimeFormat,我们使用简化的格式化方法
    const formatted = `${year}年${this.formatMonth(month)}`;
    return formatted;
  },
  formatMonth(month) {
    const months = [
      "1月",
      "2月",
      "3月",
      "4月",
      "5月",
      "6月",
      "7月",
      "8月",
      "9月",
      "10月",
      "11月",
      "12月",
    ];
    return months[parseInt(month, 10) - 1];
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    this.digitalCoursesDetailsGet(options.id)
  },
  /**
@@ -62,5 +148,216 @@
   */
  onShareAppMessage() {
  },
  digitalCoursesDetailsGet(digitalTextId) {
    let query = {
      path: '*',
      queryType: '*',
      productId: digitalTextId,
      storeInfo: 'jsek_digitalCourses',
      coverSize: {
        height: 300
      },
      fields: {
        seriesName: [],
        author: [],
        isbn: [],
        publicationDate: [],
        bookClassification: [],
        paperPrice: [],
        JDLink: [],
        tmallLink: [],
        dangdangLink: [],
        weidianLink: [],
        content: [],
        authorIntroduction: [],
        isApplyBook: [],
        isSell: [],
        pdf: [],
        protectedEpub: [],
        probationPage: [], //pdf试读页数
        freeEpubPage: [],
        courseLeader: [],
        affiliatedUnit: [],
        publishingUnit: [],
        classHours: [],
        productLinkPath: []
        //epub试读百分比
      }
    }
    app.MG.store.getProductDetail(query).then(res => {
      console.log(res);
      res.datas.publicationDate = this.formatDate(res.datas.publicationDate)
      res.datas.price = res.datas.price.toFixed(2)
      wx.setNavigationBarTitle({
        title: res.datas.name,
      })
      this.setData({
        digitalsData: res.datas,
        loading: false
      })
    })
  },
  onTabsChange(event) {
    const value = event.detail.value
    this.setData({
      tabValue: value
    })
    console.log(this.data.tabValue);
  },
  // 图书添加购物车
  async addBookShopcCar() {
    if (!this.data.expire) {
      const shoppingCartGetId = [];
      let query = {
        start: 0,
        size: 9999,
        filterList: [],
        searchList: [],
      };
      const res = await app.MG.store.getShoppingCartProductList(query);
      res.datas.forEach((item) => {
        shoppingCartGetId.push(item.saleMethod.id);
      });
      const determine = shoppingCartGetId.some(
        (item) => item == this.data.digitalsData.defaultSaleMethodId
      );
      if (!determine) {
        let query = {
          requests: [{
            saleMethodId: this.data.digitalsData.defaultSaleMethodId,
            storeEventId: null,
            agentCode: "电子书",
          }, ],
        };
        const addRes = app.MG.store.addShoppingCart(query);
        this.showSuccessToast();
      } else {
        Toast({
          context: this,
          selector: "#t-toast",
          message: "该书已在购物车,请勿重复添加",
          theme: "warning",
          direction: "column",
        });
      }
    } else {
      wx.showToast({
        title: "商品不在有效期",
        icon: "none",
        duration: 1000,
      });
    }
  },
  showSuccessToast() {
    Toast({
      context: this,
      selector: "#t-toast",
      message: "添加成功",
      theme: "success",
      direction: "column",
    });
  },
  //购买按钮
  async buyBtn() {
    if (!this.data.expire) {
      let bookOrdersId = "";
      let query = {
        remarks: "电子书",
        requests: [{
          saleMethodId: this.data.digitalsData.defaultSaleMethodId,
          count: 1,
        }, ],
      };
      // 发起订单初始化请求并等待结果
      const res = await app.MG.store.initOrder(query);
      // 获取订单号并赋值给 orderNumber.value
      console.log(res, 'res456');
      bookOrdersId = res.orderNumber;
      // 检查订单号是否存在
      if (bookOrdersId) {
        if (this.data.digitalsData.price == "0.00") {
          app.MG.store
            .confirmOrder({
              orderNum: bookOrdersId,
            })
            .then((res) => {
              this.digitalTextbooksDetailsGet(this.data.digitalTextId)
              if (res) {
                wx.showToast({
                  title: "领取成功",
                  icon: "none",
                  duration: 1000,
                });
                this.getBookInfo(this.data.bookDetail.id);
              }
            });
        } else {
          const url = "/pages/cart/paymentPage/index?orderNumber=" + bookOrdersId + '&onNorderSaleMethod=' + res.saleMethodLinks[0].orderSaleMethod.id;
          wx.navigateTo({
            url,
          });
        }
      } else {
        console.log(222);
      }
    } else {
      wx.showToast({
        title: "商品不在有效期",
        icon: "none",
        duration: 1000,
      });
    }
  },
  showDialog(e) {
    const {
      key
    } = e.currentTarget.dataset;
    this.setData({
      [key]: true,
      dialogKey: key
    });
  },
  closeDialog() {
    const {
      dialogKey
    } = this.data;
    this.setData({
      [dialogKey]: false
    });
  },
  onCertificate() {
    var page = getCurrentPages().pop(); // 获取当前页面实例
    page.setData({
      // 动态设置禁止滚动的样式
      disableScrollStyle: 'overflow: hidden;'
    });
    this.setData({
      dialogBox: true,
      scrollJudge: ''
    })
  },
  closeDialog() {
    this.setData({
      dialogBox: false,
      scrollJudge: true
    })
  },
  confirmM() {
    this.setData({
      dialogBox: false,
      scrollJudge: true
    })
  }
})