import { PhotoHelper } from '@pura/picker_utils'
import { TitleBar } from '../../../../view/TitleBar'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { BusinessError, systemDateTime } from '@kit.BasicServicesKit'
import { AppUtil, DisplayUtil, FileUtil, ImageUtil, StrUtil } from '@pura/harmony-utils'
import { ToastUtils } from '../../../../utils/ToastUtils'
import { fileIo } from '@kit.CoreFileKit'
import { SaveUtils } from '../../../../utils/SaveUtils'
import { LoadingDialog } from '../../../../dialog/LoadingDialog'
import { DownloadDialog, DownloadStatus } from '../../../../dialog/DownloadDialog'
import { EventConstants } from '../../../../common/EventConstants'
import { RectPosition } from '../../../../view/RectCropView'
import { media } from '@kit.MediaKit'
import { MediaUtils } from '../../../../utils/MediaUtils'
import { MP4Parser } from '@ohos/mp4parser'
import { TipDialog } from '../../../../dialog/TipDialog'
import { WaterMarkerView } from '../../../../view/WaterMarkerView'
import { EditTextDialog } from '../../../../dialog/EditTextDialog'
import { image } from '@kit.ImageKit'
import { avSessionManager } from '../../../../manager/AVSessionManager'
import { SelectBoundsView } from '../../../../view/SelectBoundsView'

@Entry
@ComponentV2
struct RemoveWatermarkPage {
  @Local uri?: string
  @Local currentTime: number = 0
  @Local durationTime: number = 0
  @Local isPlaying: boolean = false
  @Local isSuccess: boolean = false
  @Local playerSize: media.PixelMapParams = { width: 0, height: 0 }

  @Local showBound: boolean = false

  private controller: VideoController = new VideoController()
  private videoSize: media.PixelMapParams = { width: 0, height: 0 }
  private rect: RectPosition = { x: 0, y: 0, width: 0, height: 0 }

  addWatermark() {
    LoadingDialog.show(this.getUIContext())
    this.isSuccess = false
    let cacheVideoPath = FileUtil.getCacheDirPath() + FileUtil.separator + `scmf_${systemDateTime.getTime()}.mp4`
    if (FileUtil.accessSync(cacheVideoPath)) {
      FileUtil.unlinkSync(cacheVideoPath)
    }

    let file = FileUtil.openSync(this.uri!!, fileIo.OpenMode.READ_ONLY)
    // 复制文件到缓存目录下
    FileUtil.copyFileSync(file.fd, cacheVideoPath)
    FileUtil.closeSync(file)

    let rectX = (vp2px(this.rect.x) * this.videoSize.width!!) / this.playerSize.width!!
    let rectY = (vp2px(this.rect.y) * this.videoSize.height!!) / this.playerSize.height!!

    let rectWidth = (vp2px(this.rect.width * this.videoSize.width!!) / this.playerSize.width!!)
    let rectHeight = (vp2px(this.rect.height * this.videoSize.height!!) / this.playerSize.height!!)

    let outputPath = FileUtil.getCacheDirPath() + FileUtil.separator + `scmf_${systemDateTime.getTime()}.mp4`
    let cmd = `ffmpeg -i ${cacheVideoPath} -filter_complex "[0:v]crop=${Math.round(rectWidth)}:${Math.round(rectHeight)}:${rectX}:${rectY},avgblur=15:15[fg]; [0:v][fg]overlay=${rectX}:${rectY}" -c:v h264 -pix_fmt yuv420p -y ${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]
          this.showBound = false
          MediaUtils.getVideoSize(this.uri)
            .then((size) => {
              this.videoSize = size
              if (size.width && size.height) {
                const ratio = (DisplayUtil.getWidth() - 300) / size.width
                this.playerSize = {width: Math.ceil(size.width * ratio), height: Math.ceil(size.height * ratio)}
              }
            })
        }
      })
  }

  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: '视频去水印' })

      Stack() {
        Stack() {
          Column() {
            Image($r('app.media.ic_add_video')).width(40).height(40)
            Text('请上传视频').fontColor($r('app.color.color_466afd')).fontSize(15).fontWeight(FontWeight.Medium).margin({ top: 8})
          }
        }
        .width('100%')
        .aspectRatio(1)
        .borderRadius(20)
        .backgroundColor(Color.White)
        .shadow({radius: 10, color: '#1a9399a1'})
        .onClick(() => {
          this.selectVideo()
        })
      }
      .width('100%')
      .height('auto')
      .padding({left: 32, right: 32})
      .margin({top: 40})
      .visibility(this.uri ? Visibility.None : Visibility.Visible)

      Column() {
        RelativeContainer() {
          Video({
            src: this.uri, // 设置视频源
            controller: this.controller, //设置视频控制器，可以控制视频的播放状态
            posterOptions: { showFirstFrame: true }
          })
            .id('video')
            .width(this.playerSize ? px2vp(this.playerSize.width) : '100%')
            .height(this.playerSize ? px2vp(this.playerSize.height) : '100%')
            .backgroundColor($r('app.color.window_background'))
            .controls(false) // 设置是否显示默认控制条
            .autoPlay(false) // 设置是否自动播放
            .loop(false) // 设置是否循环播放
            .objectFit(ImageFit.Cover) // 设置视频填充模式
            .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 }
            })
            .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: 'video', align: HorizontalAlign.Start },
              top: { anchor: 'video', align: VerticalAlign.Top },
              right: { anchor: 'video', align: HorizontalAlign.End },
              bottom: { anchor: 'video', 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(this.playerSize ? px2vp(this.playerSize.width) : "100%")
          .alignRules({
            left: { anchor: 'video', align: HorizontalAlign.Start },
            right: { anchor: 'video', align: HorizontalAlign.End },
            bottom: { anchor: 'video', align: VerticalAlign.Bottom }
          })

          if (this.showBound && this.uri && !this.isSuccess) {
            SelectBoundsView({
              onRectChange: (rect) => {
                this.rect = rect
              },
              onClose: () => {
                this.showBound = false
              }
            })
              .width(this.playerSize ? px2vp(this.playerSize.width) : '100%')
              .height(this.playerSize ? px2vp(this.playerSize.height) : '100%')
              .alignRules({
                left: { anchor: 'video', align: HorizontalAlign.Start },
                top: { anchor: 'video', align: VerticalAlign.Top },
                right: { anchor: 'video', align: HorizontalAlign.End },
                bottom: { anchor: 'video', align: VerticalAlign.Bottom }
              })
          }
        }
        .layoutWeight(1)

        Stack() {
          Column(){
            Image($r('app.media.ic_remove_watermark')).width(26).height(26)
            Text('马赛克').fontColor($r('app.color.color_212226')).fontSize(12).margin({ top: 8 })
          }
          .onClick(() => {
            if (!this.showBound) {
              this.controller.stop()
              this.showBound = true
            }
          })
        }
        .width(82)
        .height(82)
        .margin({ top: 20, bottom: 20 })
        .borderRadius(10)
        .backgroundColor(Color.White)
      }
      .layoutWeight(1)
      .visibility(this.uri ? Visibility.Visible : Visibility.None)

      Blank().layoutWeight(1).visibility(this.uri ? Visibility.None : Visibility.Visible)

      Stack() {
        Button('确认处理', { type: ButtonType.Capsule, stateEffect: true })
          .width('100%')
          .height(46)
          .fontColor(Color.White)
          .fontSize(15)
          .fontWeight(FontWeight.Medium)
          .backgroundColor($r('app.color.color_466afd'))
          .onClick(() => {
            if (this.uri) {
              this.addWatermark()
            } else {
              ToastUtils.show('请上传视频')
            }
          })
          .visibility(!this.isSuccess ? Visibility.Visible : Visibility.None)

        Row() {
          Button({ type: ButtonType.Capsule, stateEffect: true }) {
            Row() {
              Image($r('app.media.ic_reupload')).width(20).height(20)
              Text('重新上传').fontColor($r('app.color.color_466afd')).fontSize(15).fontWeight(FontWeight.Medium)
            }
          }
          .height(46)
          .layoutWeight(1)
          .borderWidth(1)
          .borderColor($r('app.color.color_466afd'))
          .backgroundColor(Color.Transparent)
          .onClick(() => {
            this.controller.stop()
            this.selectVideo()
          })

          Blank().width(9)

          Button({ type: ButtonType.Capsule, stateEffect: true }) {
            Row() {
              Image($r('app.media.ic_download3')).width(20).height(20)
              Text('保存').fontColor(Color.White).fontSize(15).fontWeight(FontWeight.Medium)
            }
          }
          .height(46)
          .layoutWeight(1)
          .backgroundColor($r('app.color.color_466afd'))
          .onClick(() => {
            this.controller.stop()
            SaveUtils.saveImageVideoToAlbumDialog([this.uri!!])
              .then((saved) => {
                if (saved) {
                  this.uri = undefined
                  this.showDownloadDialog()
                } else {
                  ToastUtils.show('保存失败')
                }
              })
              .catch((e: BusinessError) => {
                ToastUtils.show('保存失败：' + e.message)
              })
          })
        }
        .visibility(this.isSuccess ? Visibility.Visible : Visibility.None)
      }
      .padding({left: 16, top: 9, right: 16, bottom: 30 })
      .backgroundColor(Color.White)
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.window_background'))
  }
}