import {
	userInfo,
	userInfoIsInvest
} from '@/api/api.js';
import config from '@/config'
import {
	onShow,
	onLoad
} from '@dcloudio/uni-app';
import {
	reactive,
	ref,
	onMounted
} from 'vue';

export function userHook() {
	const user = reactive({});
	const isInvest = ref(false)
	const tabbar = ref([])


	const fetchUserData = async () => {
		if (!uni.getStorageSync('token')) {
			return
		}


		try {
			const data = isInvest.value ? await userInfoIsInvest() : await userInfo();
			Object.assign(user, data);
		} catch (error) {
			console.log(error);
		}
	};
	const tabbarData = async () => {
		// let isInvest = uni.getStorageSync('isInvest') || false;
		tabbar.value = isInvest.value ? [{
				index: 0,
				name: '首页',
				img: '/static/tabbar/select_home.png',
				acImg: '/static/tabbar/home.png'
			},
			{
				index: 1,
				name: '订单',
				img: '/static/tabbar/orderIs1.png',
				acImg: '/static/tabbar/orderIs.png'
			},
			{
				index: 2,
				name: '充电桩',
				img: '/static/tabbar/cds.png',
				acImg: '/static/tabbar/cd.png'
			},
			{
				index: 3,
				name: '我的',
				img: '/static/tabbar/select_my.png',
				acImg: '/static/tabbar/my.png'
			}
		] : [{
				index: 0,
				name: '首页',
				img: '/static/tabbar/select_home.png',
				acImg: '/static/tabbar/home.png'
			},
			{
				index: 1,
				name: '地图',
				img: '/static/tabbar/select_sq.png',
				acImg: '/static/tabbar/sq.png'
			},
			{
				index: 2,
				name: '扫一扫',
				img: '/static/tabbar/find.png',
				acImg: '/static/tabbar/find.png',
				type: 'big'
			},
			{
				index: 3,
				name: '发现',
				img: '/static/tabbar/select_order.png',
				acImg: '/static/tabbar/order.png'
			},
			{
				index: 4,
				name: '我的',
				img: '/static/tabbar/select_my.png',
				acImg: '/static/tabbar/my.png'
			}
		];
	};

	// onMounted(() => {
	// 	console.log('onMounted-Hook');
	// 	tabbarData()
	// })

	onLoad(() => {
		console.log('onLoad-Hook');
		isInvest.value = uni.getStorageSync('isInvest');
		if (isInvest.value === '') {
			isInvest.value = config.isInvest;
		}



		tabbarData()
	})

	onShow(async () => {
		console.log('onShow Hook');
		isInvest.value = uni.getStorageSync('isInvest');
		if (isInvest.value === '') {
			isInvest.value = config.isInvest;
		}
		await fetchUserData();
	});

	return {
		user,
		isInvest,
		fetchUserData,
		tabbar
	};
}