Jelajahi Sumber

修复编辑歌单,添加歌曲的报错

onecold 10 bulan lalu
induk
melakukan
8f166c741a

+ 133 - 126
entry/src/main/ets/dialog/AddSongsToPlaylistDialog.ets

@@ -4,22 +4,25 @@ import { ToastUtil, LogUtil } from '@pura/harmony-utils';
 import { VideoItem } from '../viewmodel/VideoItem';
 import MediaTable from '../common/util/MediaTable';
 import PlaylistTable from '../common/util/PlaylistTable';
+import { LazyDataSource } from '../common/util/LazyDataSource';
 
 /**
  * 添加歌曲到歌单对话框内容组件
  */
 @Component
 struct AddSongsToPlaylistDialogContent {
-  @State allSongs: VideoItem[] = []
+  // @State allSongs: VideoItem[] = []
   @State selectedSongs: VideoItem[] = []
-  @State isLoading: boolean = true
+  @State isLoading: boolean = false
   @State searchText: string = ''
   @State filteredSongs: VideoItem[] = []
-  @State isDbInitialized: boolean = false
-  @Prop playlist: Playlist | null = null
+  private listScroller: ListScroller = new ListScroller()
+  @State isSearchMode: boolean = false
+  @Prop playlist: Playlist
+  @Prop mediaKuList:  Array<VideoItem>
   private mediaTable: MediaTable = new MediaTable(getContext(this))
   private playlistTable: PlaylistTable = new PlaylistTable(getContext(this))
-
+  @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.filteredSongs)
   // 回调函数
   onConfirm?: (songs: VideoItem[]) => void
   onCancel?: () => void
@@ -27,13 +30,15 @@ struct AddSongsToPlaylistDialogContent {
   aboutToAppear() {
     LogUtil.info('heanup AddSongsToPlaylistDialogContent aboutToAppear 开始')
     LogUtil.info('heanup playlist: ' + (this.playlist ? JSON.stringify({ id: this.playlist.id, name: this.playlist.name }) : 'null'))
-    
+    console.info('onecold mediaKuList 对话框 aboutToAppear='+this.mediaKuList.length)
+    this.updateListData(this.mediaKuList)
+
     // 初始化数据库连接
-    this.mediaTable.getRdbStore(getContext(this), () => {
-      LogUtil.info('heanup MediaTable 数据库初始化完成')
-      this.isDbInitialized = true
-      this.loadAllSongs()
-    })
+    // this.mediaTable.getRdbStore(getContext(this), () => {
+    //   LogUtil.info('heanup MediaTable 数据库初始化完成')
+    //   this.isDbInitialized = true
+    //   this.loadAllSongs()
+    // })
     
     LogUtil.info('heanup AddSongsToPlaylistDialogContent aboutToAppear 结束')
   }
@@ -41,66 +46,70 @@ struct AddSongsToPlaylistDialogContent {
   /**
    * 加载所有歌曲
    */
-  async loadAllSongs() {
-    if (!this.isDbInitialized) {
-      LogUtil.warn('heanup 数据库未初始化,等待初始化完成')
-      return
-    }
-    
-    try {
-      LogUtil.info('heanup loadAllSongs 开始')
-      this.isLoading = true
-      LogUtil.info('heanup 开始查询所有歌曲')
-      this.allSongs = await this.mediaTable.queryAllVideos()
-      LogUtil.info('heanup 查询到 ' + this.allSongs.length + ' 首歌曲')
-      this.filteredSongs = [...this.allSongs]
-      
-      // 过滤掉已经在歌单中的歌曲
-      if (this.playlist) {
-        LogUtil.info('heanup 开始查询歌单中的歌曲,歌单ID: ' + this.playlist.id)
-        const playlistSongs = await this.playlistTable.queryPlaylistSongs(this.playlist.id)
-        LogUtil.info('heanup 歌单中有 ' + playlistSongs.length + ' 首歌曲')
-        const playlistSongPaths = playlistSongs.map(song => song.songFilePath)
-        this.filteredSongs = this.filteredSongs.filter(song => !playlistSongPaths.includes(song.filePath))
-        this.allSongs = [...this.filteredSongs]
-        LogUtil.info('heanup 过滤后有 ' + this.filteredSongs.length + ' 首歌曲可添加')
-      } else {
-        LogUtil.warn('heanup playlist 为 null')
-      }
-    } catch (error) {
-      LogUtil.error('heanup 加载歌曲列表失败: ' + error)
-      ToastUtil.showToast('加载歌曲列表失败')
-    } finally {
-      LogUtil.info('heanup 设置 isLoading 为 false')
-      this.isLoading = false
-    }
-  }
+  // async loadAllSongs() {
+  //   if (!this.isDbInitialized) {
+  //     LogUtil.warn('heanup 数据库未初始化,等待初始化完成')
+  //     return
+  //   }
+  //
+  //   try {
+  //     LogUtil.info('heanup loadAllSongs 开始')
+  //     this.isLoading = true
+  //     LogUtil.info('heanup 开始查询所有歌曲')
+  //     // this.allSongs = await this.mediaTable.queryAllVideos()
+  //     // LogUtil.info('heanup 查询到 ' + this.allSongs.length + ' 首歌曲')
+  //     this.filteredSongs = [...this.allSongs]
+  //
+  //     // 过滤掉已经在歌单中的歌曲
+  //     if (this.playlist) {
+  //       LogUtil.info('heanup 开始查询歌单中的歌曲,歌单ID: ' + this.playlist.id)
+  //       const playlistSongs = await this.playlistTable.queryPlaylistSongs(this.playlist.id)
+  //       LogUtil.info('heanup 歌单中有 ' + playlistSongs.length + ' 首歌曲')
+  //       const playlistSongPaths = playlistSongs.map(song => song.songFilePath)
+  //       this.filteredSongs = this.filteredSongs.filter(song => !playlistSongPaths.includes(song.filePath))
+  //       this.allSongs = [...this.filteredSongs]
+  //       LogUtil.info('heanup 过滤后有 ' + this.filteredSongs.length + ' 首歌曲可添加')
+  //     } else {
+  //       LogUtil.warn('heanup playlist 为 null')
+  //     }
+  //   } catch (error) {
+  //     LogUtil.error('heanup 加载歌曲列表失败: ' + error)
+  //     ToastUtil.showToast('加载歌曲列表失败')
+  //   } finally {
+  //     LogUtil.info('heanup 设置 isLoading 为 false')
+  //     this.isLoading = false
+  //   }
+  // }
 
   /**
    * 搜索过滤歌曲
    */
   filterSongs() {
+    this.isSearchMode = true
     if (!this.searchText.trim()) {
-      this.filteredSongs = [...this.allSongs]
+      this.filteredSongs = [...this.mediaKuList]
     } else {
       const searchLower = this.searchText.toLowerCase()
-      this.filteredSongs = this.allSongs.filter(song => 
+      this.filteredSongs = this.mediaKuList.filter(song =>
         (song.name && song.name.toLowerCase().includes(searchLower)) ||
         (song.artist && song.artist.toLowerCase().includes(searchLower)) ||
         (song.album && song.album.toLowerCase().includes(searchLower))
       )
     }
+    this.updateListData(this.filteredSongs)
+  }
+
+  updateListData(mList: Array<VideoItem>) {
+    //只展示100条,不然会报错
+    setTimeout(() => {
+      this.dataSource.pushArrayData(mList.slice(0,  100))
+
+    }, 200);
+
   }
 
   build() {
     Column({ space: 16 }) {
-      // 标题
-      Text('添加歌曲到歌单')
-        .fontSize(18)
-        .fontWeight(FontWeight.Bold)
-        .fontColor($r('app.color.text_color'))
-        .margin({ top: 20 })
-
       // 搜索框
       Row({ space: 8 }) {
         Image($r('app.media.ic_action_search'))
@@ -167,7 +176,7 @@ struct AddSongsToPlaylistDialogContent {
         .width('100%')
         .height(300)
         .justifyContent(FlexAlign.Center)
-      } else if (this.filteredSongs.length === 0) {
+      } else if (this.filteredSongs.length === 0&&this.isSearchMode) {
         Column({ space: 12 }) {
           Image($r('app.media.music_red'))
             .width(64)
@@ -184,83 +193,77 @@ struct AddSongsToPlaylistDialogContent {
       } else {
         Scroll() {
           Column({ space: 0 }) {
-            ForEach(this.filteredSongs, (song: VideoItem) => {
-              Row({ space: 12 }) {
-                // 选择框
-                Checkbox({ name: 'song_' + song.id })
-                  .select(this.selectedSongs.some(s => s.id === song.id))
-                  .selectedColor($r('app.color.theme_color'))
-                  .shape(CheckBoxShape.ROUNDED_SQUARE)
-                  .onChange((checked: boolean) => {
-                    if (checked) {
-                      if (!this.selectedSongs.some(s => s.id === song.id)) {
-                        this.selectedSongs.push(song)
-                      }
-                    } else {
-                      const index = this.selectedSongs.findIndex(s => s.id === song.id)
-                      if (index > -1) {
-                        this.selectedSongs.splice(index, 1)
-                      }
-                    }
-                  })
-
-                // 歌曲信息
-                Column({ space: 4 }) {
-                  Text(song.name || '未知歌曲')
-                    .fontSize(14)
-                    .fontColor($r('app.color.text_color'))
-                    .maxLines(1)
-                    .textOverflow({ overflow: TextOverflow.Ellipsis })
-                    .width('100%')
+            List({ scroller: this.listScroller }) {
+              LazyForEach(this.dataSource, (song: VideoItem, index: number) => {
+                ListItem() {
+                  Row({ space: 12 }) {
+                    // 选择框
+                    Checkbox({ name: 'song_' + song.id })
+                      .select(this.selectedSongs.some(s => s.id === song.id))
+                      .selectedColor($r('app.color.theme_color'))
+                      .shape(CheckBoxShape.ROUNDED_SQUARE)
+                      .onChange((checked: boolean) => {
+                        if (checked) {
+                          if (!this.selectedSongs.some(s => s.id === song.id)) {
+                            this.selectedSongs.push(song)
+                          }
+                        } else {
+                          const index = this.selectedSongs.findIndex(s => s.id === song.id)
+                          if (index > -1) {
+                            this.selectedSongs.splice(index, 1)
+                          }
+                        }
+                      })
 
-                  Row() {
-                    if (song.artist) {
-                      Text(song.artist)
-                        .fontSize(12)
-                        .fontColor('#999999')
+                    // 歌曲信息
+                    Column({ space: 4 }) {
+                      Text(song.name || '未知歌曲')
+                        .fontSize(14)
+                        .fontColor($r('app.color.text_color'))
                         .maxLines(1)
                         .textOverflow({ overflow: TextOverflow.Ellipsis })
-                        .layoutWeight(1)
-                    }
+                        .width('100%')
 
-                    if (song.artist && song.album) {
-                      Text('·')
-                        .fontSize(12)
-                        .fontColor('#999999')
-                    }
+                      Row() {
+                        if (song.artist) {
+                          Text(song.artist)
+                            .fontSize(12)
+                            .fontColor('#999999')
+                            .maxLines(1)
+                            .textOverflow({ overflow: TextOverflow.Ellipsis })
+                            .layoutWeight(1)
+                        }
 
-                    if (song.album) {
-                      Text(song.album)
-                        .fontSize(12)
-                        .fontColor('#999999')
-                        .maxLines(1)
-                        .textOverflow({ overflow: TextOverflow.Ellipsis })
-                        .layoutWeight(1)
+                      }
+                      .width('100%')
                     }
+                    .alignItems(HorizontalAlign.Start)
+                    .layoutWeight(1)
                   }
                   .width('100%')
+                  .padding(12)
+                  .borderRadius(8)
+                  .onClick(() => {
+                    const isSelected = this.selectedSongs.some(s => s.id === song.id)
+                    if (isSelected) {
+                      const index = this.selectedSongs.findIndex(s => s.id === song.id)
+                      if (index > -1) {
+                        this.selectedSongs.splice(index, 1)
+                      }
+                    } else {
+                      this.selectedSongs.push(song)
+                    }
+                  })
                 }
-                .alignItems(HorizontalAlign.Start)
-                .layoutWeight(1)
-              }
-              .width('100%')
-              .padding(12)
-              .borderRadius(8)
-              .onClick(() => {
-                const isSelected = this.selectedSongs.some(s => s.id === song.id)
-                if (isSelected) {
-                  const index = this.selectedSongs.findIndex(s => s.id === song.id)
-                  if (index > -1) {
-                    this.selectedSongs.splice(index, 1)
-                  }
-                } else {
-                  this.selectedSongs.push(song)
-                }
-              })
-            }, (song: VideoItem) => song.id)
+
+              }, (song: VideoItem) => song.id)
+            }
+            .cachedCount(6)
           }
+
         }
         .scrollBar(BarState.Auto)
+
         .scrollable(ScrollDirection.Vertical)
         .height(300)
       }
@@ -296,7 +299,7 @@ struct AddSongsToPlaylistDialogContent {
       .justifyContent(FlexAlign.SpaceBetween)
       .margin({ top: 20, bottom: 20 })
     }
-    .width('90%')
+    .width('100%')
     .constraintSize({ maxWidth: 400 })
     .backgroundColor($r('app.color.dialog_background'))
     .borderRadius(12)
@@ -329,11 +332,13 @@ export struct AddSongsToPlaylistDialogManager {
   buildAddSongsToPlaylistDialog(
     playlist: Playlist,
     onConfirm: (songs: VideoItem[]) => void,
-    onCancel?: () => void
+    mediaKuList: VideoItem[],
+    onCancel?: () => void,
   ) {
     AddSongsToPlaylistDialogContent({
       playlist: playlist,
       onConfirm: onConfirm,
+      mediaKuList: mediaKuList,
       onCancel: onCancel
     })
   }
@@ -344,14 +349,15 @@ export struct AddSongsToPlaylistDialogManager {
   showAddSongsToPlaylistDialog(
     playlist: Playlist,
     onConfirm: (songs: VideoItem[]) => void,
-    onCancel?: () => void
+    mediaKuList: VideoItem[],
+    onCancel?: () => void,
   ) {
     DialogHelper.showCustomContentDialog({
       dialogId: 'addSongsToPlaylistDialog',
       title: '添加歌曲到歌单',
       autoCancel: true,
       contentBuilder: () => {
-        this.buildAddSongsToPlaylistDialog(playlist, onConfirm, onCancel)
+        this.buildAddSongsToPlaylistDialog(playlist, onConfirm, mediaKuList,onCancel)
       },
       buttons: []
     })
@@ -370,7 +376,8 @@ const dialogManager = new AddSongsToPlaylistDialogManager()
 export function showAddSongsToPlaylistDialog(
   playlist: Playlist,
   onConfirm: (songs: VideoItem[]) => void,
-  onCancel?: () => void
+  mediaKuList: VideoItem[],
+  onCancel?: () => void,
 ) {
-  dialogManager.showAddSongsToPlaylistDialog(playlist, onConfirm, onCancel)
+  dialogManager.showAddSongsToPlaylistDialog(playlist, onConfirm, mediaKuList,onCancel)
 }

+ 11 - 6
entry/src/main/ets/pages/PlaylistDetailPage.ets

@@ -31,6 +31,7 @@ interface PlaylistEventData {
 @Component
 export struct PlaylistDetailPage {
   context = this.getUIContext().getHostContext() as common.UIAbilityContext
+  @StorageProp('mediaKuList')  mediaKuList: Array<VideoItem> = []; //媒体库文件
   @State playlist: Playlist | null = null
   @State songList: VideoItem[] = []
   @State isLoading: boolean = true
@@ -58,7 +59,7 @@ export struct PlaylistDetailPage {
       this.playlistId = this.playlist.id
       this.loadPlaylistDetail()
     }
-
+    console.info('onecold mediaKuList 歌单详情页面 aboutToAppear='+this.mediaKuList.length)
     // 监听播放状态变化
     this.setupPlaybackStatusListener()
   }
@@ -695,9 +696,11 @@ export struct PlaylistDetailPage {
             // 添加歌曲按钮
             Button() {
               Row({ space: 6 }) {
-                Text('+')
-                  .fontSize(18)
-                  .fontColor(Color.White)
+                SymbolGlyph($r('sys.symbol.plus'))
+                  .fontSize(22)
+                  .fontColor([this.themeColor])
+                  .effectStrategy(SymbolEffectStrategy.HIERARCHICAL)
+                  .alignSelf(ItemAlign.Center)
 
                 Text('添加歌曲')
                   .fontSize(14)
@@ -1012,7 +1015,8 @@ export struct PlaylistDetailPage {
                     } else {
                       ToastUtil.showToast('添加歌曲失败')
                     }
-                  }
+                  },
+                  this.mediaKuList!
                 )
               })
               .stateStyles({
@@ -1106,7 +1110,8 @@ export struct PlaylistDetailPage {
           } else {
             ToastUtil.showToast('添加歌曲失败')
           }
-        }
+        },
+        this.mediaKuList
       )
     }
   }

+ 3 - 2
entry/src/main/ets/view/LocalMusic.ets

@@ -204,7 +204,8 @@ export struct LocalMusic {
   @State dirList: Array<VideoItem> = []
   @Consume videoLocalList: Array<VideoItem>
   @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
-  @State mediaKuList: Array<VideoItem> = []; //媒体库文件
+  // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
+  @StorageProp('mediaKuList')  mediaKuList: Array<VideoItem> = []; //媒体库文件
   @State artistList: Array<VideoItem> = []; //艺术家文件
   @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
   @State albumList: Array<VideoItem> = []; //专辑文件
@@ -916,7 +917,7 @@ export struct LocalMusic {
           this.mediaKuList = e.data.data
           Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
           Utility.doSortListAscending(this.mediaKuList)
-          // AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
+          AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
           if (this.modeType === 1) {
             this.updateListData(this.mediaKuList)
           }