import { ComponentContent } from '@kit.ArkUI';
import { AppUtil, DisplayUtil, FileUtil, FormatUtil, NumberUtil, StrUtil, WindowUtil } from '@pura/harmony-utils';
import { DialogCallback } from '../callback/DialogCallback';

export enum DownloadStatus {
  COMPLETED,
  DOWNLOADING,
  VIDEO_DOWNLOADING,
  AUDIO_DOWNLOADING,
  PROCESSING,
  PROCESSING_PROGRESS,
  TAKING
}

export declare class DownloadDialogOption {
  status: DownloadStatus
  totalSize: number
  progress: number
  totalCount: number
  index: number
  isAudio?: boolean
  callback?: DialogCallback
}

@Builder
function defaultBuilder(option: DownloadDialogOption) {
  Column() {
    Text((option.status === DownloadStatus.DOWNLOADING ? '下载中' :
      option.status === DownloadStatus.VIDEO_DOWNLOADING ? '视频下载中' :
        option.status === DownloadStatus.AUDIO_DOWNLOADING ? '音频下载中' : '处理中') +
      (option.totalCount > 1 ? ` ${option.index + 1}/${option.totalCount}` : ''))
      .fontColor($r('app.color.color_90ffffff'))
      .fontSize(16)
      .visibility(option.status === DownloadStatus.COMPLETED ? Visibility.None : Visibility.Visible)

    Image(option.status === DownloadStatus.COMPLETED ? $r('app.media.ic_completed') : $r('app.media.ic_downloading'))
      .width(80)
      .height(80)
      .margin({ top: 20 })

    Stack() {
      Column() {
        Stack({ alignContent: Alignment.Start }) {
          Progress({ value: option.progress, total: option.totalSize, type: ProgressType.Linear })
            .width('100%')
            .style({ strokeWidth: 12, strokeRadius: 6 })
            .color('#FC4F54')
            .colorBlend($r('app.color.color_10ffffff'))
            .borderRadius(6)

          Text(FormatUtil.getFormatPercentage(option.progress / option.totalSize, 1))
            .width(40)
            .height(18)
            .textAlign(TextAlign.Center)
            .fontColor(Color.White)
            .fontSize(10)
            .borderRadius(10)
            .borderWidth(1)
            .borderColor($r('app.color.color_80ffffff'))
            .backgroundColor($r("app.color.color_466afd"))
            .translate({ x: (AppUtil.getUIContext().px2vp(DisplayUtil.getWidth()) * 0.8 - 80) * option.progress / option.totalSize })
        }

        Text(`${FileUtil.getFormatFileSize(option.progress)}/${option.totalSize !== 0 ?
        FileUtil.getFormatFileSize(option.totalSize) : '获取中'}`)
          .fontColor($r('app.color.color_999999'))
          .fontSize(12)
          .margin({ top: 16 })
          .visibility(option.status === DownloadStatus.PROCESSING ? Visibility.Hidden : Visibility.Visible)

        Row() {
          Button('取消下载', { type: ButtonType.Capsule, stateEffect: true })
            .width(110)
            .height(36)
            .backgroundColor($r('app.color.color_333333'))
            .fontColor($r('app.color.color_50ffffff'))
            .fontSize(15)
            .onClick(() => {
              if (option.callback?.cancel) {
                option.callback.cancel()
              }
              DownloadDialog.dismiss()
            })

          Button('后台下载', { type: ButtonType.Capsule, stateEffect: true })
            .width(110)
            .height(36)
            .linearGradient({
              colors: [['#F62C6C', 0.0], ['#FC4F54', 1.0]],
              direction: GradientDirection.Right
            })
            .fontColor($r('app.color.color_90ffffff'))
            .fontSize(15)
            .margin({ left: 10 })
            .onClick(() => {
              if (option.callback?.confirm) {
                option.callback.confirm()
              }
              DownloadDialog.dismiss()
            })
            .visibility(Visibility.None)
        }
        .margin({ top: 16 })
      }
      .margin({ top: 20 })
      .visibility(option.status === DownloadStatus.COMPLETED ? Visibility.None : Visibility.Visible)

      Column() {
        Text(option.isAudio ? '已保存到本地' : '已保存到系统相册中').fontColor($r('app.color.color_90ffffff')).fontSize(16)

        Text(option.isAudio ? '文件管理/我的手机/Download/素材魔方' : '文件管理/我的手机/Download/图库')
          .fontColor($r('app.color.color_999999'))
          .fontSize(12)
          .margin({ top: 10 })

        Row() {
          Button('取消', { type: ButtonType.Capsule, stateEffect: true })
            .width(110)
            .height(36)
            .backgroundColor($r('app.color.color_333333'))
            .fontColor($r('app.color.color_50ffffff'))
            .fontSize(15)
            .onClick(() => {
              if (option.callback?.cancel) {
                option.callback.cancel()
              }
              DownloadDialog.dismiss()
            })

          Blank().width(10)

          Button('前往查看', { type: ButtonType.Capsule, stateEffect: true })
            .width(110)
            .height(36)
            .linearGradient({
              colors: [['#F62C6C', 0.0], ['#FC4F54', 1.0]],
              direction: GradientDirection.Right
            })
            .fontColor($r('app.color.color_90ffffff'))
            .fontSize(15)
            .onClick(() => {
              if (option.callback?.confirm) {
                option.callback.confirm()
              }
              DownloadDialog.dismiss()
            })
        }
        .margin({ top: 16 })
      }
      .margin({ top: 20 })
      .visibility(option.status === DownloadStatus.COMPLETED ? Visibility.Visible : Visibility.None)
    }
  }
  .width('80%')
  .borderRadius(10)
  .backgroundColor($r('app.color.color_222222'))
  .padding(20)
}

export class DownloadDialog {
  context: UIContext | null = null;
  contentNode: ComponentContent<Object> | null = null;
  confirm?: () => void;
  cancel?: () => void;

  private static instance: DownloadDialog | null = null;

  static show(context: UIContext, option: DownloadDialogOption) {
    if (DownloadDialog.instance === null) {
      DownloadDialog.instance = new DownloadDialog(context, option);
    }
    DownloadDialog.instance?.openDialog();
  }

  static update(option: DownloadDialogOption) {
    DownloadDialog.instance?.updateDialog(option);
  }

  static dismiss() {
    if (DownloadDialog.instance !== null) {
      DownloadDialog.instance.closeDialog();
      DownloadDialog.instance = null;
    }
  }

  constructor(context: UIContext, option: DownloadDialogOption) {
    this.context = context;
    this.confirm = option.callback?.confirm
    this.cancel = option.callback?.cancel
    this.contentNode = new ComponentContent(context, wrapBuilder(defaultBuilder), option);
  }


  openDialog() {
    if (this.context !== null && this.contentNode !== null) {
      this.context.getPromptAction().openCustomDialog(this.contentNode, {
        onWillDismiss: () => {
          return false
        }
      })
        .then(() => {
          console.info('OpenCustomDialog complete.');
        })
    }
  }

  closeDialog() {
    if (this.context !== null && this.contentNode !== null) {
      this.context.getPromptAction().closeCustomDialog(this.contentNode)
        .then(() => {
          console.info('CloseCustomDialog complete.');
        })
    }
  }

  updateDialog(option: DownloadDialogOption) {
    option.callback = { confirm: this.confirm, cancel: this.cancel }
    this.contentNode?.update(option);
  }
}