闫增涛
2024-04-29 558845242a07b68f42fa1802c45ab2769395d8b8
packageBookService/pages/bookServices/detail/buyResource/index.js
@@ -10,19 +10,24 @@
    learn: [],
    openLearnids: [],
    bookId: "",
    loading: false,
    loading: true,
    shoppingList: [],
    shoppingCartGetId: [],
    methodId: [],
    paymentPage: false,
    superior: false,
    checkAllState: false,
    checkAllState: true,
    productLinkPath: '',
    refCode: '',
    haider: false,
    naData: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getBookInfo(options.bookId);
    const systInfo = wx.getSystemInfoSync();
    const menu = wx.getMenuButtonBoundingClientRect(); // 胶囊信息
    const navBarHeight =
@@ -31,15 +36,11 @@
      barHeight: systInfo.statusBarHeight,
      navBarHeight: navBarHeight,
      bookId: options.bookId,
      productLinkPath: options.productLinkPath,
      refCode: options.refCode
    });
    this.getResourceClass();
    console.log(options);
    this.getResourceData({
      productLinkPath: options.productLinkPath,
      refCode: options.refCode,
    });
    this.getShoppingCartProductGet();
    this.getBookInfo(options.bookId);
  },
  /**
@@ -84,6 +85,245 @@
  goBack() {
    wx.navigateBack();
  },
  // 获取所有子项数量
  getChildrenItem(data) {
    let num = 0
    function getNum(data) {
      for (let index = 0; index < data.length; index++) {
        const item = data[index];
        if (item.sysType == 'CmsItem') {
          num += 1
        } else if (item.sysType == 'CmsFolder') {
          if (item.children && item.children.length)
            getNum(item.children)
        }
      }
    }
    getNum(data)
    return num
  },
  // 给·目录添加子项数量
  changeResourceChildren(list) {
    const changeList = (list) => {
      for (let index = 0; index < list.length; index++) {
        const item = list[index];
        if (item.sysType == 'CmsFolder' && item.children && item.children.length) {
          item.childrenItem = this.getChildrenItem([item])
          changeList(item.children)
        } else if (item.sysType == 'CmsFolder' && item.children && !item.children.length) {
          item.childrenItem = 0
        } else if (item.sysType == 'CmsFolder' && !item.children) {
          item.childrenItem = 0
        }
      }
    }
    changeList(list)
    return list
  },
  // 扁平化数据转换tree
  getTreeList(rootList, pathLength, newArr, path) {
    for (const item of rootList) {
      if ((pathLength - item.productLinkPath.length >= 0 && pathLength - item.productLinkPath.length <= 3) && item.productLinkPath.includes(path)) {
        if (item.sysType == 'CmsItem') {
          if (item.selectType == 'webpage') {
            item.disabled = true
          } else {
            if (item.isDownload != 1) {
              item.disabled = true
            }
          }
          if (item.file && item.fileMap && item.fileMap[item.file]) {
            if (item.fileMap[item.file].protectType == 'Private') item.disabled = true
          }
        }
        // newArr.push(item)
        // 在插入过程中对数据进行排序  并且去除已经领取和购买的
        if (item.sysType == 'CmsFolder') {
          newArr = this.insertAndSortObjectsByProductLinkPath(newArr, item)
        } else if (item.sysType == 'CmsItem' && this.resourceIsBuy(item)) {
          newArr = this.insertAndSortObjectsByProductLinkPath(newArr, item)
        }
      }
    }
    //给数组里面再添加一个children的空数组
    for (const i of newArr) {
      i.children = []
      this.getTreeList(rootList, pathLength + 6, i.children, i.productLinkPath)
      if (i.children.length == 0) {
        delete i.children
      }
    }
    return newArr
  },
  // 去除树结构多余项
  ensureTreeConsistency(tree) {
    for (let index = 0; index < tree.length; index++) {
      const item = tree[index];
      if (item.children && item.children.length) {
        const isFloder = item.children.findIndex(citem => citem.sysType == 'CmsFolder')
        const isItem = item.children.findIndex(citem => citem.sysType == 'CmsItem')
        if (isFloder > -1 && isItem > -1) {
          item.children = item.children.filter(ditem => ditem.sysType == 'CmsItem')
        }
        this.ensureTreeConsistency(item.children)
      }
    }
    return tree
  },
  // 排序数组 按照productLinkPath
  insertAndSortObjectsByProductLinkPath(array, newObj) {
    // 查找新对象应该插入的位置
    let insertIndex = array.findIndex(obj => Number(newObj.productLinkPath.substring(newObj.productLinkPath.length - 6, newObj.productLinkPath.length)) < Number(obj.productLinkPath.substring(obj.productLinkPath.length - 6, obj.productLinkPath.length)));
    // 如果没有找到合适的位置,则放在数组末尾
    if (insertIndex === -1) {
      insertIndex = array.length;
    }
    // 插入新对象到数组
    array.splice(insertIndex, 0, newObj);
    // 测试6 正式5
    // 对数组进行排序
    array.sort((a, b) => {
      if (Number(a.productLinkPath.substring(a.productLinkPath.length - 5, a.productLinkPath.length)) < Number(b.productLinkPath.substring(b.productLinkPath.length - 5, b.productLinkPath.length))) {
        return -1;
      }
      if (Number(a.productLinkPath.substring(a.productLinkPath.length - 5, a.productLinkPath.length)) > Number(b.productLinkPath.substring(b.productLinkPath.length - 5, b.productLinkPath.length))) {
        return 1;
      }
      // a must be equal to b
      return 0;
    });
    // 返回更新后的数组
    return array;
  },
  // 遍历树结构转换为数组方法
  handleTreeData(array) {
    const flattenedArray = [];
    array.forEach((node) => {
      // 将当前节点添加到展开的数组中
      flattenedArray.push(node);
      // 递归处理子节点
      if (node.children && node.children.length > 0) {
        const childrenArray = this.handleTreeData(node.children);
        flattenedArray.push(...childrenArray);
      }
    });
    return flattenedArray.filter((item) => item.sysType == "CmsItem");
  },
  // 教学资源 云学习 获取
  getResourceDataList(type) {
    this.setData({
      loading: true,
      noResources: false,
    });
    let query = {
      path: '*',
      queryType: '*',
      productId: this.data.bookDetail.id,
      cmsPath: type.productLinkPath,
      cmsType: '*',
      itemFields: {
        SysType: 'CmsFolder',
        // 资源类型,试读文件,是否允许下载等参数
        selectType: [],
        freeFile: [],
        file: [],
        protectedFile: [],
        resourcesClassification: [],
        isDownload: [],
        jsek_resourceBrief: [],
        jsek_link: [],
        jsek_questionBank: []
      },
      pading: {
        start: 0,
        size: 999
      },
    }
    app.MG.store.getProductDetail(query).then((res) => {
      if (!res.datas.cmsDatas[0].datas.length) {
        return this.setData({
          noResources: true,
          loading: false,
          haider: true,
        });
      }
      let list = []
      // 测试 6位// 正式 5位//  测试调用传20,内部7  正式调用传17 内部传6
      //教学资源 云学习
      if (
        type.refCode == "jsek_teachingResources" ||
        type.refCode == "jsek_cloudLearning"
      ) {
        res.datas.cmsDatas[0].datas.forEach((item) => {
          item.checked = false;
          if (item.sysType == 'CmsItem') {
            // 教学资源 类型名称赋值
            this.data.resourceClassList.forEach((type) => {
              if (type.value == item.resourcesClassification)
                item.resourceClass = type.name;
            });
            if (this.data.tabValue == "jsek_teachingResources") {} else if (this.data.tabValue == "jsek_cloudLearning") {
              item.isbuy = this.isShowNeedBuy(item);
              item.isShopCar = this.isShoppingCart(item);
            }
          }
        });
        // 显示 需要购买的和需要免费领取的
        // const arr = res.datas.cmsDatas[0].datas.filter(item => this.resourceIsBuy(item))
        // if (!arr.length) {
        //   return this.setData({
        //     loading: false,
        //     haider: true,
        //     noData: true
        //   })
        // }
        // debugger
        const num = query.cmsPath.length + 6
        this.getTreeList(res.datas.cmsDatas[0].datas, num, list, '\\')
        list = this.ensureTreeConsistency(list)
        list = this.changeResourceChildren(list)
        console.log('修改后云', list);
        let result = [];
        if (type.refCode == "jsek_teachingResources") {
          this.findChildIds(list, result);
          this.setData({
            teach: list,
            loading: false,
            openTeachids: result,
          });
        } else if (type.refCode == "jsek_cloudLearning") {
          let arr = this.handleTreeData(list).filter(
            (item) => item.saleMethod[0]
          );
          let freeIds = arr.filter((item) => {
            return item.saleMethod[0].Price == 0;
          });
          if (!freeIds.length)
            this.setData({
              isshowDrawBtn: false,
            });
          this.findChildIds(list, result);
          this.setData({
            learn: list,
            loading: false,
            openLearnids: result,
            haider: true,
          });
        }
      }
    })
  },
  //  获取教学资源  云学习  云测试
  getResourceData(type) {
    this.setData({
@@ -119,6 +359,7 @@
          return this.setData({
            noResources: true,
            loading: false,
            haider: true,
          });
        }
        //教学资源 云学习
@@ -135,6 +376,7 @@
              this.setData({
                teach: list,
                loading: false,
                haider: true
              });
              this.findChildIds(this.data.teach, (this.data.openTeachids = []));
            } else if (type.refCode == "jsek_cloudLearning") {
@@ -147,9 +389,10 @@
                learn: list,
                loading: false,
                openLearnids: result,
                haider: true
              });
              console.log("教学资源", list);
            }
            console.log(list, '云學習');
          } else {
            // 无数据
          }
@@ -158,6 +401,7 @@
          this.setData({
            test: res.datas.cmsDatas[0].datas,
            loading: false,
            haider: true
          });
        } else {
          console.log("其他");
@@ -199,6 +443,7 @@
        jsek_resourceBrief: [],
        jsek_link: [],
        accessType: [],
        learnSelectType: [],
      },
      pading: {
        start: 0,
@@ -228,12 +473,12 @@
    });
    data.datas.cmsDatas[0].datas.forEach((item) => {
      item.checked = false;
      item.isbuy = this.resourceIsBuy(item);
      item.isbuy = this.isShowNeedBuy(item);
      item.isShopCar = this.isShoppingCart(item);
    });
    return data.datas.cmsDatas[0].datas;
  },
  getBookInfo(id) {
  async getBookInfo(id) {
    this.setData({
      "mockData'.id": 0,
      "mockData.price": 0,
@@ -271,12 +516,21 @@
        freeEpubPage: [], //epub试读百分比
      },
    };
    app.MG.store.getProductDetail(query).then(async (res) => {
    await app.MG.store.getProductDetail(query).then(async (res) => {
      this.setData({
        bookDetail: res.datas,
        buyIdList: res.datas.purchasedSaleMethodIdList,
      });
      // this.getResourceData({
      //   productLinkPath: this.data.productLinkPath,
      //   refCode: this.data.refCode,
      // });
      this.getResourceDataList({
        productLinkPath: this.data.productLinkPath,
        refCode: this.data.refCode,
      })
    });
  },
  // 获取已购买商品
  getShoppingCartProductGet() {
@@ -303,6 +557,22 @@
      const isSHow = this.data.buyIdList.some(
        (item) => item == data.saleMethod[0].Id
      );
      return !isSHow;
    } else {
      return false;
    }
  },
  isShowNeedBuy(data) {
    if (data.saleMethod && data.saleMethod.length) {
      const isSHow = this.data.buyIdList.some(
        (item) => item == data.saleMethod[0].Id
      );
      if (isSHow) {
        return false;
      } else {
        return data.saleMethod[0].price > 0 ? true : false;
      }
      return !isSHow;
    } else {
      return false;
@@ -375,30 +645,26 @@
  },
  //购买按钮
  batchPurchase() {
    if (!this.data.learn.length) {
      return wx.showToast({
        icon: "error",
        title: '暂无数据',
      })
    }
    let saleMethodIds = [];
    let requests = [];
    let item = [];
    let selectAllId = [];
    const child = this.selectComponent("#tree");
    console.log(
      child.data.superiorPurchaseSaleMethodId,
      "superiorPurchaseSaleMethodId"
    );
    console.log(child.data.sonPurchaseSaleMethodId, "child.data");
    // console.log(child.data.selectAll, 'selectAll');
    item = child.data.superiorPurchaseSaleMethodId;
    const sonItem = child.data.sonPurchaseSaleMethodId;
    let selectAll = child.data.selectAll;
    if (selectAll) {
      // console.log(selectAll);
      selectAll.forEach((item) => {
        if (item.saleMethod != 0) {
          // console.log(item, 'item');
          selectAllId.push(item.saleMethod[0].Id);
        }
      });
      console.log(selectAllId);
      app.MG.store
        .initOrder({
          requests: selectAllId.map((id) => ({
@@ -409,8 +675,7 @@
        .then((res) => {
          if (res) {
            wx.navigateTo({
              url:
                "/pages/cart/paymentPage/index?orderNumber=" + res.orderNumber,
              url: "/pages/cart/paymentPage/index?orderNumber=" + res.orderNumber,
            });
            selectAllId = [];
            child.setData({
@@ -420,15 +685,12 @@
        });
    }
    if (item) {
      console.log(item, "sadsdasd");
      // 拿到id
      item.forEach((items) => {
        if (items.saleMethod != 0) {
          saleMethodIds.push(items.saleMethod[0].Id);
        }
      });
      console.log(saleMethodIds, "saleMethodIds");
      app.MG.store
        .initOrder({
          requests: saleMethodIds.map((id) => ({
@@ -439,8 +701,7 @@
        .then((res) => {
          if (res) {
            wx.navigateTo({
              url:
                "/pages/cart/paymentPage/index?orderNumber=" + res.orderNumber,
              url: "/pages/cart/paymentPage/index?orderNumber=" + res.orderNumber,
            });
            child.setData({
@@ -460,8 +721,7 @@
        .then((res) => {
          if (res) {
            wx.navigateTo({
              url:
                "/pages/cart/paymentPage/index?orderNumber=" + res.orderNumber,
              url: "/pages/cart/paymentPage/index?orderNumber=" + res.orderNumber,
            });
            this.setData({
              paymentPage: true,
@@ -473,4 +733,58 @@
        });
    }
  },
});
  // 章节勾选方法
  findAndUpdateItemsByIds(tree, ids, state) {
    function findAndUpdate(node) {
      if (ids.includes(node.id)) {
        // console.log(node, 'node');
        node.checked = state; // 将目标项的 check 属性设置为 true
      }
      if (node.children && node.children.length > 0) {
        for (let child of node.children) {
          findAndUpdate(child); // 递归处理子节点
        }
      }
    }
    for (let node of tree) {
      findAndUpdate(node); // 对每个顶层节点执行查找和更新操作
    }
    // console.log(tree, 'tree345');
    return tree; // 返回修改后的完整数组
  },
  // 单个勾选方法
  checkResoucrceInfo(tree, id) {
    function findAndUpdate(node) {
      if (node.sysType == "CmsFolder" && node.children.length > 0) {
        for (let index = 0; index < node.children.length; index++) {
          const element = node.children[index];
          findAndUpdate(element);
        }
      } else if (id == node.id && node.sysType == "CmsItem") {
        node.checked = !node.checked; // 将目标项的 check 属性设置为 true
      }
    }
    for (let node of tree) {
      findAndUpdate(node); // 对每个顶层节点执行查找和更新操作
    }
    return tree; // 返回修改后的完整数组
  },
  // 章节勾选事件
  changeListChecked(e) {
    const ids = e.detail.ids
    const state = e.detail.flag
    const updated = this.findAndUpdateItemsByIds(this.data.learn, ids, state)
    this.setData({
      learn: updated
    })
  },
  // 单个勾选事件
  changeResourceChecked(e) {
    const id = e.detail.id
    const updated = this.checkResoucrceInfo(this.data.learn, id)
    this.setData({
      learn: updated
    })
  }
});