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 { 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'
import { MP4Parser } from '@ohos/mp4parser'
import { QCloud } from 'qcloudfileflash'
import { Constants } from '../../../../common/Constants'
import { VoiceRecognizeResultEntity } from '../../../../entity/VoiceRecognizeResultEntity'
import { plainToInstance } from 'class-transformer'

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

  videoToAudio() {
    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.videoUri!!, fileIo.OpenMode.READ_ONLY)
    // 复制文件到缓存目录下
    FileUtil.copyFileSync(file.fd, cachePath)
    FileUtil.closeSync(file)

    let outputPath = FileUtil.getCacheDirPath() + FileUtil.separator + `scmf_${systemDateTime.getTime()}.mp3`
    let cmd = `ffmpeg -i ${cachePath} -vn -c:a mp3 ${outputPath}`
    MP4Parser.ffmpegCmd(cmd, {
      callBackResult: (code: number) => {
        if (code === 0) {
          this.recognizeAudio(outputPath)
            .then((result: VoiceRecognizeResultEntity) => {
              this.resultText = result.flash_result[0].text
              this.isSuccess = true
              this.isPlaying = false
              ToastUtils.show('处理成功')
              LoadingDialog.dismiss()
            })
            .catch((e: BusinessError) => {
              console.log(e.message)
              ToastUtils.show('处理失败')
              LoadingDialog.dismiss()
            })
        } else {
          ToastUtils.show('处理失败')
          LoadingDialog.dismiss()
        }
      }
    })
  }

  async recognizeAudio(uri: string): Promise<VoiceRecognizeResultEntity> {
    let builder = new QCloud.FileFlash.Builder()
    builder.appID = Constants.QCLOUD_APP_ID
    builder.secretID = Constants.QCLOUD_SECRET_ID
    builder.secretKey = Constants.QCLOUD_SECRET_KEY
    // builder.token = this._token
    builder.setApiParam(QCloud.FileFlash.kEngineType, '16k_zh')
    builder.setApiParam(QCloud.FileFlash.kVoiceFormat, 'mp3')
    builder.setApiParam(QCloud.FileFlash.kFilterDirty, 0)
    builder.setApiParam(QCloud.FileFlash.kFilterModal, 0)
    builder.setApiParam(QCloud.FileFlash.kFilterPunc, 0)
    builder.setApiParam(QCloud.FileFlash.kConvertNumMode, 1)
    builder.setApiParam(QCloud.FileFlash.kWordInfo, 0)
    builder.setApiParam(QCloud.FileFlash.kSpeakerDiarization, 1)
    try {
      let file = FileUtil.openSync(uri, fileIo.OpenMode.READ_ONLY)
      const stat = FileUtil.lstatSync(uri)
      const buffer = new ArrayBuffer(stat.size)
      FileUtil.readSync(file.fd, buffer)
      FileUtil.closeSync(file)
      let result = await builder.build(buffer).task
      const voiceResult = plainToInstance(VoiceRecognizeResultEntity, result)
      return Promise.resolve(voiceResult)
    } catch (e) {
      console.error(e)
      return Promise.reject(e)
    }
  }

  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.videoUri = 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: '视频转文字' })

      Stack() {
        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%')
          .height('100%')
          .onClick(() => {
            this.selectVideo()
          })
          .visibility(this.videoUri ? Visibility.None : Visibility.Visible)

          RelativeContainer() {
            Video({
              src: this.videoUri, // 设置视频源
              controller: this.controller, //设置视频控制器，可以控制视频的播放状态
              posterOptions: { showFirstFrame: true }
            })
              .width('100%')
              .height('100%')
              .borderRadius(20)
              .backgroundColor(Color.White)
              .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%")
            .borderRadius({bottomLeft: 20, bottomRight: 20})
            .backgroundColor('#1A000000')
            .padding({ left: 30, right: 30 })
            .alignRules({
              bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
            })
          }
          .width('100%')
          .height('100%')
          .visibility(this.videoUri ? Visibility.Visible : Visibility.None)
        }
        .width('100%')
        .aspectRatio(1)
        .borderRadius(20)
        .backgroundColor(Color.White)
        .shadow({radius: 10, color: '#1a9399a1'})
      }
      .width('100%')
      .height('auto')
      .padding({left: 32, right: 32})
      .margin({top: 40})

      Column() {
        Row() {
          Image($r('app.media.ic_star')).width(22).height(22)
          Text('文本结果').fontColor($r('app.color.color_212226')).fontSize(15).fontWeight(FontWeight.Medium).margin({left: 4})
        }
        Divider().strokeWidth(1).color($r('app.color.color_eeeeee')).margin({top: 12})
        Text(this.resultText).width('100%').height('auto').fontColor($r('app.color.color_212226')).fontSize(14).margin({top: 14})
      }
      .width('90%')
      .layoutWeight(1)
      .borderRadius(10)
      .borderWidth(1)
      .borderColor('#DADEE5')
      .backgroundColor(Color.White)
      .margin({top: 30, bottom: 20})
      .padding(12)
      .visibility(this.resultText ? Visibility.Visible : Visibility.None)

      Blank().layoutWeight(1).visibility(this.resultText ? 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.videoUri) {
              this.videoToAudio()
            } 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_copy_text')).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.videoUri!!])
              .then((saved) => {
                if (saved) {
                  this.videoUri = 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'))
  }
}