/* 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;
	route: any;
}
class Twitter extends Component<Props> {
	webref: any;
	packUrl: any;
	taskLikeMap: Map<string, any> = new Map();
	taskRetweetMap: Map<string, any> = new Map();

	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)) ||
			{};
		let callBackData: any = null;
		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;
			case 'TwitterLikeSuccess':
				callBackData = this.taskLikeMap.get(data.tweetId) || {};
				if (callBackData) {
					DeviceEventEmitter.emit(
						callBackData.info.rnMessageId,
						data,
					);
				}
				break;
			case 'RetweetSuccess':
				callBackData = this.taskRetweetMap.get(data.tweetId) || {};
				if (callBackData) {
					DeviceEventEmitter.emit(
						callBackData.info.rnMessageId,
						data,
					);
				}
		}
	};
	handleWebViewNavigationStateChange = (newNavState: { url: any }) => {
		const { url } = newNavState;
		this.packUrl = url;
		console.log(url);
		if (!url) {
			return;
		}
	};
	injectJavaScript = () => {
		this.webref.injectJavaScript(`
		(${addDom})();
      true;
    `);
	};

	getSplitTweetId(tweetId: string) {
		const idArray = tweetId.split('');
		console.log('idArray', idArray);
		const len = idArray.length;
		const idArray1 = idArray.splice(0, Math.floor(len / 2));
		const id1 = idArray1.join('');
		const id2 = idArray.join('');
		return { id1, id2 };
	}

	FavoriteTweet = (data: any) => {
		console.log('FavoriteTweet', data);
		const { id1, id2 } = this.getSplitTweetId(data.data.tweetId);
		this.taskLikeMap.set(data.data.tweetId, data);
		this.webref.injectJavaScript(`
		window.denetJS.TwitterLikeAPI(${id1},${id2});
		true;
	`);
	};

	retweet(data: any) {
		console.log('retweet', data);
		const { id1, id2 } = this.getSplitTweetId(data.data.tweetId);
		this.taskRetweetMap.set(data.data.tweetId, data);
		this.webref.injectJavaScript(`
		window.denetJS.TwitterRetweetAPI(${id1},${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_DO_TASK_LIKE', (data: any) => {
			this.FavoriteTweet(data);
		});
		DeviceEventEmitter.addListener(
			'IFRAME_DO_TASK_RETWEET',
			(data: any) => {
				this.retweet(data);
			},
		);
	}

	render() {
		return (
			<View style={{ flex: 1 }}>
				<DenetWebview
					onLoadEndHandle={this.injectJavaScript}
					refHandle={r => (this.webref = r)}
					onMessageHandle={this.onMessageHandle}
					handleWebViewNavigationStateChange={
						this.handleWebViewNavigationStateChange
					}
					uri={this.props.route.params.webUrl}
				/>
			</View>
		);
	}
}
export default Twitter;
