YM
2024-05-29 f84c3f1d77f798eb17dc48bba29fef1015536935
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
import { ipcMain } from 'electron'
import fs from 'fs'
import os from 'os'
import moment from 'moment'
import path from 'path'
import { uuid } from './toolClass'
const xlsx = require('node-xlsx')
const Store = require('electron-store')
const ExportTasks = new Store('ExportTasks')
const DownloadConfig = new Store('DownloadConfig')
const EXPORT_TASKS = 'ExportTasks'
const DOWNLOAD_SAVE_FOLDER = 'FileDownloadSaveFolder'
 
// 默认路径
const homeDir = os.homedir()
let DOWNLOAD_PATH = ''
const FileDownloadSaveFolder = DownloadConfig.get(DOWNLOAD_SAVE_FOLDER)
if (FileDownloadSaveFolder) {
  DOWNLOAD_PATH = FileDownloadSaveFolder
} else {
  if (os.platform() === 'win32') {
    // Windows 系统下的 "Downloads" 文件夹路径
    DOWNLOAD_PATH = path.join(homeDir, 'Downloads')
  } else {
    // macOS 和 Linux 系统下的 "Downloads" 文件夹路径
    DOWNLOAD_PATH = path.join(homeDir, 'Downloads')
  }
}
 
let mainWindow: any = null
let request: any = null
 
let token = ''
let taskList: any = []
 
export const init = (win, req) => {
  mainWindow = win
  request = req
  loadTasks()
}
 
type CmsItemProps = {
  path: string
  storeId?: number
  repositoryId?: number
  type?: string
  paging: {
    Start: number
    Size: number
  }
  sort?: Record<string, any>
  linkTypes?: string[]
  fields?: {
    [key: string]: []
  }
  filters?: {
    [key: string]: string[]
  }
  subQuery?: {}
  keyword?: string
  itemId?: number
  resType?: any
}
 
class ExportTask {
  // 初始状态
  static INIT = 0
  // 处理中
  static LOADING = 1
  // 暂停中
  static PAUSE = 2
  // 完成
  static FINISHED = 3
  // 失败
  static FAILED = 4
 
  public data
 
  constructor(data) {
    this.initData(data)
    this.start()
  }
 
  // 新建任务
  initData = (data) => {
    if (data.id) {
      this.data = { ...data }
    } else {
      this.data = {
        id: uuid(8),
        startDate: moment().format('YYYY-MM-DD HH:mm:ss'),
        endDate: '',
        bookTpl: null, // 图书模板(Excel模板)
        fileTpl: null, // 文件导出模板
        tplInfo: data.tplInfo,
        bookInfo: data.bookInfo, // 导出的图书
        typeKeyMap: null,
        state: ExportTask.INIT, // 任务状态
        fileTypeList: [], // 需下载文件类型
        tabHeader: [], // Excel表头数据
        tabData: [], // Excel表头数据
        temporaryFolderPath: '', // 临时文件夹目录
        bookFolderPath: null, // 图书文件夹path
        fileMd5List: {}, // 图书文件
        taskPath: '',
        progressInfo: {
          // 进程信息
          createTask: ExportTask.INIT,
          temporaryFolder: ExportTask.INIT,
          handleFile: {},
          handleBook: {
            state: ExportTask.INIT,
            info: {
              success: 0,
              failed: 0,
              total: 0
            }
          },
          handleFolder: {},
          handleExcel: ExportTask.INIT
        }
      }
    }
    this.preloadData(this.data)
  }
 
  // 开始任务
  start = () => {
    const task = this.data
    task.state = ExportTask.LOADING
    // 请求数据
    if (
      !task.fileTypeList ||
      !task.fileTypeList.length ||
      !task.tabHeader ||
      !task.tabHeader.length
    ) {
      this.preloadData(task)
    } else {
      // 临时文件夹
      if (!task.temporaryFolderPath) {
        this.createTemporaryFolder(task)
      }
    }
  }
 
  // 预处理数据
  preloadData = (task) => {
    // 先请求相关数据,并预处理
    task.progressInfo.createTask = ExportTask.LOADING
    this.getTplInfo(task.tplInfo).then((data) => {
      console.log(data)
      if (data) {
        let fileTypeList = []
        for (let i = 0; i < task.fileTpl.fileData.length; i++) {
          const folderItem = task.fileTpl.fileData[i]
          fileTypeList = fileTypeList.concat(folderItem.fileType)
        }
        task.fileTypeList = fileTypeList
        // 处理图书模板创建excel表头
        const tabHeader: any = []
        for (let j = 0; j < task.bookTpl.fieldKeys.length; j++) {
          const field = task.bookTpl.fieldKeys[j]
          tabHeader.push({
            key: field.typeField.refCode,
            label: field.title
          })
        }
        task.tabHeader = tabHeader
        task.progressInfo.handleBook.info.total = task.bookInfo.length
        this.sendProgressInfo()
        // 临时文件夹
        if (!task.temporaryFolderPath) {
          this.createTemporaryFolder(task)
        }
      }
    })
  }
 
  // 获取模板信息
  getTplInfo = (data) => {
    if (data.type == 'user') {
      return request({
        url: '/identity/User/GetUserKey',
        method: 'post',
        headers: {
          Authorization: 'bearer ' + token
        },
        data: {
          userKeyList: [{ storeKey: 'personImportTemplate', key: data.key }]
        }
      })
        .then((res) => {
          if (res && res.length > 0) {
            try {
              return JSON.parse(res[0].value)
            } catch (error) {
              return null
            }
          }
        })
        .catch((error) => {
          console.log(error)
        })
    }
    if (data.type == 'sys') {
      return request({
        url: '/identity/Sys/GetSysKey',
        method: 'post',
        headers: {
          Authorization: 'bearer ' + token
        },
        data: {
          userKeyList: [{ storeKey: 'sysImportTemplate', key: data.key }]
        }
      }).then((res) => {
        if (res && res.length > 0) {
          try {
            return JSON.parse(res[0].value)
          } catch (error) {
            return null
          }
        }
      })
    }
  }
 
  // 创建临时文件夹
  createTemporaryFolder = (task) => {
    task.progressInfo.temporaryFolder = ExportTask.LOADING
    this.sendProgressInfo()
    // 临时文件夹名称
    const folderName = 'TF' + moment().valueOf()
    // 创建临时文件夹
    const folderPath = path.join(DOWNLOAD_PATH, folderName)
    fs.mkdirSync(folderPath, { recursive: true })
    task.temporaryFolderPath = folderPath
    // 更新状态
    task.progressInfo.temporaryFolder = ExportTask.FINISHED
    this.sendProgressInfo()
    this.createBookFolder(task)
  }
 
  // 创建图书文件夹
  createBookFolder = (task) => {
    if (!task.bookFolderPath) task.bookFolderPath = {}
    // 在临时文件夹中创建不同书籍文件夹
    for (let i = 0; i < task.bookInfo.length; i++) {
      const book = task.bookInfo[i]
      if (book.ISBN) book.ISBN = book.ISBN.replace(new RegExp('-', 'gm'), '')
      const folderPath = path.join(
        task.temporaryFolderPath,
        book.name + (book.ISBN ? '(' + book.ISBN + ')' : '')
      )
      fs.mkdirSync(folderPath, { recursive: true })
      task.bookFolderPath[book.id] = folderPath
      task.fileMd5List[book.id] = []
      task.progressInfo.handleFile[book.id] = {
        state: ExportTask.INIT,
        info: {
          success: 0,
          failed: 0,
          total: 0
        }
      }
      task.progressInfo.handleFolder[book.id] = ExportTask.INIT
      this.sendProgressInfo()
      // 获取图书信息
      this.getBookData(book, task)
    }
  }
 
  // 获取图书信息
  getBookData(book, task) {
    task.progressInfo.handleBook.state = ExportTask.LOADING
    this.sendProgressInfo()
    // const idPath = book.idPath.slice(0, book.idPath.lastIndexOf('\\'))
    // this.getCmsItem(book.storeId, book.repoId, idPath, book.id, task.typeKeyMap)
    //   .then((result) => {
    //     const bookInfo = result.data.data[0].datas[0].datas
    //     for (const key in bookInfo) {
    //       if (bookInfo[key]) {
    //         try {
    //           bookInfo[key] = JSON.parse(bookInfo[key])[0].Value
    //         } catch (error) {
    //           console.log(error)
    //         }
    //       }
    //     }
    //     task.tabData.push(bookInfo)
    //     task.progressInfo.handleBook.info.success++
    //     // 获取文件信息
    //     this.getFileData(book, task)
    //     this.sendProgressInfo()
    //     if (task.progressInfo.handleBook.info.success == task.progressInfo.handleBook.info.total) {
    //       task.progressInfo.handleBook.state = ExportTask.FINISHED
    //       this.sendProgressInfo()
    //       this.exportExcel(task)
    //     }
    //   })
    //   .catch((e) => {
    //     console.error(e)
    //   })
  }
 
  // 获取文件信息
  getFileData(book, task) {
    task.progressInfo.handleFile[book.id].state = ExportTask.LOADING
    this.sendProgressInfo()
    // let requestIndex = 0
    // let bookFile = []
    for (let i = 0; i < book.getFilePaths.length; i++) {
      // const filePath = book.getFilePaths[i]
      // this.getCmsItem({
      //   repo: {
      //     storeId: book.storeId,
      //     repoId: book.repoId
      //   },
      //   parent: { idPath: filePath },
      //   paging: { Start: 0, Size: 10 },
      //   sysTypes: ['CmsFile'],
      //   recursion: true
      // })
      //   .then((result) => {
      //     bookFile = bookFile.concat(result.datas)
      //     requestIndex++
      //     if (requestIndex == book.getFilePaths.length) {
      //       this.handleBookFile(book, task, bookFile)
      //     }
      //   })
      //   .catch((e) => {
      //     console.error(e)
      //   })
    }
  }
 
  // 处理图书文件
  handleBookFile = (book, task, bookFile) => {
    // 获取到图书下所有文件信息
    const bookFileList = bookFile.filter((item) => {
      return item.datas.LinkFile && task.fileTypeList.indexOf(item.type) > -1
    })
    // 需判断去重,同样的文件只下载一个(如果同样的文件移动两次,第二次会报错;如果是要移动至多个文件夹,移动时能兼容)
    const newBookFileList: any = []
    for (let i = 0; i < bookFileList.length; i++) {
      const exists = newBookFileList.filter((item) => {
        return bookFileList[i].linkFile[0].File.Md5 == item.linkFile[0].File.Md5
      })
      if (!exists.length) {
        newBookFileList.push(bookFileList[i])
      }
    }
    task.progressInfo.handleFile[book.id].info.total = newBookFileList.length
    this.sendProgressInfo()
    if (newBookFileList && newBookFileList.length) {
      for (let i = 0; i < newBookFileList.length; i++) {
        const item = newBookFileList[i]
        const linkInfo = JSON.parse(item.datas.LinkFile)[0]
        linkInfo.File.MetaData = JSON.parse(linkInfo.File.MetaData)
        linkInfo.File.itemType = item.type
        task.fileMd5List[book.id].push(linkInfo.File)
        // 调用下载队列进行下载(异步)
        // const downloadPath = path.join(
        //   task.bookFolderPath[book.id],
        //   linkInfo.File.MetaData.fileName
        // )
        // const info = new DownloadInfo(
        //   apps.resAppId,
        //   linkInfo.File.Md5,
        //   0,
        //   linkInfo.File.MetaData.size,
        //   downloadPath
        // )
        // const downloadTask = new DownloadTask(info)
        // downloadTask.start((downloadInfo) => {
        //   task.progressInfo.handleFile[book.id].info.success++
        //   this.sendProgressInfo()
        //   // let isbn = path.basename(path.dirname(downloadInfo.path));
        //   for (let i = 0; i < task.fileMd5List[book.id].length; i++) {
        //     const item = task.fileMd5List[book.id][i]
        //     if (item.Md5 == downloadInfo.md5 && !item.path) {
        //       item.path = downloadInfo.path
        //       break
        //     }
        //   }
        //   if (
        //     task.progressInfo.handleFile[book.id].info.success ==
        //     task.progressInfo.handleFile[book.id].info.total
        //   ) {
        //     task.progressInfo.handleFile[book.id].state = ExportTask.FINISHED
        //     this.sendProgressInfo()
        //     this.handleBookFileMerge(task, book.id)
        //   }
        // })
      }
    } else {
      task.progressInfo.handleFile[book.id].state = ExportTask.FINISHED
      task.progressInfo.handleFolder[book.id] = ExportTask.FINISHED
      this.sendProgressInfo()
      this.taskSucess(task)
    }
  }
 
  // 按文件模板合并图书文件
  handleBookFileMerge = (task, key) => {
    task.progressInfo.handleFolder[key] = ExportTask.LOADING
    this.sendProgressInfo()
    const fileTpl = task.fileTpl
    const typeToFolderList = {}
    if (task.bookTpl.tplType == 1 || !task.bookTpl.tplType) {
      // 按图书导出
      // 创建模板对应的文件夹
      for (let i = 0; i < fileTpl.fileData.length; i++) {
        const item = fileTpl.fileData[i]
        // 创建文件夹
        const folderPath = path.join(task.bookFolderPath[key], item.fileName)
        fs.mkdirSync(folderPath, { recursive: true })
        for (let z = 0; z < item.fileType.length; z++) {
          const typeItem = item.fileType[z]
          if (!typeToFolderList[typeItem]) {
            typeToFolderList[typeItem] = []
          }
          typeToFolderList[typeItem].push({
            folderName: item.fileName,
            folderPath: folderPath
          })
        }
      }
    } else if (task.bookTpl.tplType == 2) {
      // 按文件夹导出
      // 创建模板对应的文件夹
      for (let i = 0; i < fileTpl.fileData.length; i++) {
        const item = fileTpl.fileData[i]
        // 创建文件夹
        const folderPath = path.join(task.temporaryFolderPath, item.fileName)
        const stat = fs.existsSync(folderPath)
        if (!stat) {
          fs.mkdirSync(folderPath, { recursive: true })
        }
        for (let z = 0; z < item.fileType.length; z++) {
          const typeItem = item.fileType[z]
          if (!typeToFolderList[typeItem]) {
            typeToFolderList[typeItem] = []
          }
          typeToFolderList[typeItem].push({
            folderName: item.fileName,
            folderPath: folderPath
          })
        }
      }
    }
    // 移动文件对应类型文件至文件夹
    for (let j = 0; j < task.fileMd5List[key].length; j++) {
      let file = task.fileMd5List[key][j]
      if (typeToFolderList[file.itemType] && typeToFolderList[file.itemType].length > 0) {
        // 处理重命名
        file = this.handleRename(task, file, key)
        if (typeToFolderList[file.itemType].length > 1) {
          // 一个类型对应多个文件夹时,先复制后移动
          for (let n = 0; n < typeToFolderList[file.itemType].length; n++) {
            const folder = typeToFolderList[file.itemType][n]
            if (n < typeToFolderList[file.itemType].length - 1) {
              // 复制
              fs.copyFileSync(file.path, path.join(folder.folderPath, file.MetaData.fileName))
            } else {
              // 移动
              fs.renameSync(file.path, path.join(folder.folderPath, file.MetaData.fileName))
            }
          }
        } else {
          // 直接移动
          fs.renameSync(
            file.path,
            path.join(typeToFolderList[file.itemType][0].folderPath, file.MetaData.fileName)
          )
        }
      }
    }
    // 如果按文件夹导出,需删除图书文件夹
    if (task.bookTpl.tplType == 2) {
      try {
        fs.rmdirSync(task.bookFolderPath[key])
      } catch (error) {
        console.log(error)
      }
    }
 
    task.progressInfo.handleFolder[key] = ExportTask.FINISHED
    this.sendProgressInfo()
    this.taskSucess(task)
  }
 
  // 处理重命名
  handleRename = (task, file, bookId) => {
    // 获取图书信息
    const bookInfo = task.tabData.filter((item) => {
      return item.Id == bookId
    })
    const renameData = task.fileTpl.renameData
    if (!renameData) {
      return file
    }
    for (let i = 0; i < renameData.length; i++) {
      const renameItem = renameData[i]
      if (renameItem.fileType == file.itemType) {
        let newFileName = ''
        const oldFileName = file.MetaData.fileName
        const suffix = oldFileName.substring(oldFileName.lastIndexOf('.') + 1, oldFileName.length)
        // 拼接前置字符
        if (renameItem.firstTxt) {
          newFileName += renameItem.firstTxt
        }
        // 拼接替换名称
        const field = renameItem.renameField.split('/')[0]
        if (bookInfo.length && bookInfo[0][field]) {
          let fieldTxt = bookInfo[0][field]
          // 处理特殊字符
          const reg = new RegExp('[\\/:*?"<>]', 'g')
          fieldTxt = fieldTxt.replace(reg, '')
          for (let z = 0; z < renameItem.formatTxt.length; z++) {
            const formatItem = renameItem.formatTxt[z]
            if (formatItem == 'nbsp') {
              fieldTxt = fieldTxt.replace(new RegExp(' ', 'gm'), '')
            } else {
              fieldTxt = fieldTxt.replace(new RegExp(formatItem, 'gm'), '')
            }
          }
          newFileName += fieldTxt
        } else {
          const oldName = oldFileName.substring(0, oldFileName.lastIndexOf('.'))
          newFileName += oldName
        }
        // 拼接后置字符
        if (renameItem.lastTxt) {
          newFileName += renameItem.lastTxt
        }
        // 拼接后缀
        newFileName = newFileName + '.' + suffix
        // 返回数据
        file.MetaData.fileName = newFileName
        return file
      }
    }
    return file
  }
 
  // 导出excel
  exportExcel = (task) => {
    task.progressInfo.handleExcel = ExportTask.LOADING
    this.sendProgressInfo()
    const excelPath = path.join(task.temporaryFolderPath, '图书信息.xls')
    console.log(task)
    const excelData: any = []
    const headerData: any = []
    for (let i = 0; i < task.tabHeader.length; i++) {
      const header = task.tabHeader[i]
      headerData.push(header.label)
    }
    const tableData: any = []
    for (let z = 0; z < task.tabData.length; z++) {
      const tabItem = task.tabData[z]
      const itemData: any = []
      for (let j = 0; j < task.tabHeader.length; j++) {
        const headerItem = task.tabHeader[j]
        itemData.push(tabItem[headerItem.key])
      }
      tableData.push(itemData)
    }
    excelData.push(headerData)
    excelData.push(...tableData)
    console.log(excelData)
    const buffer = xlsx.build([{ name: 'Sheet', data: excelData }])
    fs.writeFileSync(excelPath, buffer)
    task.progressInfo.handleExcel = ExportTask.FINISHED
    this.sendProgressInfo()
    this.taskSucess(task)
  }
 
  // 完成
  taskSucess = (task) => {
    let bookFileState = true
    for (const key in task.progressInfo.handleFolder) {
      if (task.progressInfo.handleFolder[key] !== ExportTask.FINISHED) {
        bookFileState = false
        break
      }
    }
    if (bookFileState && task.progressInfo.handleExcel === ExportTask.FINISHED) {
      // const obj = path.parse(task.temporaryFolderPath)
      // const creactTime = parseInt(obj.base.replace('TF', ''))
      const newFolderName = task.bookTpl.name + '_' + task.key
      const newPath = path.join(path.dirname(task.temporaryFolderPath), newFolderName)
      fs.renameSync(task.temporaryFolderPath, newPath)
      task.taskPath = newPath
      task.endDate = moment().format('YYYY-MM-DD HH:mm:ss')
      task.state = ExportTask.FINISHED
      this.sendProgressInfo()
    }
  }
 
  // 发送进度信息
  sendProgressInfo = () => {}
 
  // 获取用于显示的数据
  // getShowData = () => {
  //   const showDataList = []
  //   for (let i = 0; i < this.taskList.length; i++) {
  //     const taskItem = this.taskList[i]
  //     const obj = {
  //       id: taskItem.id,
  //       bookTplName: taskItem.bookTpl.name,
  //       fileTplName: taskItem.fileTpl.name,
  //       bookInfo: {
  //         name: taskItem.bookInfo.name,
  //         ISBN: taskItem.bookInfo.ISBN
  //       },
  //       state: taskItem.state,
  //       progressInfo: taskItem.progressInfo,
  //       startDate: taskItem.startDate,
  //       endDate: taskItem.endDate,
  //       taskPath: taskItem.taskPath
  //     }
  //     showDataList.unshift(obj)
  //   }
  //   return showDataList
  // }
 
  getCmsItem = ({
    path,
    storeId,
    repositoryId,
    type,
    paging,
    sort,
    linkTypes,
    fields,
    filters,
    subQuery,
    keyword,
    itemId,
    resType
  }: CmsItemProps) => {
    const query = {
      AccessControl: {
        Path: path,
        StoreId: storeId + '',
        RepositoryId: repositoryId + '',
        Type: type ? type : '\\'
      },
      PageQuery: paging,
      SortQuery: sort ? [sort] : [],
      CreateDate: [],
      Description: [],
      Name: [],
      RefCode: [],
      Type: [],
      TypeId: [],
      State: [],
      Tag: [],
      LinkDepartment: [],
      LinkOrg: [],
      LinkInfo: [],
      LinkId: [],
      LinkOrder: [],
      LinkParentId: [],
      LinkFile: [],
      LinkType: linkTypes ?? [],
      LinkStore: [],
      LinkRepository: [],
      LinkPath: [],
      LinkAppId: [],
      Creator: [],
      ...fields,
      ...filters,
      ...subQuery
    }
 
    if (keyword) {
      delete query.Name
      query['Name*'] = [keyword]
    }
    if (itemId) query['Id='] = [`${itemId}`]
    const body = { query: JSON.stringify({ Query: [{ Q1: query }] }) }
    return request({
      url: '/resource/ResourceItem/QueryCmsItem',
      method: 'post',
      headers: {
        Authorization: 'bearer ' + token
      },
      data: body
    }).then((res) => {
      if (res && res.length > 0) {
        const data = res[0]
        const datas = this.handleCmsItemListRequestData(
          data.datas,
          fields,
          path,
          storeId,
          repositoryId
        )
        return { datas, total: data.totalCount }
      } else {
        return { datas: [], total: 0 }
      }
    })
  }
 
  handleCmsItemListRequestData = (datas, fields, path?, storeId?, repositoryId?) => {
    const dataList = []
    for (let i = 0; i < datas.length; i++) {
      const item = datas[i]
      const _fields = {}
      const _datas = []
      if (fields != null) {
        for (let fieldKey in fields) {
          // 兼容筛选条件的字段值获取,因为后台筛选和取值只能传一个,都会返回值
          fieldKey = fieldKey.replace(/[!=<>*]/g, '')
          if (item.datas[fieldKey]) {
            let values = []
            if (typeof item.datas[fieldKey] == 'string') {
              values = JSON.parse(item.datas[fieldKey])
            } else {
              values = item.datas[fieldKey]
            }
            if (values?.length > 0) {
              // 用字段名处理返回的字段值
              if (values[0].Value) {
                _fields[fieldKey] = values[0].Value
                values[0].sequenceNum = values[0].SequenceNum
              }
              // 兼容处理数据返回的key是CmsItemData
              // if (values[0].CmsItemData) {
              //   _fields[fieldKey] = values[0].CmsItemData.Value;
              //   values[0].sequenceNum = values[0].CmsItemData.SequenceNum;
              // }
 
              item.datas[fieldKey] = values[0]
              if (values?.length > 1) {
                const isFile = values.find((citem) => citem.FileList?.length > 0)
                const dataItems = this.deduplicateArray(values, 'FieldId')
                if (!isFile) {
                  _datas.push(dataItems[0])
                } else {
                  const customFile = {
                    customFileList: values,
                    name: fieldKey,
                    md5: _fields[fieldKey]
                  }
                  _datas.push(customFile)
                }
              } else {
                _datas.push(values[0])
              }
            }
          }
        }
      }
 
      if (item.datas.LogQuery) {
        item.datas.LogQuery = JSON.parse(item.datas.LogQuery)
      }
 
      const subDatas = {}
      if (item.subDatas) {
        for (let subData of item.subDatas) {
          const tag = subData.queryTag.replace('Query', '')
          subDatas[tag] = subData.datas
        }
      }
 
      dataList.push({
        ...item,
        id: item.id,
        name: item.datas.Name,
        icon: item.datas.Icon,
        storeId: storeId,
        repositoryId: repositoryId,
        refCode: item.datas.RefCode === '[]' ? null : item.datas.RefCode,
        state: item.datas.State,
        type: item.datas.Type,
        tag: item.datas.Tag,
        creator: item.datas.Creator ? JSON.parse(item.datas.Creator) : undefined,
        linkType: item.datas.LinkType,
        childrenCount: parseInt(item.datas.ChildrenCount ?? '0'),
        childrenFolderCount: parseInt(item.datas.ChildrenFolderCount ?? '0'),
        childrenChannelCount: parseInt(item.datas.ChildrenChannelCount ?? '0'),
        childrenCmsItemCount: parseInt(item.datas.ChildrenCmsItemCount ?? '0'),
        childrenFileCount: parseInt(item.datas.ChildrenFileCount ?? '0'),
        createDate: moment(item.datas.CreateDate).format('YYYY-MM-DD HH:mm:ss'),
        description: item.datas.Description,
        sysType: item.datas.SysType,
        idPath: path + '\\' + item.id,
        typeId: parseInt(item.datas.TypeId),
        linkAppId: item.datas.linkAppId,
        linkFile: JSON.parse(item.datas.LinkFile ?? '[]'),
        linkInfo: item.datas.LinkInfo ? JSON.parse(item.datas.LinkInfo) : [],
        linkPath: item.datas.LinkPath ?? null,
        linkOrg: item.datas.linkOrg ? JSON.parse(item.datas.linkOrg) : [],
        linkDepartment: item.datas.linkDepartment ? JSON.parse(item.datas.linkDepartment) : [],
        ..._fields,
        datas: item.datas,
        fieldList: _datas,
        subDatas
      })
    }
    return dataList
  }
 
  //数组去重
  deduplicateArray = (arr, idKey) => {
    const seen = {}
    const deduplicatedArray = arr.filter((item) => {
      const id = item[idKey]
      if (!seen[id]) {
        seen[id] = true
        return true
      }
      return false
    })
    return deduplicatedArray
  }
}
 
// 本地缓存加载任务列表
const loadTasks = () => {
  const txt = ExportTasks.get(EXPORT_TASKS, '[]')
  try {
    taskList = JSON.parse(txt)
  } catch (error) {
    taskList = []
  }
}
 
// 本地缓存记录任务列表
const saveTasks = () => {
  ExportTasks.set(EXPORT_TASKS, JSON.stringify(taskList))
}
 
const updateTask = (data?) => {
  // 调用渲染进程
  if (data) {
    mainWindow.webContents.send('exportTaskChange', JSON.stringify(data))
    const index = taskList.findIndex((item) => item.id == data.id)
    taskList[index] = data
  } else {
    mainWindow.webContents.send('exportTaskChange')
  }
  saveTasks()
}
 
// 获取任务列表
ipcMain.on('getExportTasks', (ev, data) => {
  // 页面会先获取任务列表,在获取列表时将token挂载
  mainWindow.webContents
    .executeJavaScript('localStorage.getItem("token");', true)
    .then((result) => {
      token = result
    })
  const returnData = JSON.parse(JSON.stringify(taskList))
  ev.returnValue = returnData
})
 
// 新建任务
ipcMain.on('newExportTask', async (ev, data) => {
  // 判断下载目录是否存在
  if (!fs.existsSync(DOWNLOAD_PATH)) {
    // 未获取到默认下载目录
    mainWindow.webContents.send(
      'showMessage',
      JSON.stringify({
        showType: 'ExportTask',
        type: 'notDownloadFolder',
        msg: JSON.stringify(data)
      })
    )
  } else {
    mainWindow.webContents.send(
      'showMessage',
      JSON.stringify({
        showType: 'ExportTask',
        type: 'showState',
        msg: '检测到导出任务,正在创建...'
      })
    )
    const task = new ExportTask(data)
    if (!data.id && data.autoPlay) {
      await task.start()
    }
    if (task.data) {
      taskList.push(task.data)
      updateTask(task)
    }
    mainWindow.webContents.send(
      'showMessage',
      JSON.stringify({
        showType: 'ExportTask',
        type: 'showState',
        msg: ''
      })
    )
  }
})
 
// 删除任务
ipcMain.on('cleanExportTask', (ev, id) => {
  // const item = taskList.find((item) => item.id == id)
  // if (item.state == 'download') {
  //   const task = new DownloadTask(item)
  //   task.pause()
  // }
 
  taskList = taskList.filter((item) => item.id != id)
  updateTask()
  ev.returnValue = true
})
 
// 清空任务
ipcMain.on('cleanAllExportTask', (ev) => {
  // for (let i = 0; i < taskList.length; i++) {
  //   const item = taskList[i]
  //   if (item.state == 'download') {
  //     const task = new DownloadTask(item)
  //     task.pause()
  //   }
  // }
 
  taskList = []
  updateTask()
  ev.returnValue = true
})