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 { avSessionManager } from '../../../../manager/AVSessionManager'

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

  takeAudio() {
    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()}.mp3`
    let cmd = `ffmpeg -i ${cachePath} -vn -c:a mp3 ${outputPath}`
    MP4Parser.ffmpegCmd(cmd, {
      callBackResult: (code: number) => {
        if (code === 0) {
          SaveUtils.saveAudioToMusic([outputPath])
            .then(() => {
              this.uri = undefined
              this.isSuccess = true
              this.isPlaying = false
              this.showDownloadDialog()
            })
            .catch((e: BusinessError) => {
              ToastUtils.show('提取失败：' + e.message)
            })
        } 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, isAudio: true, totalSize: 0, progress: 0, totalCount: 1, index: 0, callback: {
      confirm: () => {
        AppUtil.getContext().eventHub.emit(EventConstants.JumpToRecordEvent, 2)
        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}`
      }
    }
  }

  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() {
            Stack() {
              Image($r('app.media.ic_add_video')).width(44).height(44)
            }
            .width(140)
            .height(140)
            .borderRadius(10)
            .backgroundColor($r('app.color.color_333333'))
            .margin({top: 40})
            .onClick(() => {
              this.selectVideo()
            })
            .visibility(this.uri ? Visibility.None : Visibility.Visible)

            RelativeContainer() {
              Video({
                src: this.uri, // 设置视频源
                controller: this.controller, //设置视频控制器，可以控制视频的播放状态
                posterOptions: { showFirstFrame: true }
              })
                .width('100%')
                .height('100%')
                .borderRadius(12)
                .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: 20, right: 20 })
              .alignRules({
                bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
              })
            }
            .height(350)
            .margin({top: 50})
            .visibility(this.uri ? Visibility.Visible : Visibility.None)
          }
          .alignRules({
            start: { anchor: '__container__', align: HorizontalAlign.Start },
            end: { anchor: '__container__', align: HorizontalAlign.End }
          })
          .id('layout_content')

          Image($r('app.media.ic_reupload_video')).width(20).height(20)
            .alignRules({
              right: {anchor: '__container__', align: HorizontalAlign.End}
            })
            .margin({top: 20})
            .onClick(() => {
              this.controller.stop()
              this.selectVideo()
            })
            .visibility(this.uri ? Visibility.Visible : Visibility.None)

          Button('确认提取', {type: ButtonType.Capsule ,stateEffect:true})
            .width('100%')
            .height(42)
            .fontColor($r('app.color.color_90ffffff'))
            .fontSize(16)
            .linearGradient({
              colors: [['#F62C6C', 0.0], ['#FC4F54', 1.0]],
              direction: GradientDirection.Right
            })
            .alignRules({
              top: {anchor: 'layout_content', align: VerticalAlign.Bottom}
            })
            .margin({top: 40})
            .onClick(() => {
              if (this.uri) {
                this.takeAudio()
              } else {
                ToastUtils.show('请先上传视频')
              }
            })
        }
        .height('auto')
        .margin({ top: 12 })
        .borderRadius(8)
        .backgroundColor($r('app.color.color_222222'))
        .padding({left: 20, right: 20, bottom: 30})
      }.margin({ left: 16, top: 16, right: 16 })
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.window_background'))
  }
}