/* eslint-disable react-native/no-inline-styles */
import React, { Component } from 'react';
import { View, DeviceEventEmitter } from 'react-native';
import { DenetWebview } from '@/components/webview';
import { addDom, addDataToStorge } from '../../utils/contentInTwitterJS/addDom';
// import EventEmitter from 'react-native-eventemitter';

interface Props {
	navigation: any;
}
class Twitter extends Component<Props> {
	webref: any;
	packUrl: any;

	getPostIdByType = (post_Id: string) => {
		let result: any = { post_Id };
		if (post_Id.includes('nft/')) {
			result.post_Id = post_Id.replace('nft/', '');
			result.page_type = 'NFT';
		} else if (post_Id.includes('nft_group/')) {
			result.post_Id = post_Id.replace('nft_group/', '');
			result.page_type = 'nft_group';
		} else if (post_Id.includes('luckdraw/')) {
			result.post_Id = post_Id.replace('luckdraw/', '');
			result.page_type = '抽奖';
		} else if (post_Id.includes('toolbox/')) {
			result.post_Id = post_Id.split('toolbox/')[1] || '';
			result.page_type = 'toolbox';
		} else if (!post_Id.includes('/')) {
			result.post_Id = post_Id;
			result.page_type = '红包';
		} else if (post_Id.includes('treasure/')) {
			if (post_Id.includes('invite/')) {
				post_Id = post_Id.replace('/undefined', '');
				let arr = post_Id.split('/');
				let index;
				for (let i in arr) {
					index = Number(i) + 1;
					if (arr[i] == 'invite' && arr.length >= index) {
						result.invite_code = arr[index];
						if (arr.length > index + 1) {
							result.invite_channel = arr[index + 1];
						} else {
							result.invite_channel = '';
						}
						break;
					}
				}

				result.page_type = '邀请链接';
				if (result.invite_code) {
					result.post_Id = '';
				}
			} else {
				// 原始链接
				result.page_type = '原始链接';
				result.post_Id = result.post_Id.split('treasure/')[1] || '';
			}
		}
		return result;
	};

	onMessageHandle = async (messageData: any) => {
		let { actionType, data } =
			(messageData.nativeEvent.data &&
				JSON.parse(messageData.nativeEvent.data)) ||
			{};
		switch (actionType) {
			case 'goDetailPage':
				// const { tweet_Id, ct0, post_Id, invite_code } = data;
				this.props.navigation.navigate('Redpack', data);
				break;
			case 'fetchPostId':
				const postId = await this.getPostId(data.short_url);
				const postIdData = this.getPostIdByType(postId);
				data = { ...data, ...postIdData };
				this.webref.injectJavaScript(`
				(${addDataToStorge})(${JSON.stringify(data)});
				true;
				`);
				break;
		}
	};
	handleWebViewNavigationStateChange = (newNavState: { url: any }) => {
		const { url } = newNavState;
		this.packUrl = url;
		console.log(url);
		if (!url) {
			return;
		}
	};
	injectJavaScript = () => {
		this.webref.injectJavaScript(`
		(${addDom})();
      true;
    `);
	};

	FavoriteTweet = (data: any) => {
		// let jsString = `window.TwitterLikeAPI(${data.tweet_Id})`;
		// data = JSON.parse(data);
		console.log('FavoriteTweet', data);
		// 	this.webref.injectJavaScript(`
		// 	window.TwitterLikeAPI(${data.id1},${data.id2});
		//   true;
		// `);
	};

	getPostId(shortUrl: RequestInfo) {
		return fetch(shortUrl) // 返回一个Promise对象
			.then(res => {
				return res.text(); // res.text()是一个Promise对象
			})
			.then(res => {
				res = res.toString();
				let str_arr = res.match(/denetme.net\/([\s\S]*?)"/) || [];
				let post_Id = str_arr[1] || '';
				return post_Id;
			});
	}

	async componentDidMount() {
		DeviceEventEmitter.addListener(
			'IFRAME_TWITTER_API_DO_TASK',
			(data: any) => {
				this.FavoriteTweet(data);
			},
		);
	}

	render() {
		return (
			<View style={{ flex: 1 }}>
				<DenetWebview
					onLoadEndHandle={this.injectJavaScript}
					refHandle={r => (this.webref = r)}
					onMessageHandle={this.onMessageHandle}
					handleWebViewNavigationStateChange={
						this.handleWebViewNavigationStateChange
					}
					uri="https://mobile.twitter.com/home"
				/>
			</View>
		);
	}
}
export default Twitter;
