/**
 * 登录模块
 */
import { useState, useEffect } from 'react';
import { postRequest } from '@/netWork/index';
import { getStorageData, setStorageData } from '@/storage/index';
import { Alert } from 'react-native';

type LoginParams = {
	consumerKey: String;
	authToken: String;
};
type UserInfo = {
	accessToken?: String;
	avatarUrl?: String;
	nickName?: String;
	uid?: Number;
};
export const useLoginCom = (props: any) => {
	const [userInfo, setUserInfo] = useState({} as UserInfo);
	const [loginParams, setLoginParamsData] = useState({} as LoginParams);
	const [loading, setLoading] = useState(false);
	const [isLogin, setIsLogin] = useState(false);
	const goTwitterAuthorize = async () => {
		setLoading(true);
		let params = {
			oauthCallback: 'https://testh5.denetme.net/authloginApp',
		};
		postRequest('/denet/user/twitterRequestToken', params)
			.then((res: any) => {
				setLoginParamsData(res.data);
				if (res.code === 0) {
					props.navigation.navigate('Login', {
						token: res.data.authToken,
					});
				}
			})
			.catch((e: any) => {
				console.log('e', e);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	const twitterLogin = (verifier: any) => {
		setLoading(true);
		if (verifier) {
			postRequest('/denet/user/twitterLogin', {
				consumerKey: loginParams.consumerKey,
				oauthToken: loginParams.authToken,
				oauthVerifier: verifier,
			})
				.then(({ code, data }) => {
					if (code === 0) {
						setIsLogin(true);
						setUserInfo(data);
						return setStorageData('userInfo', data);
					} else {
						Alert.alert('login fail');
					}
				})
				.catch((err: any) => {
					Alert.alert('login fail.' + err);
				})
				.finally(async () => {
					setLoading(false);
				});
		}
	};

	const logOut = async () => {
		await setStorageData('userInfo', {});
		setIsLogin(false);
		setUserInfo({});
	};

	useEffect(() => {
		const getUserInfo = async () => {
			const user = await getStorageData('userInfo');
			if (user.accessToken) {
				setUserInfo(user);
				setIsLogin(true);
			}
		};
		getUserInfo();
	}, []);

	useEffect(() => {
		const unsubscribe = props.navigation.addListener('focus', async () => {
			const user = await getStorageData('userInfo');
			if (user.verifier) {
				setIsLogin(false);
				twitterLogin(user.verifier);
			} else if (user.accessToken) {
				setUserInfo(user);
				setIsLogin(true);
			} else {
				setUserInfo(user);
				setIsLogin(false);
			}
		});
		return unsubscribe;
	}, [props.navigation, twitterLogin]);

	return {
		isLogin,
		loading,
		userInfo,
		goTwitterAuthorize,
		logOut,
	};
};
