import { TitleBar } from '../../view/TitleBar'
import { ShareManager } from '../../manager/ShareManager'
import { PrefUtils } from '../../utils/PrefUtils'
import { SimpleTipDialog } from '../../dialog/SimpleTipDialog'
import { WantUtils } from '../../utils/WantUtils'
import { avSessionManager } from '../../manager/AVSessionManager'

@Entry
@ComponentV2
struct VideoPlayerPage {
  private controller: VideoController = new VideoController()
  @Local title: string = ''
  @Local uri: string = ''
  @Local showActions: boolean = false
  @Local currentTime: number = 0
  @Local durationTime: number = 0
  @Local isPlaying: boolean = false

  aboutToAppear(): void {
    this.initParams()
  }

  initParams() {
    const params = this.getUIContext().getRouter().getParams() as Record<string, Object>;
    if (params) {
      this.title = params.title as string
      this.uri = params.uri as string;
      this.showActions = params.showActions as boolean
    }
  }

  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({isDark: true}).width('100%')

      RelativeContainer() {
        Video({
          src: this.uri, // 设置视频源
          controller: this.controller, //设置视频控制器，可以控制视频的播放状态
          posterOptions: { showFirstFrame: true }
        })
          .width('100%')
          .height('100%')
          .backgroundColor(Color.Black)
          .controls(false) // 设置是否显示默认控制条
          .autoPlay(true) // 设置是否自动播放
          .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 })
        .margin({ bottom: 50 })
        .alignRules({
          bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
        })
      }.layoutWeight(1)

      Row() {
        Column() {
          Image($r('app.media.ic_action_share')).width(50).height(50)
          Text('转发').fontSize(12).fontColor($r('app.color.color_50ffffff')).margin({ top: 13 })
        }
        .id('btn_share')
        .alignRules({
          right: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .margin({ right: 40 })
        .onClick(() => {
          ShareManager.shareFile(this.uri)
        })

        Column() {
          Image($r('app.media.ic_action_delete')).width(50).height(50)
          Text('删除').fontSize(12).fontColor($r('app.color.color_50ffffff')).margin({ top: 13 })
        }
        .id('btn_delete')
        .alignRules({
          left: { anchor: '__container__', align: HorizontalAlign.Center },
        })
        .margin({ left: 40 })
        .onClick(() => {
          this.controller.pause()
          if (PrefUtils.getBoolean('show_record_delete_tip', true)) {
            SimpleTipDialog.show(this.getUIContext(), {
              title: '提示', content: '因系统限制，请到相册中手动删除', buttonText: '知道了', callback: {
                confirm: () => {
                  WantUtils.toPhotoGallery()
                  PrefUtils.put('show_record_delete_tip', false)
                }
              }
            })
          } else {
            WantUtils.toPhotoGallery()
          }
        })
      }
      .height(200)
      .margin({ top: 10 })
      .visibility(this.showActions ? Visibility.Visible : Visibility.None)
    }
    .width('100%')
    .height('100%')
    .backgroundColor(Color.Black)
  }
}