import { PhotoHelper } from '@pura/picker_utils'
import { TitleBar } from '../../../../view/TitleBar'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { BusinessError, systemDateTime } from '@kit.BasicServicesKit'
import { AppUtil, FileUtil } from '@pura/harmony-utils'
import { ToastUtils } from '../../../../utils/ToastUtils'
import { fileIo } from '@kit.CoreFileKit'
import { SaveUtils } from '../../../../utils/SaveUtils'
import { MP4Parser } from '@ohos/mp4parser'
import { LoadingDialog } from '../../../../dialog/LoadingDialog'
import { DownloadDialog, DownloadStatus } from '../../../../dialog/DownloadDialog'
import { EventConstants } from '../../../../common/EventConstants'
import { TipDialog } from '../../../../dialog/TipDialog'
import { avSessionManager } from '../../../../manager/AVSessionManager'

@Entry
@ComponentV2
struct RemoveAudioPage {
  private controller: VideoController = new VideoController()
  @Local uri?: string
  @Local currentTime: number = 0
  @Local durationTime: number = 0
  @Local isPlaying: boolean = false
  @Local isSuccess: boolean = false

  mirrorVideo() {
    LoadingDialog.show(this.getUIContext())
    this.isSuccess = false
    let cachePath = FileUtil.getCacheDirPath() + FileUtil.separator + `cache_${systemDateTime.getTime()}.mp4`
    if (FileUtil.accessSync(cachePath)) {
      FileUtil.unlinkSync(cachePath)
    }
    let file = FileUtil.openSync(this.uri!!, fileIo.OpenMode.READ_ONLY)
    // 复制文件到缓存目录下
    FileUtil.copyFileSync(file.fd, cachePath)

    let outputPath = FileUtil.getCacheDirPath() + FileUtil.separator + `kcsp_${systemDateTime.getTime()}.mp4`
    let cmd = `ffmpeg -i ${cachePath} -an -c:v copy ${outputPath}`
    MP4Parser.ffmpegCmd(cmd, {
      callBackResult: (code: number) => {
        if (code === 0) {
          this.uri = FileUtil.getUriFromPath(outputPath)
          this.isSuccess = true
          this.isPlaying = false
          ToastUtils.show('处理成功')
        } else {
          ToastUtils.show('处理失败')
        }
        LoadingDialog.dismiss()
      }
    })
  }

  selectVideo() {
    PhotoHelper.selectEasy({
      MIMEType: photoAccessHelper.PhotoViewMIMETypes.VIDEO_TYPE,
      maxSelectNumber: 1,
      isPhotoTakingSupported: false,
      isEditSupported: false,
      isOriginalSupported: false
    })
      .then((uris) => {
        if (uris.length != 0) {
          this.isSuccess = false
          this.uri = uris[0]
        }
      })
  }

  showDownloadDialog() {
    DownloadDialog.show(this.getUIContext(), { status: DownloadStatus.COMPLETED, totalSize: 0, progress: 0, totalCount: 1, index: 0, callback: {
      confirm: () => {
        AppUtil.getContext().eventHub.emit(EventConstants.JumpToRecordEvent, 0)
        this.getUIContext().getRouter().back()
      }
    } })
  }

  formatTime(time: number): string {
    let minute: number = 0
    let second: number = 0
    if (time > 60) {
      minute = Math.trunc(time / 60)
      second = time % 60
      if (minute < 10) {
        if (second < 10) {
          return `0${minute}:0${second}`
        } else {
          return `0${minute}:${second}`
        }
      } else {
        if (second < 10) {
          return `${minute}:0${second}`
        } else {
          return `${minute}:${second}`
        }
      }
    } else {
      second = time
      if (second < 10) {
        return `00:0${second}`
      } else {
        return `00:${second}`
      }
    }
  }

  onBackPress(): boolean | void {
    if (this.isSuccess) {
      TipDialog.show(this.getUIContext(), {title:'温馨提示', content:'视频尚未保存，是否确定退出？', callback: {
        confirm: () => {
          this.getUIContext().getRouter().back()
        }
      }})
      return true
    }
    return false
  }

  build() {
    Column() {
      TitleBar({ title: '去音乐' })

      Column() {
        Row() {
          Text('上传视频').fontColor($r('app.color.color_90ffffff')).fontSize(16).fontWeight(FontWeight.Medium)
          Text('（仅支持mp4格式）').fontColor($r('app.color.color_50ffffff')).fontSize(12)
        }.alignSelf(ItemAlign.Start)

        RelativeContainer() {
          Stack() {
            Image($r('app.media.ic_add_video')).width(44).height(44)
          }
          .width(140)
          .height(140)
          .borderRadius(10)
          .backgroundColor($r('app.color.color_333333'))
          .alignRules({
            start: { anchor: '__container__', align: HorizontalAlign.Start },
            top: { anchor: '__container__', align: VerticalAlign.Top },
            end: { anchor: '__container__', align: HorizontalAlign.End },
            bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
          })
          .onClick(() => {
            this.selectVideo()
          })
        }
        .height(220)
        .margin({ top: 12 })
        .borderRadius(8)
        .backgroundColor($r('app.color.color_222222'))
      }.margin({ left: 16, top: 16, right: 16 })
      .visibility(this.uri ? Visibility.None : Visibility.Visible)

      Column() {
        RelativeContainer() {
          Video({
            src: this.uri, // 设置视频源
            controller: this.controller, //设置视频控制器，可以控制视频的播放状态
            posterOptions: { showFirstFrame: true }
          })
            .width('100%')
            .height('100%')
            .backgroundColor($r('app.color.window_background'))
            .controls(false) // 设置是否显示默认控制条
            .autoPlay(false) // 设置是否自动播放
            .loop(false) // 设置是否循环播放
            .objectFit(ImageFit.Contain) // 设置视频填充模式
            .onPrepared((event) => {
              if (event) {
                this.durationTime = event.duration
              }
            })
            .onUpdate((event) => {
              if (event) {
                this.currentTime = event.time
              }
            })
            .onStart(() => {
              this.isPlaying = true
            })
            .onPause(() => {
              this.isPlaying = false
              avSessionManager.deactivate()
            })
            .onStop(() => {
              this.isPlaying = false
              avSessionManager.deactivate()
            })
            .onFinish(() => {
              this.isPlaying = false
              avSessionManager.deactivate()
            })
            .onError(() => {
              this.isPlaying = false
              avSessionManager.deactivate()
            })
            .onDisAppear(() => {
              avSessionManager.deactivate()
            })

          Image($r('app.media.ic_play_video'))
            .width(50)
            .height(50)
            .visibility(this.isPlaying ? Visibility.None : Visibility.Visible)
            .onClick(async () => {
              await avSessionManager.activate()
              this.controller.start()
            })
            .alignRules({
              left: { anchor: '__container__', align: HorizontalAlign.Start },
              top: { anchor: '__container__', align: VerticalAlign.Top },
              right: { anchor: '__container__', align: HorizontalAlign.End },
              bottom: { anchor: '__container__', align: VerticalAlign.Bottom },
            })

          Row() {
            Image(this.isPlaying ? $r('app.media.ic_player_controls_pause') : $r('app.media.ic_player_controls_play'))
              .width(20)
              .height(20)
              .margin({ right: 20 })
              .onClick(async () => {
                if (this.isPlaying) {
                  this.controller.pause()
                } else {
                  await avSessionManager.activate()
                  this.controller.start()
                }
              })
            Text(this.formatTime(this.currentTime)).width(35).fontColor(Color.White).fontSize(12)
            Slider({
              value: this.currentTime,
              min: 0,
              max: this.durationTime
            })
              .blockColor(Color.White)
              .trackColor($r('app.color.color_60ffffff'))
              .onChange((value: number, mode: SliderChangeMode) => {
                this.controller.setCurrentTime(value); // 设置视频播放的进度跳转到value处
              })
              .layoutWeight(1)
            Text(this.formatTime(this.durationTime)).width(35).fontColor(Color.White).fontSize(12)
          }
          .opacity(0.8)
          .width("100%")
          .padding({ left: 30, right: 30 })
          .alignRules({
            bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
          })
        }
        .layoutWeight(1)

        Row() {
          Text(this.isSuccess ? '重新上传' : '取消').fontColor($r('app.color.color_90ffffff')).fontSize(17).margin({ left: 16 })
            .onClick(() => {
              this.controller.stop()
              if (this.isSuccess) {
                this.selectVideo()
              } else {
                this.getUIContext().getRouter().back()
              }
            })
          Blank().layoutWeight(1)
          Text(this.isSuccess ? '保存' : '确定').fontColor($r("app.color.color_466afd")).fontSize(17).margin({ right: 16 })
            .onClick(() => {
              this.controller.stop()
              if (this.isSuccess) {
                SaveUtils.saveImageVideoToAlbumDialog([this.uri!!])
                  .then((saved) => {
                    if (saved) {
                      this.uri = undefined
                      this.showDownloadDialog()
                    } else {
                      ToastUtils.show('保存失败')
                    }
                  })
                  .catch((e: BusinessError) => {
                    ToastUtils.show('保存失败：' + e.message)
                  })

              } else {
                this.mirrorVideo()
              }
            })
        }
        .margin({ top: 140, bottom: 30 })
      }
      .layoutWeight(1)
      .visibility(this.uri ? Visibility.Visible : Visibility.None)
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.window_background'))
  }
}