litian
2024-06-26 ccda9ec2fe70d8f51ef184eafc04b78d22dfbabd
pages/digitalTextbooks/digitalTextbooksDetails/index.js
@@ -1,10 +1,61 @@
// pages/digitalTextbooks/digitalTextbooksDetails/index.js
import Toast from "tdesign-miniprogram/toast";
import {
  loginInfo
} from '../../../assets/js/login';
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    type: 'basicInformation',
    digitalTextId: '',
    digitalsData: {},
    expire: false, //商品或子商品销售方式是否过期
    tabValue: "brief",
    relatedBookData: [],
    publicationDate: '',
    isBuy: false,
    loading: true,
    briefIcon: {
      name: "/static/images/digitalTextbooks/jibenxinxi-t@2x.png",
    },
    briefIconClick: {
      name: "/static/images/digitalTextbooks/jibenxinxi-t-click@3x.png",
    },
    eBookIcon: {
      name: "/static/images/digitalTextbooks/zuozhejianjie-t@2x.png",
    },
    eBookClickIcon: {
      name: "/static/images/digitalTextbooks/zuozhejianjie@2x.png",
    },
    teachResourcesIcon: {
      name: "/static/images/digitalTextbooks/zuozhejianjie-t@2x.png",
    },
    teachResourcesClickIcon: {
      name: "/static/images/digitalTextbooks/zuozhejianjie-t-click@3x.png",
    },
    learnResourceIcon: {
      name: "/static/images/digitalTextbooks/shengshu-t@2x.png",
    },
    learnResourceClickIcon: {
      name: "/static/images/digitalTextbooks/zhengshu-t-click@3x.png",
    },
    testResourceIocn: {
      name: "/static/images/digitalTextbooks/link-t@3x.png",
    },
    testResourceClickIocn: {
      name: "/static/images/digitalTextbooks/link-t-click@3x.png",
    },
    catalogue: {
      name: "/static/images/digitalTextbooks/mulu-t@3x.png",
    },
    catalogueClickIcon: {
      name: "/static/images/digitalTextbooks/mulu-t-click@3x.png",
    },
  },
@@ -12,9 +63,60 @@
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options.id);
    console.log(options);
    this.setData({
      digitalTextId: options.id
    })
    this.digitalTextbooksDetailsGet(this.data.digitalTextId)
  },
  // 格式化日期
  // 格式化日期
  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];
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
@@ -40,7 +142,9 @@
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.setData({
      digitalsData: {}
    })
  },
  /**
@@ -62,5 +166,476 @@
   */
  onShareAppMessage() {
  }
  },
  digitalTextbooksDetailsGet(digitalId) {
    let query = {
      path: '*',
      queryType: '*',
      productId: digitalId,
      storeInfo: 'jsek_digitalTextbooks',
      coverSize: {
        height: 300
      },
      fields: {
        seriesName: [],
        author: [],
        isbn: [],
        publicationDate: [],
        bookClassification: [],
        paperPrice: [],
        JDLink: [],
        tmallLink: [],
        dangdangLink: [],
        weidianLink: [],
        content: [],
        authorIntroduction: [],
        isApplyBook: [],
        isSell: [],
        pdf: [],
        protectedEpub: [],
        probationPage: [], //pdf试读页数
        freeEpubPage: [],
        catalogue: []
        //epub试读百分比
      }
    }
    app.MG.store.getProductDetail(query).then(res => {
      if (res.datas.purchasedSaleMethodIdList.includes(res.datas.defaultSaleMethodId)) {
        this.setData({
          isBuy: true
        })
      } else {
        this.setData({
          isBuy: false
        })
      }
      // res.datas.publicationDate =
      if (res.datas.icon == '') {
        res.datas.icon = '/static/images/default-book-img.png'
      }
      this.setData({
        publicationDate: this.formatDate(res.datas.publicationDate)
      })
      res.datas.price = res.datas.price.toFixed(2)
      this.setData({
        digitalsData: res.datas
      })
      let times = new Date(res.datas.defaultSaleMethod.endDate).getTime()
      let startTime = new Date(res.datas.defaultSaleMethod.beginDate).getTime()
      if (times < new Date().getTime() || new Date().getTime() < startTime) {
        this.setData({
          expire: true
        })
      } else {
        this.setData({
          expire: res.false
        })
      }
      wx.setNavigationBarTitle({
        title: res.datas.name,
      })
      this.getAboutBook(res.datas.productLinkInfo[res.datas.productLinkInfo.length - 1].LinkPath)
      console.log(this.data.isBuy);
      this.setData({
        loading: false,
        type: 'basicInformation',
      });
      // this.onCe()
    })
  },
  onTabsChange(event) {
    this.setData({
      tabValue: event.detail.value,
    })
    console.log(this.data.tabValue);
  },
  onTabsClick(event) {
    // console.log(`Click tab, tab-panel value is ${event.detail.value}.`);
  },
  // 获取相关教材
  getAboutBook(path) {
    let query = {
      path,
      queryType: '*',
      coverSize: {
        height: 243
      },
      paging: {
        start: 0,
        size: 99
      },
      fields: {
        author: [],
        publicationDate: []
      }
    }
    app.MG.store.getProductList(query).then(res => {
      const Arr = res.datas.filter(
        (item) => item.id != this.data.digitalsData.id
      );
      let bookArr = []
      if (Arr.length) {
        if (Arr.length > 9) {
          for (var i = 0; i < 9; i++) {
            var _num = Math.floor(Math.random() * Arr.length)
            var mm = Arr[_num]
            Arr.splice(_num, 1)
            bookArr.push(mm)
          }
        } else {
          bookArr = Arr
        }
        bookArr.forEach(item => {
          if (item.icon == '') {
            item.icon = '/static/images/default-book-img.png'
          }
        })
        this.setData({
          relatedBookData: bookArr
        })
        console.log(this.data.relatedBookData);
      } else {
        this.setData({
          relatedBookData: []
        })
      }
    })
  },
  onCorrelationBook(e) {
    const item = e.currentTarget.dataset.item
    // const event = {
    //   detail: {
    //     value: "brief"
    //   }
    // }
    // this.onTabsChange(event)
    // this.digitalTextbooksDetailsGet(item.id)
    this.onLoad({
      id: item.id
    })
  },
  // 图书添加购物车
  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,
      });
    }
  },
  // console.log(item, app.config.textReaderUrl);
  // console.log(token);
  goRead() {
    // 首页测试登录功能,后续注释
    // 检查登录状态
    const token = wx.getStorageSync(app.config.tokenKey)
    if (!token) {
      loginInfo(app, (data) => {
        // 如果不是第一次登录,会执行回调
        if (data) {
          // 登录成功,自动记录token和用户信息,并返回true
          const item = this.data.digitalsData
          wx.navigateTo({
            url: '/pages/digitalTextbooks/digitalTextbooksDetails/components/webView/index?refCode=' + item.refCode + "&tryPageCount=" + item.probationPage
          });
        } else {
          // 出现错误,返回false
        }
      })
    } else {
      // 如果是第一次登录,会跳转至绑定用户信息页面,填写完用户信息后进行登录并储存token和用户信息,结束后跳转回当前页面(携带页面参数)
      const item = this.data.digitalsData
      wx.navigateTo({
        url: '/pages/digitalTextbooks/digitalTextbooksDetails/components/webView/index?refCode=' + item.refCode + "&tryPageCount=" + item.probationPage
      });
    }
    // let token = wx.getStorageSync(app.config.tokenKey)
    // if (token) {
    // }
  },
  onTabClick(e) {
    // debugger
    console.log(e);
    let tab = e.currentTarget.dataset.tab;
    this.setData({
      type: tab,
    })
    if (tab == 'basicInformation') {
      this.setData({
        topPos: 0
      })
    } else if (tab == 'certificateInformation') {
      this.setData({
        topPos: this.certificateInformation
      })
    } else if (tab == 'authorSynopsis') {
      this.setData({
        topPos: this.authorSynopsis
      })
    } else if (tab == 'listings') {
      this.setData({
        topPos: this.listings
      })
    } else if (tab == 'relatedTextbooks') {
      this.setData({
        topPos: this.relatedTextbooks
      })
    }
  },
  onScroll(e) {
    let scrollTop = e.detail.scrollTop
    console.log(scrollTop);
    // this.setData({
    //   type: scrollTop
    // })
    if (scrollTop < this.basicInformation) {
      this.setData({
        type: 'basicInformation'
      })
    } else if (scrollTop >= this.basicInformation && scrollTop < this.certificateInformation) {
      this.setData({
        type: 'certificateInformation'
      })
    } else if (scrollTop >= this.certificateInformation && scrollTop < this.authorSynopsis) {
      this.setData({
        type: 'authorSynopsis'
      })
    } else if (scrollTop >= this.authorSynopsis && scrollTop < this.listings) {
      this.setData({
        type: 'listings'
      })
    } else if (scrollTop >= this.listings && scrollTop < this.relatedTextbooks) {
      this.setData({
        type: 'relatedTextbooks'
      })
    }
  },
  onCe() {
    let that = this;
    var query = wx.createSelectorQuery()
    console.log(query, '12355');
    //获取板块一离scroll-view顶部的距离,第一板块实际距离为0,此处获取只为给第二及第三板块减去第一板块距离scroll-view的顶部距离
    wx.createSelectorQuery().select('#basicInformation').boundingClientRect(function (res) {
      console.log(res, '456882588');
      that.basicInformation = res.top
    }).exec()
    //获取板块二离scroll-view顶部的距离
    query.select('#certificateInformation').boundingClientRect(function (res) {
      that.certificateInformation = res.top - that.basicInformation
    }).exec()
    //获取板块三离scroll-view顶部的距离
    query.select('#authorSynopsis').boundingClientRect(function (res) {
      that.authorSynopsis = res.top - that.basicInformation
    }).exec()
    //获取板块四离scroll-view顶部的距离
    query.select('#listings').boundingClientRect(function (res) {
      that.listings = res.top - that.basicInformation
    }).exec()
    //获取板块五离scroll-view顶部的距离
    query.select('#relatedTextbooks').boundingClientRect(function (res) {
      that.relatedTextbooks = res.top - that.basicInformation
    }).exec()
  },
  setCoolect() {
    console.log(456);
    // 首页测试登录功能,后续注释
    // 检查登录状态
    const token = wx.getStorageSync(app.config.tokenKey)
    if (!token) {
      loginInfo(app, (data) => {
        // 如果不是第一次登录,会执行回调
        if (data) {
          if (this.data.digitalsData.isFavourite) {
            app.MG.store
              .delProductLink({
                productIds: [this.data.digitalsData.id],
                linkType: 'FavoriteBookCity'
              })
              .then(() => {
                this.setData({
                  "digitalsData.isFavourite": false
                })
              })
          } else {
            let params = {
              productIds: [this.data.digitalsData.id],
              linkType: 'FavoriteBookCity'
            }
            app.MG.store.addProductLink(params).then((res) => {
              this.setData({
                "digitalsData.isFavourite": true
              })
            })
          }
        } else {
          // 出现错误,返回false
        }
      })
    } else {
      if (this.data.digitalsData.isFavourite) {
        app.MG.store
          .delProductLink({
            productIds: [this.data.digitalsData.id],
            linkType: 'FavoriteBookCity'
          })
          .then(() => {
            this.setData({
              "digitalsData.isFavourite": false
            })
          })
      } else {
        let params = {
          productIds: [this.data.digitalsData.id],
          linkType: 'FavoriteBookCity'
        }
        app.MG.store.addProductLink(params).then((res) => {
          this.setData({
            "digitalsData.isFavourite": true
          })
        })
      }
    }
  },
  // 我要建议
  suggestBtn() {
    // 检查登录状态
    const token = wx.getStorageSync(app.config.tokenKey);
    console.log(465);
    const child = this.selectComponent("#suggest-component");
    // if (token)
    //   // child.showDialog();
    //   this.setData({
    //     showIndex: '1'
    //   })
  },
})