if (!("finalizeConstruction" in ViewPU.prototype)) {
    Reflect.set(ViewPU.prototype, "finalizeConstruction", () => { });
}
interface Index_Params {
    // WebviewController
    _controller?: webview.WebviewController;
    _urlString?: string;
    _titleString?: string;
    resultH5Url?: string;
    callBack?: FaceH5VerifyCallback;
    isGranted?: boolean;
    sandboxFilePath?: string;
    //上传文件的类型，0：相机；1：视频；2：图片，3普通文件
    uploadFileType?;
    hideTitle?: boolean;
}
import webview from "@ohos:web.webview";
import promptAction from "@ohos:promptAction";
import router from "@ohos:router";
import bundleManager from "@ohos:bundle.bundleManager";
import abilityAccessCtrl from "@ohos:abilityAccessCtrl";
import type common from "@ohos:app.ability.common";
import type { Permissions } from "@ohos:abilityAccessCtrl";
import type Want from "@ohos:app.ability.Want";
import type { BusinessError } from "@ohos:base";
import cameraPicker from "@ohos:multimedia.cameraPicker";
import camera from "@ohos:multimedia.camera";
import { PermissionsUtils } from "@normalized:N&&&esignfacesdk/src/main/ets/utils/PermissionsUtils&1.0.0";
import { FaceResultResponse } from "@normalized:N&&&esignfacesdk/src/main/ets/EsignSDK&1.0.0";
import type { FaceH5VerifyCallback } from "@normalized:N&&&esignfacesdk/src/main/ets/EsignSDK&1.0.0";
export class routerParams {
    'url': string;
    'resultH5Url': string = '';
    'title': string = 'e签宝';
    'callBack': FaceH5VerifyCallback;
}
let mContext = getContext(this) as common.Context;
async function picCamera(video: boolean): Promise<cameraPicker.PickerResult> {
    console.log('video:' + video);
    return new Promise((resolve, reject) => {
        try {
            let pickerProfile: cameraPicker.PickerProfile = {
                cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
            };
            let type = video ? cameraPicker.PickerMediaType.VIDEO : cameraPicker.PickerMediaType.PHOTO;
            let pickerResult = cameraPicker.pick(mContext, [type], pickerProfile);
            console.log("the pick pickerResult is:" + JSON.stringify(pickerResult));
            resolve(pickerResult);
        }
        catch (error) {
            let err = error as BusinessError;
            console.error(`the pick call failed. error code: ${err.code}`);
            reject(error);
        }
    });
}
const TAG = '[BaseWebView]';
class Index extends ViewPU {
    constructor(parent, params, __localStorage, elmtId = -1, paramsLambda = undefined, extraInfo) {
        super(parent, __localStorage, elmtId, extraInfo);
        if (typeof paramsLambda === "function") {
            this.paramsGenerator_ = paramsLambda;
        }
        this._controller = new webview.WebviewController();
        this.___urlString = new ObservedPropertySimplePU((router.getParams() as routerParams).url, this, "_urlString");
        this.___titleString = new ObservedPropertySimplePU(router.getParams() == null || router.getParams() === undefined ? 'e签宝' : (router.getParams() as routerParams).title, this, "_titleString");
        this.resultH5Url = (router.getParams() as routerParams).resultH5Url;
        this.callBack = (router.getParams() as routerParams).callBack;
        this.__isGranted = new ObservedPropertySimplePU(false, this, "isGranted");
        this.sandboxFilePath = "";
        this.uploadFileType = 3;
        this.__hideTitle = new ObservedPropertySimplePU(true
        // 拦截页面侧滑侧滑事件
        , this, "hideTitle");
        this.setInitiallyProvidedValue(params);
        this.finalizeConstruction();
    }
    setInitiallyProvidedValue(params: Index_Params) {
        if (params._controller !== undefined) {
            this._controller = params._controller;
        }
        if (params._urlString !== undefined) {
            this._urlString = params._urlString;
        }
        if (params._titleString !== undefined) {
            this._titleString = params._titleString;
        }
        if (params.resultH5Url !== undefined) {
            this.resultH5Url = params.resultH5Url;
        }
        if (params.callBack !== undefined) {
            this.callBack = params.callBack;
        }
        if (params.isGranted !== undefined) {
            this.isGranted = params.isGranted;
        }
        if (params.sandboxFilePath !== undefined) {
            this.sandboxFilePath = params.sandboxFilePath;
        }
        if (params.uploadFileType !== undefined) {
            this.uploadFileType = params.uploadFileType;
        }
        if (params.hideTitle !== undefined) {
            this.hideTitle = params.hideTitle;
        }
    }
    updateStateVars(params: Index_Params) {
    }
    purgeVariableDependenciesOnElmtId(rmElmtId) {
        this.___urlString.purgeDependencyOnElmtId(rmElmtId);
        this.___titleString.purgeDependencyOnElmtId(rmElmtId);
        this.__isGranted.purgeDependencyOnElmtId(rmElmtId);
        this.__hideTitle.purgeDependencyOnElmtId(rmElmtId);
    }
    aboutToBeDeleted() {
        this.___urlString.aboutToBeDeleted();
        this.___titleString.aboutToBeDeleted();
        this.__isGranted.aboutToBeDeleted();
        this.__hideTitle.aboutToBeDeleted();
        SubscriberManager.Get().delete(this.id__());
        this.aboutToBeDeletedInternal();
    }
    // WebviewController
    private _controller: webview.WebviewController;
    // WebViewJavascriptBridge 桥接
    // private _bridge: WebViewJavascriptBridge | undefined;
    // 当前加载的链接
    private ___urlString: ObservedPropertySimplePU<string>;
    get _urlString() {
        return this.___urlString.get();
    }
    set _urlString(newValue: string) {
        this.___urlString.set(newValue);
    }
    private ___titleString: ObservedPropertySimplePU<string>;
    get _titleString() {
        return this.___titleString.get();
    }
    set _titleString(newValue: string) {
        this.___titleString.set(newValue);
    }
    private resultH5Url: string;
    private callBack: FaceH5VerifyCallback;
    private __isGranted: ObservedPropertySimplePU<boolean>;
    get isGranted() {
        return this.__isGranted.get();
    }
    set isGranted(newValue: boolean) {
        this.__isGranted.set(newValue);
    }
    private sandboxFilePath: string;
    //上传文件的类型，0：相机；1：视频；2：图片，3普通文件
    private uploadFileType;
    private __hideTitle: ObservedPropertySimplePU<boolean>;
    get hideTitle() {
        return this.__hideTitle.get();
    }
    set hideTitle(newValue: boolean) {
        this.__hideTitle.set(newValue);
    }
    // 拦截页面侧滑侧滑事件
    onBackPress() {
        if (this._controller.accessBackward()) {
            // 有历史记录可后退
            this._controller.backward();
        }
        return true;
    }
    aboutToAppear(): void {
    }
    NavigationTitle(parent = null) {
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Row.create();
            Row.alignItems(VerticalAlign.Center);
            Row.justifyContent(FlexAlign.Center);
            Row.width("100%");
            Row.height(56);
            Row.margin({ bottom: 0 });
        }, Row);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Navigator.create({ type: NavigationType.Back, target: "" });
            Navigator.layoutWeight(1);
        }, Navigator);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Image.create({ "id": 16777329, "type": 20000, params: [], "bundleName": "com.esign.sdk", "moduleName": "entry" });
            Image.width(18);
            Image.height(32);
            Image.aspectRatio(1);
            Image.visibility(this.hideTitle ? Visibility.Hidden : Visibility.Visible);
            Image.objectFit(ImageFit.Contain);
            Image.onClick(() => {
                if (this._controller.accessStep(-1)) {
                    // 有历史记录可后退
                    this._controller.backward();
                }
                else {
                    this.onBackPress();
                }
            });
        }, Image);
        Navigator.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Text.create(this._titleString);
            Text.fontColor('#333333');
            Text.fontSize(18);
            Text.fontWeight(500);
            Text.width("70%");
            Text.textAlign(TextAlign.Center);
            Text.layoutWeight(6);
            Text.maxLines(1);
            Text.textOverflow({ overflow: TextOverflow.Ellipsis });
        }, Text);
        Text.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Blank.create();
            Blank.layoutWeight(1);
        }, Blank);
        Blank.pop();
        Row.pop();
    }
    initialRender() {
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Column.create();
            Column.width('100%');
            Column.height('100%');
        }, Column);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Navigation.create(new NavPathStack(), { moduleName: "entry", pagePath: "esignfacesdk/src/main/ets/pages/WebView", isUserCreateStack: false });
            Navigation.title({ builder: () => {
                    this.NavigationTitle.call(this);
                } });
            Navigation.titleMode(NavigationTitleMode.Mini);
            Navigation.hideBackButton(true);
            Navigation.hideTitleBar(this.hideTitle);
        }, Navigation);
        this.webView.bind(this)();
        Navigation.pop();
        Column.pop();
    }
    private webView(parent = null) {
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Web.create({
                src: this._urlString,
                controller: this._controller,
            });
            Web.width('100%');
            Web.zoomAccess(false);
            Web.mixedMode(MixedMode.All);
            Web.domStorageAccess(true);
            Web.javaScriptAccess(true);
            Web.fileAccess(true);
            Web.mediaPlayGestureAccess(false);
            Web.cacheMode(CacheMode.Default);
            Web.onTitleReceive((info) => {
                console.log(info.title);
                if (info.title !== 'e签宝-电子签名、电子合同行业引领者' && info.title !== 'e签宝') {
                    this._titleString = info.title;
                }
            });
            Web.onControllerAttached(() => {
                let options = new webview.BackForwardCacheOptions();
                options.size = 10;
                options.timeToLive = 20;
                this._controller.setBackForwardCacheOptions(options);
                // UA 注入，用于H5判断是 e签宝环境下的鸿蒙OS容器
                bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION).then((bundleInfo) => {
                    let versionNo = bundleInfo.versionCode; //应用版本号
                    let userAgent = this._controller.getUserAgent() + ";EsignHarmonyClient/5.9.2;" + versionNo + ";kyc/h5face;hoskyc/2.0";
                    console.log("pj 鸿蒙ua样例:" + userAgent);
                    this._controller.setCustomUserAgent(userAgent);
                });
            });
            Web.onAlert((event) => {
                AlertDialog.show({ message: event?.message });
                return false;
            });
            Web.onLoadIntercept((event) => {
                console.log("onLoadIntercept url:" + event.data.getRequestUrl());
                const url = event.data.getRequestUrl();
                if (url.startsWith(this.resultH5Url)) {
                    this.callBack(new FaceResultResponse());
                    router.back();
                }
                return false;
            });
            Web.onPermissionRequest((event) => {
                if (event) {
                    this.checkPermission().then(() => {
                        event.request.grant(event.request.getAccessibleResource()); // 2. 授权h5页面
                    }).catch((error: BusinessError) => {
                        console.error(TAG, "申请权限异常" + error.message);
                        event.request.deny(); //2.告诉h5页面没有权限
                    });
                }
            });
            Web.onShowFileSelector((event) => {
                return true;
            });
        }, Web);
    }
    private _toast(msg: string) {
        promptAction.showToast({
            message: msg,
            duration: 4000
        });
    }
    // 相机权限检测
    async checkPermission() {
        // 检查权限
        const permissions: Array<Permissions> = ['ohos.permission.CAMERA'];
        let grantStatusCamera = await PermissionsUtils.checkAccessToken(permissions[0]);
        console.debug(TAG, `checkPermission grantStatus ${grantStatusCamera}`);
        if (grantStatusCamera != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
            console.debug(TAG, `requestCameraPermission`);
            // 没有授权了
            await this.requestPermission(permissions);
        }
        else {
            this.isGranted = true;
        }
    }
    // 获取权限
    async requestPermission(permissionList: Array<Permissions>) {
        let context = getContext(this) as common.UIAbilityContext;
        let grantStatus = await PermissionsUtils.reqPermissionsFromUser(context, permissionList);
        let length: number = grantStatus.length;
        for (let i = 0; i < length; i++) {
            if (grantStatus[i] === 0) {
                console.info(TAG, `requestPermissionsFromUser success`);
            }
            else {
                console.error(TAG, `requestPermissionsFromUser failed`);
                AlertDialog.show({
                    title: '权限申请',
                    message: '请授权申请相机权限',
                    primaryButton: {
                        value: '取消',
                        action: () => {
                        }
                    },
                    secondaryButton: {
                        value: '确认',
                        action: () => {
                            this.openPermissionsInSystemSettings();
                        }
                    },
                    onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
                        console.debug(TAG, `dialog onWillDismiss reason= + ${JSON.stringify(dismissDialogAction.reason)}`);
                        //不管是点击三键back、左滑/右滑、键盘ESC，还是点击遮障层,或者是下拉关闭都不退出；只有点击关闭按钮时才退出
                        if (dismissDialogAction.reason == DismissReason.CLOSE_BUTTON) {
                            dismissDialogAction.dismiss();
                        }
                    },
                    autoCancel: false,
                    alignment: DialogAlignment.Center
                });
                break;
            }
        }
    }
    // 打开系统权限设置页
    async openPermissionsInSystemSettings(): Promise<void> {
        console.error(TAG, `openPermissionsInSystemSettings`);
        let context = getContext(this) as common.UIAbilityContext;
        let currentBundleName = await PermissionsUtils.getBundleName();
        let wantInfo: Want = {
            bundleName: 'com.huawei.hmos.settings',
            abilityName: 'com.huawei.hmos.settings.MainAbility',
            uri: 'application_info_entry',
            parameters: {
                settingsParamBundleName: currentBundleName // Open the details page of a specified application.
            }
        };
        try {
            context.startAbilityForResult(wantInfo).then((result: common.AbilityResult) => {
                console.info(TAG, `startAbility Success:${result.resultCode}`);
            }).catch((err: BusinessError) => {
                // 处理业务逻辑错误
                console.error(TAG, `startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
            });
        }
        catch (err) {
            // 处理入参错误异常
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error(TAG, `startAbilityForResult failed, code is ${code}, message is ${message}`);
        }
    }
    rerender() {
        this.updateDirtyElements();
    }
    static getEntryName(): string {
        return "Index";
    }
}
{
    let routeNameNode = 'WebView';
    registerNamedRoute(() => new Index(undefined, {}), routeNameNode, { bundleName: "com.esign.sdk", moduleName: "entry", pagePath: "../../../../esignfacesdk/src/main/ets/pages/WebView", pageFullPath: "esignfacesdk/src/main/ets/pages/WebView", integratedHsp: "false", moduleType: "followWithHap" });
}
