import { HMRouter, HMRouterMgr } from "@hadss/hmrouter";
import { common } from "@kit.AbilityKit";
import AppConstants from "../../app/AppConstant";
import { createWaterMark } from "../custom/Watermark";
import { webview } from "@kit.ArkWeb";
import { fileIo, fileUri, picker } from "@kit.CoreFileKit";
import { photoAccessHelper } from "@kit.MediaLibraryKit";
import { WebUserInfoModel } from "../../model/cacheModel/UserInfoModel";
import { RuanseeAbilityStag } from "../../app/RuanseeAbilityStag";
import { StringUtils } from "../../util/StringUtils";
import JiaMi from "../../util/JiaMi";
import { H5OperationType, WebAppPageParam } from "../../model/uiModel/WebAppPageParam";
import { SelectFileOptions } from "../../model/uiModel/SelectFileOptions";
import {  window } from "@kit.ArkUI";
import { DialogHelper } from "@pura/harmony-dialog";
import { call } from "@kit.TelephonyKit";
import { StrUtil } from "@pura/harmony-utils/src/main/ets/utils/StrUtil";
import { FileUtils } from "../../util/FileUtils";
import { camera, cameraPicker } from "@kit.CameraKit";
import { ImageUtil, ToastUtil } from "@pura/harmony-utils";

@Preview
@HMRouter({ pageUrl: 'WebAppPages' })
@Component
export struct WebAppPages {
  webController: webview.WebviewController = new webview.WebviewController();
  context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  @State statusBarColor: string | Resource = $r('app.color.bull')
  @State statusBarHeight: number = 34
  @State topBarVisible: boolean = true;
  @State hmMethodInterface: HMMethodInterface = new HMMethodInterface()
  @State leftImage: Resource = $r('app.media.icon_back3')
  @State title: string | Resource = ''
  @State currentIndex: number = 0
  /**
   * 标题栏是否深色模式
   */
  @State isBlackFontColor: boolean = false
  fileSelector: SelectFileOptions = new SelectFileOptions(false,true,true,true)
  ///////////////// 接收参数 //////////////////
  h5AppParam:WebAppPageParam = new WebAppPageParam()

  @State loadUrl :string|Resource = $rawfile('TestJs.html')

  /////////////////////////////////

  aboutToAppear(): void {
    this.h5AppParam   = HMRouterMgr.getCurrentParam() as WebAppPageParam
    if (!this.h5AppParam) {
      DialogHelper.showToastTip({
        message: "错误的应用参数",
        imageRes: $r('app.media.icon_tips_error'),
        duration: 1000,
      })
      setTimeout(() => {
        HMRouterMgr.pop()
      }, 1200)
      return
    }
    this.title = this.h5AppParam.appName
    this.hmMethodInterface.bindComponent(this)
    this.handUrl();
    setTimeout(() => {
      this.webController.loadUrl(this.loadUrl)
    }, 800)
  }

  handUrl() {
    if (StringUtils.isNullOrEmpty(this.h5AppParam!.linkUrl)){
      this.loadUrl =  $rawfile('TestJs.html')
      return
    }
    if (StringUtils.containsChar(this.h5AppParam.linkUrl,"?")){
      this.loadUrl = `${this.h5AppParam.linkUrl}&userInfo=${this.hmMethodInterface.getUserInfo()}`
    }else {
      this.loadUrl = `${this.h5AppParam.linkUrl}?userInfo=${this.hmMethodInterface.getUserInfo()}`
    }
    if(this.h5AppParam!.operationType == H5OperationType.login){
      this.loadUrl = `${this.loadUrl}?operation_type=login`
      return
    }
    if(this.h5AppParam!.operationType == H5OperationType.readMessage){
      if(StringUtils.isNullOrEmpty(this.h5AppParam!.msgId)){
        this.loadUrl = `${this.loadUrl}?operation_type=login`
        return
      }
      this.loadUrl = `${this.loadUrl}?operation_type=readMessage&msg_id=${StringUtils.get(this.h5AppParam!.msgId,"")}`
      if (StrUtil.isNotEmpty(this.h5AppParam!.msgType)) {
        this.loadUrl = `${this.loadUrl}?msg_type=${StringUtils.get(this.h5AppParam!.msgType,"")}`
      }
    }
    if(this.h5AppParam!.operationType == H5OperationType.search){
      this.loadUrl = `${this.loadUrl}?operation_type=search&search_type=${StringUtils.get(this.h5AppParam!.searchType,"")}`
    }
  }

  /**
   * 文件选择器
   * @param result
   * @returns
   */
  async selectImage(result: FileSelectorResult): Promise<void> {
    let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    // 过滤选择媒体文件类型为IMAGE
    photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE;
    // 设置最大选择数量
    photoSelectOptions.maxSelectNumber = 1;
    let chooseFile: picker.PhotoSelectResult = await photoPicker.select(photoSelectOptions);
    // 获取选择的文件列表
    result.handleFileList(chooseFile.photoUris);
  }

  async selectFile(result: FileSelectorResult) {
    console.log('MyFileUploader onShowFileSelector invoked')
    const documentSelectOptions = new picker.DocumentSelectOptions();
    let uri: string | null = null;
    documentSelectOptions.maxSelectNumber = 1;
    const documentViewPicker = new picker.DocumentViewPicker();
    documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => {
      uri = documentSelectResult[0];
      console.info('documentViewPicker.select to file succeed and uri is:' + uri);
      if (result) {
        result.handleFileList([uri]);
      }
    }).catch((err: Error) => {
      console.error(`Invoke documentViewPicker.select failed, code is ${err.message},  message is ${err.message}`);
    })
  }

  /**
   * 拍照
   */
  async takePhoto(webResult: FileSelectorResult) {
    let pathDir = FileUtils.IMAGE_DIR;
    let fileName = `${new Date().getTime()}.JPEG`
    let filePath = `${pathDir}/${fileName}`
    let imageFileUri: string | undefined = undefined;
    fileIo.createRandomAccessFileSync(filePath, fileIo.OpenMode.CREATE);

    let fileUris = fileUri.getUriFromPath(filePath);
    let pickerProfile: cameraPicker.PickerProfile = {
      cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,
      saveUri: fileUris,
    };
    let result: cameraPicker.PickerResult =
      await cameraPicker.pick(getContext(), [cameraPicker.PickerMediaType.PHOTO],
        pickerProfile);
    console.info(`picker resultCode: ${result.resultCode},resultUri: ${result.resultUri},mediaType: ${result.mediaType}`);
    if (result.resultCode == 0) {
      if (result.mediaType === cameraPicker.PickerMediaType.PHOTO) {
        imageFileUri = result.resultUri
        imageFileUri = await ImageUtil.compressPhoto(imageFileUri, 150);
        webResult.handleFileList([imageFileUri])
      }
    } else {
      ToastUtil.showToast("取消选择")
    }
  }

  showUpdatePhoto(selectItems:Array<string>,webResult: FileSelectorResult) {
    //带标题
    DialogHelper.showActionSheetDialog({
      title: "选择文件",
      titleFontColor: Color.Black,
      cancelFontColor: Color.Red,
      cancelFontWeight: FontWeight.Normal,
      sheets: selectItems,
      onAction: (index) => {
        let item = selectItems[index]
        if(item == '相机拍摄'){
          this.takePhoto(webResult)
        }
        if(item == '相册选择'){
          this.selectImage(webResult)
        }
        if(item == '文件选择'){
          this.selectFile(webResult)
        }
      }
    })
  }

  build() {
    Column() {
      Blank()
        .width(AppConstants.PERCENTAGE_MAX)
        .height(this.statusBarHeight)
        .color(this.statusBarColor)

      this.topBar()

      this.webView()
    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)
    .padding({bottom: $r('app.float.default_28')})
    .overlay(createWaterMark())

  }

  @Builder
  webView() {
    //// 设置为同步渲染模式
    Web({ src: "", controller: this.webController, renderMode: RenderMode.SYNC_RENDER })
      // .layoutMode(WebLayoutMode.FIT_CONTENT)// 设置为Web组件大小自适应页面内容
      .overScrollMode(OverScrollMode.NEVER)// 设置过滚动模式为关闭状态
      .fileAccess(true)
      .javaScriptAccess(true)
      .layoutWeight(1)
      .width(AppConstants.PERCENTAGE_MAX)
      .javaScriptProxy({
        object: this.hmMethodInterface,
        name: "callByAndroid",
        methodList: ["isTitleBlock", "getUserInfo", "setUploadFileOptions", "onBack", "exitToHome",
          "setSystemStatusBarStyle", "showNetPermission","reloadPage"],
        asyncMethodList: ["asyncTest"],
        controller: this.webController,
      })
      .defaultFixedFontSize(14)
      .defaultFontSize(14)
      .minFontSize(14)
      .minLogicalFontSize(13)
      .mixedMode(MixedMode.All)
      .zoomAccess(false)
      .databaseAccess(true)
      .domStorageAccess(true)
      .horizontalScrollBarAccess(false)// .cacheMode(CacheMode.Online)
      .copyOptions(CopyOptions.LocalDevice)
      .onLoadIntercept((event) => {
        if (event.data.getRequestUrl().startsWith('tel:')) {
          call.makeCall(event.data.getRequestUrl().substring(4));
          return true; // 阻止默认跳转
        }
        return false;
      })
      .onAlert((event) => { //网页加载时弹出提示框
        if (event) {
          console.log("event.url:" + event.url);
          console.log("event.message:" + event.message);
          AlertDialog.show({
            title: 'onAlert',
            message: event.message,
            primaryButton: {
              value: '取消',
              action: () => {
                event.result.handleCancel();
              }
            },
            secondaryButton: {
              value: '确定',
              action: () => {
                event.result.handleConfirm();
              }
            },
            cancel: () => {
              event.result.handleCancel();
            }
          })
        }
        return false;
      })
      .onErrorReceive((event) => { //网页加载遇到错误时触发该回调
        if (event) {
          console.log('getErrorInfo:' + event.error.getErrorInfo());
          console.log('getErrorCode:' + event.error.getErrorCode());
          console.log('url:' + event.request.getRequestUrl());
          console.log('isMainFrame:' + event.request.isMainFrame());
          console.log('isRedirect:' + event.request.isRedirect());
          console.log('isRequestGesture:' + event.request.isRequestGesture());
          console.log('getRequestHeader_headerKey:' + event.request.getRequestHeader().toString());
          let result = event.request.getRequestHeader();
          console.log('The request header result size is ' + result.length);
          for (let i of result) {
            console.log('The request header key is : ' + i.headerKey + ', value is : ' + i.headerValue);
          }
        }
      })
      .onDownloadStart((event) => { //通知主应用开始下载一个文件。
        if (event) {
          console.log('url:' + event.url)
          console.log('userAgent:' + event.userAgent)
          console.log('contentDisposition:' + event.contentDisposition)
          console.log('contentLength:' + event.contentLength)
          console.log('mimetype:' + event.mimetype)
        }
      })
      .onHttpErrorReceive((event) => { //网页加载资源遇到的HTTP错误（响应码>=400)时触发该回调。
        if (event) {
          console.log('url:' + event.request.getRequestUrl());
          console.log('isMainFrame:' + event.request.isMainFrame());
          console.log('isRedirect:' + event.request.isRedirect());
          console.log('isRequestGesture:' + event.request.isRequestGesture());
          console.log('getResponseData:' + event.response.getResponseData());
          console.log('getResponseEncoding:' + event.response.getResponseEncoding());
          console.log('getResponseMimeType:' + event.response.getResponseMimeType());
          console.log('getResponseCode:' + event.response.getResponseCode());
          console.log('getReasonMessage:' + event.response.getReasonMessage());
          let result = event.request.getRequestHeader();
          console.log('The request header result size is ' + result.length);
          for (let i of result) {
            console.log('The request header key is : ' + i.headerKey + ' , value is : ' + i.headerValue);
          }
          let resph = event.response.getResponseHeader();
          console.log('The response header result size is ' + resph.length);
          for (let i of resph) {
            console.log('The response header key is : ' + i.headerKey + ' , value is : ' + i.headerValue);
          }
        }
      })
      .onPageBegin((event) => { //网页开始加载时触发该回调
        if (event) {
          console.log('url:' + event.url);
        }
      })
      .onPageEnd((event) => { //网页加载完成时触发该回调
        if (event) {
          console.log('url:' + event.url);
        }
      })
      .onProgressChange((event) => { //网页加载进度变化时触发该回调
        if (event) {
          console.log('newProgress:' + event.newProgress);
        }
      })
      .onTitleReceive((event) => {
        if (event) {
          console.log('title:' + event.title);
        }
      })
      .onRenderExited((event) => { //应用渲染进程异常退出时触发该回调
        if (event) {
          console.log('reason:' + event.renderExitReason);
        }
      })
      .onShowFileSelector((event) => {
        if (this.fileSelector) {
          if (this.fileSelector.selfRealization) {
              return true
          }
          if (this.fileSelector.onlyOneItemIsSelected()) {
            if(this.fileSelector.isCamera){
              //相机拍照
              this.takePhoto(event.result)
            }
            if(this.fileSelector.isFileSelection){
              //文件选择
              this.selectFile(event.result)
            }
            if(this.fileSelector.isDCIM){
              //图库
              this.selectImage(event.result)
            }
            return true;
          }else {
            let selectItems = new Array<string>();
            if(this.fileSelector.isCamera) {
              selectItems.push('相机拍摄')
            }
            if(this.fileSelector.isDCIM) {
              selectItems.push('相册选择')
            }
            if(this.fileSelector.isFileSelection) {
              selectItems.push('文件选择')
            }
            this.showUpdatePhoto(selectItems, event.result);
          }
          return true;
        }
        /**
         * 调用此函数以处理具有“文件”输入类型的HTML表单。如果不调用此函数或返回false，
         * Web组件会提供默认的“选择文件”处理界面。如果返回true，应用可以自定义“选择文件”的响应行为。
         */
        event.fileSelector.getMode()
        event.fileSelector.getAcceptType()
        event.fileSelector.getMimeTypes()
        event.fileSelector.isCapture()
        if (event.fileSelector) {

        }
        return true;
      })
      .onPermissionRequest((event) => { //通知收到获取权限请求
        if (event) {
          AlertDialog.show({
            title: 'title',
            message: 'text',
            primaryButton: {
              value: 'deny',
              action: () => {
                event.request.deny();
              }
            },
            secondaryButton: {
              value: 'onConfirm',
              action: () => {
                event.request.grant(event.request.getAccessibleResource());
              }
            },
            cancel: () => {
              event.request.deny();
            }
          })
        }
      })
      .onGeolocationShow((event) => { //通知用户收到地理位置信息获取请求。
        if (event) {
          AlertDialog.show({
            title: 'title',
            message: 'text',
            confirm: {
              value: 'onConfirm',
              action: () => {
                event.geolocation.invoke(event.origin, true, true);
              }
            },
            cancel: () => {
              event.geolocation.invoke(event.origin, false, true);
            }
          })
        }
      })
  }

  @Builder
  topBar() {
    Row() {
      Row() {
        Image(this.leftImage)
          .width($r('app.float.default_24'))
          .height($r('app.float.default_24'))
      }
      .height("100%")
      .width($r('app.float.default_68'))
      .alignItems(VerticalAlign.Center)
      .padding({ left: $r('app.float.default_10') })
      .onTouch((event) => {
        if (event.type === TouchType.Down) {
          this.leftImage = $r('app.media.icon_back2');
        } else if (event.type === TouchType.Up) {
          if (this.isBlackFontColor) {
            this.leftImage = $r('app.media.icon_back_black');
          } else {
            this.leftImage = $r('app.media.icon_back3');
          }
        }
      })
      .onClick(() => {
        if (this.webController.accessBackward()) {
          this.webController.backward()
        } else {
          HMRouterMgr.pop()
        }
      })

      Text(this.title)
        .fontColor(this.isBlackFontColor ? $r('app.color.colorGrey8') : $r('app.color.white'))
        .fontSize($r('app.float.text_size_18'))
        .layoutWeight(1)
        .height("100%")
        .textAlign(TextAlign.Center)
        .align(Alignment.Center)
        .margin({
          left: $r('app.float.default_10'),
          right: $r('app.float.default_10')
        })

      Row() {
        Image(this.isBlackFontColor ? $r('app.media.icon_refresh_grad') : $r('app.media.icon_refresh'))
          .width($r('app.float.default_24'))
          .height($r('app.float.default_24'))
          .onClick(() => {
            this.webController.refresh()
          })

        Image(this.isBlackFontColor ? $r('app.media.icon_over_back') : $r('app.media.icon_over'))
          .width($r('app.float.default_24'))
          .height($r('app.float.default_24'))
          .margin({ left: $r('app.float.default_5') })
          .onClick(() => {
            HMRouterMgr.pop({ navigationId: 'startNavigation', pageUrl: "MainPage" })
          })
      }
      .alignItems(VerticalAlign.Center)
      .height("100%")
      .width($r('app.float.default_68'))
      .padding({ right: $r('app.float.default_10') })
    }
    .alignItems(VerticalAlign.Center)
    .width('100%')
    .visibility(this.topBarVisible ? Visibility.Visible : Visibility.None)
    .backgroundColor(this.statusBarColor)
    .height($r('app.float.default_40'))
  }

  hideTopBar(isShow: boolean) {
    this.topBarVisible = isShow;
  }

  /**
   * 设置状态栏颜色
   * @param statusBarColor
   */
  setStatusBarColor(statusBarColor: string) {
    // 在UIAbility或UI组件中执行（需确保已获取Window对象）
    let sysBarProps: window.SystemBarProperties = {
      statusBarContentColor: statusBarColor, // 白色文字/图标
      statusBarColor: '#00000000'         // 黑色背景
    };
    this.context.windowStage.getMainWindow()
      .then((windows) => {
        if (windows) {
          windows.setWindowSystemBarProperties(sysBarProps)
            .then(() => {
              console.info('状态栏颜色修改成功');
            })
            .catch((err: Error) => {
              console.error(`修改失败，信息: ${err.message}`);
            });
        }
      })
      .catch((err: Error) => {
        console.error(`获取window失败，信息: ${err.message}`);

      })
  }

  @Builder
  errorDialog(message: string, ywry: string, ywryPhone: string) {
    Column() {
      Text(message)
        .fontColor($r('app.color.colorGrey8'))
        .fontSize($r('app.float.text_size_14'))

      Row() {
        Text(ywry)
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_14'))
        Text(ywryPhone)
          .fontColor($r('app.color.bull'))
          .fontSize($r('app.float.text_size_14'))
          .copyOption(CopyOptions.LocalDevice)
          .decoration({
            type: TextDecorationType.Underline,
            color: Color.Blue,
            style: TextDecorationStyle.WAVY
          })
          .onClick(() => {
            this.callPhone(ywryPhone)
          })
      }
      .alignItems(VerticalAlign.Center)
      .justifyContent(FlexAlign.Center)
      .height($r('app.float.default_38'))
      .width(AppConstants.PERCENTAGE_MAX)

    }
    .alignItems(HorizontalAlign.Center)
    .width(AppConstants.PERCENTAGE_MAX)
  }

  callPhone(phone: string) {
    if (!call.hasVoiceCapability()) {
      console.error('设备不支持拨号功能');
      return;
    }

    call.makeCall("tel:" + phone, (err: Error) => {
      if (err) {
        console.error(`跳转失败：${err.message}`);
      }
    });

  }
}

class HMMethodInterface {
  private componentRef: WebAppPages | null = null;

  bindComponent(ref: WebAppPages) {
    this.componentRef = ref;
  }

  isTitleBlock(isShow: boolean) {
    this.componentRef?.hideTopBar(isShow);
  }

  /**
   * 获取加密用户信息
   * @returns
   */
  getUserInfo(): string {
    let userData: WebUserInfoModel = new WebUserInfoModel();
    userData.userCode = RuanseeAbilityStag.userCache.getUserCode
    userData.userName = RuanseeAbilityStag.userCache.getUserName
    userData.deptName = RuanseeAbilityStag.userCache.getDeptName
    userData.deptCode = RuanseeAbilityStag.userCache.getDeptCode
    userData.idCardNum = RuanseeAbilityStag.userCache.getIdCardNum
    let userInfo = JSON.stringify(userData)
    let jmData = StringUtils.get(new JiaMi().desCrypto(userInfo,this.componentRef!.h5AppParam.appId, this.componentRef!.h5AppParam.secret), "")
    console.debug("加密后数据：", jmData)
    return jmData
  }

  /**
   * TODO 该方法不能弹出选择框，此方法是在JS调用选择文件方法之前调用的。在使用JS调选择文件时将根据此方法的配置做对应操作
   * 配置上传文件选择项。此方法再调用上传文件的事件之前调用，如果不调用则默认 selfRealization = false , 其他参数默认为 true
   * 详情查看 {@link WebViewPresenter#mWebChromeClient} 的 onShowFileChooser(WebView, ValueCallback<Uri[]> , FileChooserParams ) 方法
   *
   * @param selfRealization 是否由JS自己实现文件选择上传。
   *                        PS: true:由JS自己实现，Android原生不做操作，不会弹出选择框,.值为false时将原生代码将拦截操作并根据下面参数配置弹出选择框。
   * @param isCamera        PS:是否支持相机拍照：  true =  支持相机拍照上传，false = 不支持相机拍照上传，值为false时弹出框将没有相机选项
   * @param isDCIM          PS:是否支持相册选择：  true =  支持相册选择上传，false = 不支持相册选择上传，值为false时弹出框将没有相册选项
   * @param isFileSelection PS:是否支持文件选择：  true =  支持文件选择上传，false = 不支持文件选择上传，值为false时弹出框将没有文件选择选项
   *                        TODO 当且仅当 selfRealization = true && (isCamera | isDCIM | isFileSelection ) 只有一个为 true 时 将没有弹框，直接跳转对应操作
   */
  setUploadFileOptions(selfRealization: boolean, isCamera: boolean, isDCIM: boolean, isFileSelection: boolean) {
    if (this.componentRef) {
      if (!this.componentRef.fileSelector) {
        this.componentRef.fileSelector = new SelectFileOptions(selfRealization, isCamera, isDCIM, isFileSelection);
      } else {
        this.componentRef.fileSelector.setConfig(selfRealization, isCamera, isDCIM, isFileSelection)
      }
    }
  }

  /**
   * 调用返回按钮
   */
  onBack() {
    if (this.componentRef) {
      if (this.componentRef.webController.accessBackward()) {
        this.componentRef.webController.backward()
      } else {
        HMRouterMgr.pop()
      }
    }
  }

  /**
   * 退出到主页
   */
  exitToHome() {
    HMRouterMgr.pop()
  }

  /**
   * 设置状态栏颜色及状态栏图标字体颜色深浅模式
   *
   * @param statusBarColor   状态栏颜色 值为字符串 格式为：#ffffff
   * @param isBlackFontColor 是否为   true 为黑色字体   |    false 为白色字体
   */
  setSystemStatusBarStyle(statusBarColor: string, isBlackFontColor: boolean) {
    if (this.componentRef) {
      let effectiveColor = "#3255E3";
      if (StringUtils.strictCheckHexColor(statusBarColor)) {
        effectiveColor = statusBarColor;
      }
      this.componentRef.statusBarColor = effectiveColor
      this.componentRef.isBlackFontColor = isBlackFontColor
      if (isBlackFontColor) {
        this.componentRef.leftImage = $r('app.media.icon_back_black')
        this.componentRef.setStatusBarColor("#000000")
        // setStatusBarColor(this.context, bg, content);
      } else {
        this.componentRef.leftImage = $r('app.media.icon_back3')
        this.componentRef.setStatusBarColor("#ffffff")
        // setStatusBarColor(this.context, bg, content);
      }
    }
  }

  /**
   * 弹出提示框
   *
   * @param title     提示标题
   * @param msg       提示内容
   * @param lxryName  联系人员
   * @param lxryPhone 联系电话
   */
  showNetPermission(title = "重要提醒", msg: string, lxryName: string, lxryPhone: string) {
    //自定义文本内容，使用全局 @Builder 和 自定义组件
     DialogHelper.showCustomContentDialog({
      title: title,
      contentBuilder: () => {
        this.componentRef?.errorDialog(msg, lxryName, lxryPhone)
      },
      buttons: [
        { value: '确定', fontColor: Color.Black }
      ],
      onAction: (action, dialogId, value) => {
        if (action === -1) {
          DialogHelper.closeDialog(dialogId)
          HMRouterMgr.pop()
        }
      }
    })
  }

  /**
   * 刷新页面
   */
  reloadPage() {
    if (this.componentRef) {
      this.componentRef.webController.refresh()
    }
  }
}
