import { MaterialEntity } from '../../../../entity/MaterialEntity';
import { TitleBar } from '../../../../view/TitleBar';
import { router, window } from '@kit.ArkUI';
import { ImagePreview } from '@rv/image-preview';
import { AppUtil, DisplayUtil, FileUtil, NumberUtil } from '@pura/harmony-utils';
import { media } from '@kit.MediaKit';
import { BusinessError, request, systemDateTime } from '@kit.BasicServicesKit';
import { ToastUtils } from '../../../../utils/ToastUtils';
import { SaveUtils } from '../../../../utils/SaveUtils';
import { AuthViewModel } from '../../../../viewModel/AuthViewModel';
import { VipPermissionEntity } from '../../../../entity/VipPermissionEntity';
import { LoginManager } from '../../../../manager/LoginGlobalManager';
import { RouterUrls } from '../../../../common/RouterUrls';
import { EventReportGlobalManager } from '../../../../manager/EventReportGlobalManager';
import { EventConstants } from '../../../../common/EventConstants';
import { LoadingDialog } from '../../../../dialog/LoadingDialog';
import { DownloadDialog, DownloadStatus } from '../../../../dialog/DownloadDialog';

@Entry
@ComponentV2
struct MaterialDetailPage {
  windowStage: window.WindowStage = AppStorage.get("windowStage") as window.WindowStage;

  @Local material?: MaterialEntity;
  @Local tagArray: Array<string> = []

  private viewModel: AuthViewModel = new AuthViewModel(this.getUIContext())
  private imageSize: media.PixelMapParams = {}

  @Monitor('viewModel.permissionInfo')
  onPermissionInfoChange(monitor: IMonitor) {
    const info = monitor.value()?.now as VipPermissionEntity;
    if (info.auth) {
      if (!LoginManager.isLogin()) {
        this.getUIContext().getRouter().pushUrl({url: RouterUrls.LOGIN_PAGE, params: {from: 1}}, router.RouterMode.Single)
        return;
      }
      this.download()
    } else {
      if (!info.auth_ad) {
        this.getUIContext().getRouter().pushUrl({url: RouterUrls.VIP_PAGE, params: {origin: 'download_material'}})
        EventReportGlobalManager.eventReport(EventConstants.JUMP_TO_MEMBER_RECHARGE, 'download_material')
        return;
      }
    }
  }

  @Monitor('viewModel.errorCode')
  onErrorCodeChange(monitor: IMonitor) {
    const errorCode = monitor.value()?.now as number;
    if (errorCode === 12002 || errorCode === 12003 || errorCode === 12004) {
      this.getUIContext().getRouter().pushUrl({url: RouterUrls.RECHARGE_DIAMOND_PAGE});
      EventReportGlobalManager.eventReport(EventConstants.JUMP_TO_RECHARGE_DIAMOND, 'download_material')
      ToastUtils.show('M币已用完')
    }
  }

  aboutToAppear(): void {
    this.windowStage.getMainWindowSync().setWindowSystemBarProperties({
      statusBarColor: '#00000000',
      statusBarContentColor: '#FFFFFF'
    });
    this.initParams()
  }

  aboutToDisappear(): void {
    this.windowStage.getMainWindowSync().setWindowSystemBarProperties({
      statusBarColor: '#00000000',
      statusBarContentColor: '#000000'
    });
  }

  initParams() {
    const params = this.getUIContext().getRouter().getParams() as Record<string, Object>;
    if (params) {
      this.material = params.material as MaterialEntity
      if (this.material.pic_size) {
        const size = this.material.pic_size.split(':')
        if (size.length === 2) {
          this.imageSize.width = NumberUtil.toNumber(size[0])
          this.imageSize.height = NumberUtil.toNumber(size[1])
        }
      }
      this.tagArray = this.material.tags
    }
  }

  download() {
    LoadingDialog.show(this.getUIContext())
    let outputPath = FileUtil.getCacheDirPath() + FileUtil.separator + `kcsp_${systemDateTime.getTime()}.jpeg`
    let config: request.agent.Config  =  {
      action: request.agent.Action.DOWNLOAD,
      url: this.material!!.pic!!.url,
      overwrite: true,
      saveas: outputPath,
      gauge: true,
      priority:0
    }
    request.agent.create(AppUtil.getApplicationContext(), config)
      .then((task: request.agent.Task) => {
        task.start((err: BusinessError) => {
          if (err) {
            console.error(`下载失败: ${err.message}`);
            ToastUtils.show(err.message);
            return;
          }
          LoadingDialog.dismiss()
        });
        task.on('completed',() => {
          LoadingDialog.dismiss()
          if (FileUtil.accessSync(outputPath)) {
            SaveUtils.saveImageVideoToAlbumDialog([outputPath])
              .then((saved) => {
                if (saved) {
                  this.showDownloadDialog()
                } else {
                  ToastUtils.show('保存失败')
                }
              })
              .catch(() => {
                ToastUtils.show('保存失败')
              })
          } else {
            ToastUtils.show('下载失败: 文件不存在');
          }
          request.agent.remove(task.tid);
        })
        task.on('failed', () => {
          LoadingDialog.dismiss()
          ToastUtils.show('下载失败，请检查网络后重试');
          request.agent.remove(task.tid);
        });
      })
      .catch((err: BusinessError) => {
        if (err) {
          console.error(`下载失败: ${err.message}`);
          ToastUtils.show(err.message);
        }
        LoadingDialog.dismiss()
      })
  }

  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()
        }
      }
    })
  }

  build() {
    Column() {
      TitleBar({title: this.material?.title, isDark: true})

      Stack() {
        ImagePreview() {
          RelativeContainer() {
            Image(this.material?.pic?.url)
              .width("100%")
              .height(px2vp(Math.round(this.imageSize.height!! * DisplayUtil.getWidth() / this.imageSize.width!!)))
              .sourceSize({
                width: px2vp(DisplayUtil.getWidth()),
                height: px2vp(Math.round(this.imageSize.height!! * DisplayUtil.getWidth() / this.imageSize.width!!))
              })
              .alignRules({
                top: {anchor: '__container__', align: VerticalAlign.Top},
                bottom: {anchor: '__container__', align: VerticalAlign.Bottom}
              })
              .draggable(false)
              .id('image')

            List({space: 4}){
              ForEach(this.tagArray, (item: string) => {
                ListItem() {
                  Text(item).fontColor(Color.White).fontSize(10)
                    .borderRadius(2)
                    .backgroundColor('#80000000')
                    .padding({left: 4, top: 1, right: 4, bottom: 1})
                }
              })
            }
            .listDirection(Axis.Horizontal)
            .alignRules({
              top: {anchor: 'image', align: VerticalAlign.Top},
              right: {anchor: 'image', align: HorizontalAlign.End}
            })
            .margin({top: 12, right: 12})
            .height('auto')
          }
          .height('auto')
        }
      }
      .width('100%')
      .layoutWeight(1)

      Stack() {
        Button({ type: ButtonType.Capsule, stateEffect: true }) {
          Row() {
            Image($r("app.media.ic_download_material")).width(22).height(22)
            Text('下载').fontColor(Color.White).fontSize(15).fontWeight(FontWeight.Medium)
          }
        }
        .width('100%')
        .height(46)
        .backgroundColor($r('app.color.color_466afd'))
        .onClick(() => {
          if (this.material?.pic?.url) {
            this.viewModel.checkVip()
          } else {
            ToastUtils.show('链接不存在')
          }
        })
      }
      .backgroundColor($r('app.color.color_1b1b1b'))
      .padding({left: 16, top: 9, right: 16, bottom: 30})
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#0F0E13')
  }
}