bug
闫增涛
2024-09-20 33bca11c5ee8db8a0ca3444869f0cc3048edbe94
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
// packageBookService/pages/bookServices/detail/buyResource/index.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    barHeight: "",
    navBarHeight: "",
    learn: [],
    openLearnids: [],
    bookId: "",
    loading: true,
    shoppingList: [],
    shoppingCartGetId: [],
    methodId: [],
    paymentPage: false,
    superior: false,
    checkAllState: true,
    productLinkPath: '',
    refCode: '',
    naData: false,
    bookRefCode: []
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getBookInfo(options.bookId);
    const systInfo = wx.getSystemInfoSync();
    const menu = wx.getMenuButtonBoundingClientRect(); // 胶囊信息
    const navBarHeight =
      (menu.top - systInfo.statusBarHeight) * 2 + menu.height; // 导航栏高度
    this.setData({
      barHeight: systInfo.statusBarHeight,
      navBarHeight: navBarHeight,
      bookId: options.bookId,
      productLinkPath: options.productLinkPath,
      refCode: options.refCode
    });
    this.getShoppingCartProductGet();
  },
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},
 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
 
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},
 
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},
 
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},
 
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},
 
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  onShareTimeline() {},
  changeCheckAll(e) {
    this.setData({
      checkAllState: e.detail.value,
    });
  },
  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, newArr, path) {
    for (const item of rootList) {
      if (path == item.productLinkPath.replace('\\' + item.id, '')) {
        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 = this.insertAndSortObjectsByProductLinkPath(newArr, item)
        // 插进数组后 从原数据中删除
        rootList = rootList.filter(nitem => nitem.id != item.id)
      }
    }
    //给数组里面再添加一个children的空数组
    for (const i of newArr) {
      i.children = []
      this.getTreeList(rootList, 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 => newObj.id < obj.id);
    // 如果没有找到合适的位置,则放在数组末尾  
    if (insertIndex === -1) {
      insertIndex = array.length;
    }
    // 插入新对象到数组  
    array.splice(insertIndex, 0, newObj);
    // 测试6 正式5
    // 对数组进行排序  
    array.sort((a, b) => {
      if (a.id < b.id) return -1;
      if (a.id > b.id) return 1;
      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;
  },
  // 递归树结构,如果父级有销售方式(有效期),去掉所有子集的销售方式
  clearTreeSealmethod(clearSaleMethod, tree) {
    for (let item of tree) {
      const saleData = item.saleMethod &&
        item.saleMethod.length ?
        item.saleMethod.find((citem) => citem.SaleType == 'Normal') : null
      if (
        ((saleData && new Date(saleData.EndDate).getTime() >= new Date().getTime() && new Date(saleData.BeginDate).getTime() <= new Date().getTime()) ||
          clearSaleMethod) && item.children && item.children.length
      ) {
        item.children.forEach((ditem) => (ditem.saleMethod = []))
      }
      if (item.children && item.children.length)
        this.clearTreeSealmethod(
          saleData && new Date(saleData.EndDate).getTime() >= new Date().getTime() && new Date(saleData.BeginDate).getTime() <= new Date().getTime(),
          item.children
        )
    }
    return tree
  },
  // 勾选禁用
  handleTreeCheck(tree) {
    for (const item of tree) {
      const saleData = item.saleMethod &&
        item.saleMethod.length ?
        item.saleMethod.find((citem) => citem.SaleType == 'Normal') : undefined
      if (saleData && new Date(saleData.EndDate).getTime() >= new Date().getTime() && new Date(saleData.BeginDate).getTime() <= new Date().getTime()) {
        item.disabled = false
      } else {
        item.disabled = true
      }
      if (item.children && item.children.length) this.handleTreeCheck(item.children)
    }
    return tree
  },
  //  获取云学习
  getResourceDataList(type) {
    this.setData({
      loading: true,
      noResources: false,
    });
    let query = {
      path: '*',
      queryType: '*',
      productId: this.data.bookDetail.id,
      cmsPath: type.productLinkPath,
      cmsType: '*',
      itemFields: {
        SysType: 'CmsFolder',
        // 资源类型,试读文件,是否允许下载等参数
        learnSelectType: [],
        // freeFile: [],
        // file: [],
        // protectedFile: [],
        // resourcesClassification: [],
        // isDownload: [],
        // jsek_resourceBrief: [],
        // jsek_link: [],
        // jsek_questionBank: []
      },
      pading: {
        start: 0,
        size: 999
      },
    }
    app.MG.store.getProductDetailNoChildren(query).then((res) => {
      if (!res.datas.cmsDatas[0].datas.length) {
        return this.setData({
          noResources: true,
          loading: false,
        });
      }
      let list = []
      res.datas.cmsDatas[0].datas.forEach((item) => {
        item.checked = false;
        // if (item.sysType == 'CmsItem') {
        //   item.isbuy = this.resourceIsBuy(item);
        //   item.isShopCar = this.isShoppingCart(item);
        // }
      });
      // 显示 需要购买的和需要免费领取的
      this.getTreeList(res.datas.cmsDatas[0].datas, list, query.cmsPath)
      list = this.ensureTreeConsistency(list)
      list = this.changeResourceChildren(list)
      list = this.clearTreeSealmethod(false, list)
      list = this.handleTreeCheck(list)
      this.handleTreeData(list).forEach(item => {
        item.isbuy = this.resourceIsBuy(item);
        item.isShopCar = this.isShoppingCart(item);
      })
      console.log('修改后云', list);
      let result = [];
      let arr = res.datas.cmsDatas[0].datas.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,
      });
    })
  },
 
  async getBookInfo(id) {
    const query = {
      path: "*",
      queryType: "*",
      productId: id,
      favoriteTypes: "FavoriteBookCity",
      itemFields: {
        "SysType=": "CmsFolder",
      },
      coverSize: {
        height: 300,
      },
      fields: {
        seriesName: [],
        author: [],
        isbn: [],
        publicationDate: [],
        bookClassification: [],
        paperPrice: [],
        JDLink: [],
        tmallLink: [],
        dangdangLink: [],
        weidianLink: [],
        content: [],
        authorIntroduction: [],
        isApplyBook: [],
        isSell: [],
        pdf: [],
        protectedEpub: [],
        probationPage: [], //pdf试读页数
        freeEpubPage: [], //epub试读百分比
      },
    };
    await app.MG.store.getProductDetail(query).then(async (res) => {
      this.setData({
        bookDetail: res.datas,
        buyIdList: res.datas.purchasedSaleMethodIdList,
      });
      this.getResourceDataList({
        productLinkPath: this.data.productLinkPath,
        refCode: this.data.refCode,
      })
    });
 
  },
  // 获取已购买商品
  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,
      });
    });
  },
  // 判断资源是否购买
  resourceIsBuy(data) {
    if (data.saleMethod && data.saleMethod.length) {
      const saleData = data.saleMethod.find((item) => item.SaleType == 'Normal')
      if (saleData.State == 'Disable') return false
      const isShow = this.data.buyIdList.some(
        (item) => item == saleData.Id
      );
      // 已经购买
      if (isShow) return false
      // 未购买,查看销售方式是否过期
      if (!isShow) {
        const flag = new Date(saleData.EndDate).getTime() >= new Date().getTime() &&
          new Date(saleData.BeginDate).getTime() <= new Date().getTime()
        if (flag) {
          // 为过期 ,需要购买
          return true
        } else {
          // 已过期 无需购买
          return false
        }
      }
    } else {
      return false;
    }
  },
 
  // 判断资源加入购物车按钮是否显示
  isShoppingCart(data) {
    if (data.saleMethod && data.saleMethod.length) {
      const saleData = data.saleMethod.find((item) => item.SaleType == 'Normal')
      // 先判断是否免费
      if (saleData.Price <= 0) return false
      // 再判断是否购买
      const isBuy = this.data.buyIdList.some((item) => item == saleData.Id)
      if (isBuy) {
        // 购买了
        return false
      } else {
        // 判断是否加入购物车
        const isShow = this.data.shoppingCartGetId.some((item) => item == saleData.Id)
        if (isShow) return false
        // 未购买,查看销售方式是否过期
        if (!isShow) {
          const flag = new Date(saleData.EndDate).getTime() >= new Date().getTime() &&
            new Date(saleData.BeginDate).getTime() <= new Date().getTime()
          if (flag) {
            // 为过期 ,需要购买
            return true
          } else {
            // 已过期 无需购买
            return false
          }
        }
      }
      // 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;
    }
  },
  // 获取展开项
  findChildIds(data, result) {
    let index = 0;
    for (let i = 0; i < data.length; i++) {
      if (index < 3) {
        const item = data[i];
        if (item.children && item.children.length > 0) {
          result.push(item.id);
          for (let j = 0; j < item.children.length; j++) {
            if (index < 3) {
              const childrenItme = item.children[j];
              if (item.children && item.children.length > 0) {
                result.push(childrenItme.id);
                index += 1;
              }
            } else {
              break;
            }
          }
        } else if (item.children && item.children.length > 0) {
          result.push(item.id);
          index += 1;
        }
      } else {
        break;
      }
    }
  },
  checkAll() {
    const child = this.selectComponent("#tree");
    child.checkAll();
  },
  //购买按钮
  batchPurchase() {
    if (!this.data.learn.length) {
      return wx.showToast({
        icon: "error",
        title: '暂无数据',
      })
    }
    // 修改后方法
    const checkData = this.handleTreeData(this.data.learn).filter(item => item.checked == true)
    console.log('选中', checkData);
    if (!checkData.length) return wx.showToast({
      icon: 'error',
      title: '请勾选资源',
    })
    let saleMethodIds = [];
    checkData.forEach((items) => {
      if (items.saleMethod.length) {
        saleMethodIds.push(items.saleMethod.find(citem => citem.SaleType == 'Normal').Id);
      }
    });
    app.MG.store
      .initOrder({
        requests: saleMethodIds.map((id) => ({
          saleMethodId: id,
          count: 1,
        })),
      })
      .then((res) => {
        if (res) {
          wx.navigateTo({
            url: "/pages/cart/paymentPage/index?orderNumber=" + res.orderNumber,
          });
        }
      });
  },
 
  // 章节勾选方法
  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
    }, () => {
      wx.hideLoading()
    })
  },
  // 单个勾选事件
  changeResourceChecked(e) {
    const id = e.detail.id
    const updated = this.checkResoucrceInfo(this.data.learn, id)
    this.setData({
      learn: updated
    }, () => {
      wx.hideLoading()
    })
  },
  upDateShopCar(id, tree) {
    for (let item of tree) {
      if (item.id == id) {
        item.isShopCar = false
      } else {
        if (item.children && item.children.length) this.upDateShopCar(id, item.children)
      }
    }
    return tree
  },
  // 更新购物车图标
  updateCloudLearning(e) {
    const {
      id
    } = e.detail
    console.log(id);
    const list = this.upDateShopCar(id, this.data.learn)
    this.setData({
      learn: list
    })
  }
});