yiming
2024-03-06 bcd706eeb0c7f9e36ee4803386e52ce2bc0510f6
pages/bookServices/detail/index.js
@@ -1,5 +1,5 @@
// pages/bookServices/detail/index.js
import Message from 'tdesign-miniprogram/message/index';
import Message from 'tdesign-miniprogram/message/index.js';
const app = getApp();
Page({
  /**
@@ -19,8 +19,30 @@
      dang: '',
      micro: '',
    },
    tabValue: 'brief',
    cmsDatas: [], // 资源refCode列表
    ids: [1],
    list: [],
    teachResources: [],
    teach: [],
    learn: [],
    openTeachids: [],
    openLearnids: [],
    resourceClassList: [], // 资源所属分类
    applyState: "",  // 教学资源申请状态
    deadline: "",  // 教学资源申请有效日期
    rejectCause: "",  // 下载拒绝原因
    buyIdList: [],
    shoppingCartGetId: [], // 已购买id列表
    shoppingList: []
  },
  resetTree: function (e) {
    this.setData({
      currentCheck: e.detail.checkedItem,
      list: e.detail.changeList
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
@@ -39,42 +61,49 @@
      },
    });
    this.getBookInfo(options.id);
    this.getResourceClass() // 获取资源所属分类
    this.getApplyInfo(options.id)
    if (wx.getAccountInfoSync('jsek-token')) {
      this.getShoppingCartProductGet()
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},
  onReady() {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  onShow() { },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},
  onHide() { },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},
  onUnload() { },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},
  onPullDownRefresh() { },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},
  onReachBottom() { },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  onShareAppMessage() { },
  // 格式化日期
  formatDate(dateString) {
    if (!dateString) {
@@ -169,8 +198,9 @@
    app.MG.store.getProductDetail(query).then((res) => {
      this.setData({
        bookDetail: res.datas,
        cmsDatas: res.datas.cmsDatas[0].datas,
        buyIdList: res.datas.purchasedSaleMethodIdList
      });
      console.log('详情', res.datas);
      // 获取图书分类
      const iconType = JSON.parse(res.datas.bookClassification)[0][0];
      const classType = JSON.parse(res.datas.bookClassification)[0][1];
@@ -211,12 +241,14 @@
          linkType: 'FavoriteBookCity',
        })
        .then(() => {
          this.data.bookDetail.isFavourite = false;
          this.setData({
            'bookDetail.isFavourite': false
          })
          Message.success({
            context: this,
            offset: ['20rpx', '32rpx'],
            duration: 2000,
            content: '取消收藏',
            offset: [20, 32],
            duration: 5000,
            content: '这是一条成功的提示消息',
          });
        });
    } else {
@@ -225,8 +257,9 @@
        linkType: 'FavoriteBookCity',
      };
      app.MG.store.addProductLink(params).then((res) => {
        console.log(res);
        this.data.bookDetail.isFavourite = true;
        this.setData({
          'bookDetail.isFavourite': true
        })
        Message.success({
          context: this,
          offset: ['20rpx', '32rpx'],
@@ -236,6 +269,11 @@
      });
    }
  },
  // 我要建议
  suggestBtn() {
    const child = this.selectComponent('#suggest-component')
    child.showDialog()
  },
  // 跳转网店
  goShop(e) {
    const { link } = e.currentTarget.dataset;
@@ -243,4 +281,486 @@
      url: link,
    });
  },
});
  onTabsChange(e) {
    this.setData({
      tabValue: e.detail.value
    })
    if (e.detail.label == '教学资源' || e.detail.label == '云学习' || e.detail.label == '云测试') {
      const checkData = this.data.cmsDatas.find(item => item.refCode == e.detail.value)
      if (checkData) {
        if ((e.detail.value == 'jsek_teachingResources' && !this.data.teach.length)
          || (e.detail.value == 'jsek_cloudLearning' && !this.data.learn.length)
          || (e.detail.value == 'questionBank' && !this.data.test.length)) {
          this.getResourceData(checkData)
        }
      }
    }
    console.log('切换', this.data.tabValue);
  },
  // 获取资源所属分类
  getResourceClass() {
    let query = {
      refCodes: ['resourcesClassification']
    }
    app.MG.store.getProductTypeField(query).then((res) => {
      this.setData({
        resourceClassList: JSON.parse(res[0].config).option
      })
    })
  },
  //  获取教学资源  云学习  云测试
  getResourceData(type) {
    let query = {
      path: '*',
      queryType: '*',
      productId: this.data.bookDetail.id,
      cmsPath: type.productLinkPath,
      itemFields: {
        SysType: 'CmsFolder',
        // 资源类型,试读文件,是否允许下载等参数
        selectType: [],
        freeFile: [],
        file: [],
        resourcesClassification: [],
        isDownload: [],
        jsek_resourceBrief: [],
        jsek_link: [],
        jsek_questionBank: []
      },
      pading: {
        start: 0,
        size: 999
      },
    }
    app.MG.store
      .getProductDetail(query)
      .then(async (res) => {
        // 云测试,递归请求里层数据
        if (type.refCode == 'questionBank') {
          const data = res.datas.cmsDatas[0].datas.filter(
            (item) => item.refCode == 'jsek_questionBank'
          )
          if (data.length) return getResourceData(data[0])
        }
        //教学资源 云学习
        if (type.refCode == 'jsek_teachingResources' || type.refCode == 'jsek_cloudLearning') {
          if (res.datas.cmsDatas[0].datas.length > 0) {
            if (type.refCode == 'jsek_teachingResources') {
              res.datas.cmsDatas[0].datas.forEach(item => {
                item.checked = false
              })
              const list = await this.getAllResource(res.datas.cmsDatas[0].datas)
              this.setData({
                teachResources: list,
                teach: list
              })
              this.findChildIds(this.data.teachResources, this.data.openTeachids = [])
            } else if (type.refCode == 'jsek_cloudLearning') {
              const list = await this.getAllResource(res.datas.cmsDatas[0].datas)
              this.setData({
                learn: list
              })
              console.log('云学习', this.data.learn);
              this.findChildIds(this.data.teachResources, this.data.openLearnids = [])
            }
          } else {
            // 无数据
          }
        } else if (type.refCode == 'jsek_questionBank') {
          console.log('云测试');
        } else {
          console.log('其他');
        }
      })
      .catch((e) => {
        console.log(e)
      })
    console.log('信息', this.data);
  },
  // 获取tag下所有资源
  async getAllResource(data) {
    if (!data.length) return false
    for (let i = 0; i < data.length; i++) {
      let item = data[i]
      if (item.sysType == 'CmsFolder' && item.childrenCount > 0) {
        item.children = []
        item.children = await this.getFolderItem(item.productLinkPath)
        await this.getAllResource(item.children)
      }
    }
    return data
  },
  // 获取资源接口
  async getFolderItem(path) {
    let query = {
      path: '*',
      queryType: '*',
      productId: this.data.bookDetail.id,
      cmsPath: path,
      itemFields: {
        SysType: 'CmsFolder',
        // 资源类型,试读文件,是否允许下载等参数
        selectType: [],
        freeFile: [],
        file: [],
        protectedFile: [],
        resourcesClassification: [],
        isDownload: [],
        jsek_resourceBrief: [],
        jsek_link: [],
        accessType: []
      },
      pading: {
        start: 0,
        size: 999
      },
    }
    const data = await app.MG.store.getProductDetail(query)
    data.datas.cmsDatas[0].datas.forEach((item) => {
      this.data.resourceClassList.forEach((type) => {
        if (type.value == item.resourcesClassification) item.resourceClass = type.name
      })
      // 网页 不能下载 私有文件
      if (item.sysType == 'CmsItem') {
        if (item.selectType == 'webpage') {
          item.disabled = true
        } else {
          if (item.isDownload != 1) {
            item.disabled = true
          }
        }
        if (item.file) {
          if (item.fileMap[item.file].protectType == 'Private') item.disabled = true
        }
      }
    })
    data.datas.cmsDatas[0].datas.forEach(item => {
      if (this.data.tabValue == 'jsek_teachingResources') {
        item.checked = false
      } else if (this.data.tabValue == 'jsek_cloudLearning') {
        item.isbuy = this.resourceIsBuy(item)
        item.isShopCar = this.isShoppingCart(item)
      }
    })
    return data.datas.cmsDatas[0].datas
  },
  // 获取展开项
  findChildIds(data, result) {
    let index = 0
    for (let i = 0; i < data.length; i++) {
      if (index < 3) {
        const item = data[i]
        if (item.childrenFolderCount > 0) {
          result.push(item.id)
          for (let j = 0; j < item.children.length; j++) {
            if (index < 3) {
              const childrenItme = item.children[j]
              if (item.childrenCount > 0) {
                result.push(childrenItme.id)
                index += 1
              }
            } else {
              break
            }
          }
        } else if (item.childrenCount > 0) {
          result.push(item.id)
          index += 1
        }
      } else {
        break
      }
    }
  },
  // 图书添加购物车
  addBookShopcCar() {
    let query = {
      requests: [
        {
          saleMethodId: this.data.bookDetail.defaultSaleMethodId,
          storeEventId: null,
          agentCode: '电子书'
        }
      ]
    }
    const addRes = app.MG.store.addShoppingCart(query)
  },
  // 获取教学资源下载是否申请通过
  getApplyInfo(id) {
    // 获取当前时间
    const currentDate = new Date()
    let query = {
      sort: {
        type: 'Desc',
        field: 'CreateDate'
      },
      start: 0,
      size: 99999,
      appRefCode: app.config.appRefCode,
      topicIdOrRefCode: 'productDownLoad'
    }
    app.MG.ugc.getTopicMessageList(query).then((res) => {
      const applyResource = res.datas.find((item) => {
        let content = []
        try {
          content = JSON.parse(item.content)
        } catch (error) {
          content = []
        }
        if (Array.isArray(content)) return content.find((citem) => citem.id == id)
        return false
      })
      // 有申请记录
      if (applyResource) {
        if (applyResource.state == 'Reject') {
          this.setData({
            rejectCause: JSON.parse(applyResource.feedBack).reason,
            applyState: 'Reject'
          })
        } else if (applyResource.state == 'Normal') {
          const endDate = JSON.parse(applyResource.feedBack).endDate
          // const endDate = new Date(JSON.parse(applyResource.feedBack).endDate + ' 23:59:59').getTime()
          if (endDate == '永久') {
            // deadline.value = '永久'
            this.setData({
              applyState: 'Normal',
              deadline: '永久',
            })
          } else {
            let endTime = new Date(endDate + ' 23:59:59').getTime()
            // deadline.value = endDate + ' 23:59:59'
            this.setData({
              deadline: endDate + ' 23:59:59'
            })
            if (currentDate.getTime() < endTime) {
              // 未超时
              this.setData({
                applyState: 'Normal'
              })
            } else {
              this.setData({
                applyState: 'none'
              })
            }
          }
        } else {
          this.setData({
            applyState: applyResource.state
          })
        }
      } else {
        this.setData({
          applyState: 'none'
        })
      }
      console.log('申请通过', this.data.applyState);
    })
  },
  // 申请教学资源
  applyResource() {
    // let role = userStore.userInfo ? userStore.userInfo.role : null
    // if (role) {
    //   if (role == 'Teacher') {
    // 申请教学资源
    let query = {
      topicIdOrRefCode: 'productDownLoad',
      type: 'applyForDownload',
      state: 'WaitAudit',
      cmsTypeRefCode: '',
      newDataListRequest: [],
      name: this.data.bookDetail.name, // name为申请的书本名称
      content: JSON.stringify([
        {
          name: this.data.bookDetail.name,
          id: this.data.bookDetail.id,
          // defaultSaleMethodId: bookData.value.defaultSaleMethodId,
          icon: this.data.bookDetail.icon
        }
      ])
    }
    app.MG.ugc.newTopicMessage(query).then((res) => {
      if (res) {
        Message.success('申请已提交,请待审核通过后下载')
      }
      this.getApplyInfo(this.data.bookDetail.id)
    })
    //   } else {
    //     ElMessageBox.confirm('请先进行教师认证!', '尊敬的用户,您好!', {
    //       confirmButtonText: '去认证',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     })
    //       .then(() => {
    //         isShow.value = true
    //       })
    //       .catch(() => { })
    //   }
    // } else {
    //   // logIn()
    // }
  },
  downloadTeach(e) {
    const data = e.detail.value
    // const data
    // let role = userStore.userInfo ? userStore.userInfo.role : null
    // if (role) {
    //   if (role == 'Teacher') {
    if (this.properties.applyState == 'Normal' || this.properties.applyState == 'none') {
      // 是否允许下载
      if (data.isDownload == 1) {
        // 申请通过
        let url = app.config.requestCtx + '/file/api/ApiDownloadForAuthorize?md5='
        if (data.file) {
          // 判断是否私有
          if (data.fileMap[data.file].protectType == 'Private')
            return Message.error({
              context: this,
              offset: ['20rpx', '32rpx'],
              duration: 5000,
              content: '该文件无法下载'
            })
          url = url + data.file + '&token=' + wx.getStorageSync('jsek-token')
        } else if (data.freeFile) {
          url = url + data.freeFile + '&token=' + wx.getStorageSync('jsek-token')
        } else {
          Message.error({
            context: this,
            offset: ['20rpx', '32rpx'],
            duration: 5000,
            content: '暂无资源',
          })
        }
        this.downloadFile(url)
      } else {
        Message.error({
          context: this,
          offset: ['20rpx', '32rpx'],
          duration: 5000,
          content: '该资源无法下载',
        })
      }
    } else if (this.properties.applyState == 'WaitAudit') {
      // ElMessageBox.confirm('请先申请下载!', '尊敬的用户,您好!', {
      //   confirmButtonText: '申请',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => applyBookInfo())
      //   .catch()
      Message.error({
        context: this,
        offset: ['20rpx', '32rpx'],
        duration: 5000,
        content: '该资源下载申请审核中',
      })
    } else if (this.properties.applyState == 'Reject') {
      Message.error({
        context: this,
        offset: ['20rpx', '32rpx'],
        duration: 5000,
        content: '资源下载申请未通过'
      })
    } else {
      // Message.error({
      //   context: this,
      //   offset: ['20rpx', '32rpx'],
      //   duration: 5000,
      //   content: '请先申请下载'
      // })
      console.log('请先申请下载');
    }
    //   } else {
    //     ElMessageBox.confirm('请先进行教师认证!', '尊敬的用户,您好!', {
    //       confirmButtonText: '去认证',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     })
    //       .then(() => {
    //         isShow.value = true
    //       })
    //       .catch(() => { })
    //   }
    // } else {
    //   logIn()
    // }
  },
  downloadFile(url) {
    wx.downloadFile({
      url: url,
      success: function (res) {
        // 下载成功后,调用saveImageToPhotosAlbum函数保存图片到本地
        wx.saveFile({
          tempFilePath: res.tempFilePath,
          success: function (res) {
            wx.showToast({
              title: '下载成功',
              icon: 'success'
            })
          },
          fail: function (res) {
            wx.showToast({
              title: '下载失败',
              icon: 'none'
            })
          }
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        })
      }
    })
  },
  // 判断资源是否购买
  resourceIsBuy(data) {
    if (data.saleMethod && data.saleMethod.length) {
      const isSHow = this.data.buyIdList.some((item) => item == data.saleMethod[0].Id)
      return !isSHow
    } else {
      return false
    }
  },
  getShoppingCartProductGet() {
    let query = {
      start: 0,
      size: 999,
      filterList: [],
      searchList: []
    }
    app.MG.store.getShoppingCartProductList(query).then((res) => {
      const list = []
      res.datas.forEach((item) => {
        list.push(item.saleMethod.id)
      })
      this.setData({
        shoppingList: res.datas,
        shoppingCartGetId: list
      })
      console.log('购买', this.data);
    })
  },
  // 判断资源加入购物车按钮是否显示
  isShoppingCart(data) {
    if (data.saleMethod && data.saleMethod.length) {
      if (data.saleMethod[0].Price <= 0) return false
      // 再判断是否购买
      const isBuy = this.data.buyIdList.some((item) => item == data.saleMethod[0].Id)
      if (isBuy) {
        // 购买了
        return false
      } else {
        // 判断是否加入购物车
        const isSHow = this.data.shoppingCartGetId.some((item) => item == data.saleMethod[0].Id)
        return !isSHow
      }
    } else {
      return false
    }
  }
})