import { EmptyView, PageStatus } from '../../../view/EmptyView';
import { AudioRecordItemView, VideoRecordItemView } from '../../../view/RecordItemView';
import { AppUtil, PermissionUtil } from '@pura/harmony-utils';
import { ToastUtils } from '../../../utils/ToastUtils';
import { MediaRecordEntity } from '../../../entity/MediaRecordEntity';
import { EventConstants } from '../../../common/EventConstants';
import { MediaAction, MediaManager, MediaType } from '../../../manager/MediaManager';
import { TipDialog } from '../../../dialog/TipDialog';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { LocalMediaManager } from '../../../manager/LocalMediaManager';
import { fileIo } from '@kit.CoreFileKit';

@ComponentV2
export struct AudioRecordPage {
  @Local mediaList: Array<MediaRecordEntity> = [];
  @Local rowCount: number = 1;
  @Local isCheckAll: boolean = false

  aboutToAppear(): void {
    this.refresh()
    this.initObserver()
  }

  initObserver() {
    AppUtil.getContext().eventHub.on(EventConstants.MediaActionEvent, (type: MediaType, action: MediaAction) => {
      if (type === MediaType.AUDIO) {
        if (action === MediaAction.CLEAR && this.mediaList.length > 0) {
          this.deleteAll()
        } else {
          this.refresh()
        }
      }
    })

    AppUtil.getContext().eventHub.on(EventConstants.RecordRefreshEvent, () => {
      this.refresh()
    })
  }

  async refresh() {
    this.mediaList = await MediaManager.getAudioList()
  }

  deleteAll() {
    TipDialog.show(this.getUIContext(), {
      title: '提示', content: '确定清空音频？', callback: {
        confirm: () => {
          try {
            this.mediaList.forEach((item) => {
              fileIo.unlinkSync(item.uri)
            })
            LocalMediaManager.deleteAllAudios()
            AppUtil.getContext().eventHub.emit(EventConstants.MediaActionEvent, MediaType.AUDIO, MediaAction.DELETE)
            ToastUtils.show('删除成功')
          } catch (e) {
            ToastUtils.show('删除失败, 请到文件管理中手动删除')
          }
        }
      }
    })
  }

  build() {
    Stack() {
      Column() {
        List() {
          ForEach(this.mediaList, (item: MediaRecordEntity, index) => {
            ListItem() {
              AudioRecordItemView({ media: item })
            }
          })
        }
        .width('auto')
        .layoutWeight(1)
        .scrollBar(BarState.Off)
        .margin({ left: 16, right: 16, bottom: 15 })
      }

      EmptyView({
        status: this.mediaList.length > 0 ? PageStatus.GONE : PageStatus.NO_DATA,
        noDataImage: $r('app.media.ic_empty_data'),
        noDataText: '暂无数据'
      })
    }
  }
}