/**
 * 通用 webview 封装
 */
import React from 'react';
import { WebView } from 'react-native-webview';
import { getStorageData } from '@/storage/';
import { getMid } from '@/utils/';

interface Props {
	uri: any;
	onLoadEndHandle?: () => void;
	handleWebViewNavigationStateChange?: (newNavState: { url: any }) => void;
	onMessageHandle?: (e: any) => void;
	refHandle?: (r: any) => any;
	style?: any;
}
export const DenetWebview = (props: Props) => {
	const innerRefHandle = async (r: any) => {
		const mid = await getMid();
		const userInfo = await getStorageData('userInfo');
		if (props.refHandle) {
			props.refHandle(r);
		}
		if (mid && userInfo && r) {
			r.injectJavaScript(`
			window.denetData = ${JSON.stringify({
				mid,
				userInfo,
			})};
		  true;
		`);
		}
	};

	return (
		<WebView
			applicationNameForUserAgent={'denet/1.1.0'}
			mediaCapturePermissionGrantType={'grant'}
			setSupportMultipleWindows={false}
			javaScriptEnabled={true}
			startInLoadingState={true}
			originWhitelist={['*']}
			cacheEnabled={true}
			javaScriptCanOpenWindowsAutomatically={true}
			allowUniversalAccessFromFileURLs={true}
			allowFileAccessFromFileURLs={true}
			onLoadEnd={props.onLoadEndHandle}
			ref={r => innerRefHandle(r)}
			onMessage={props.onMessageHandle}
			onNavigationStateChange={props.handleWebViewNavigationStateChange}
			style={props.style}
			source={{
				uri: props.uri,
			}}
		/>
	);
};
