<template>
	<view class="sharepage_container">
		<view class="background_image_container">
			<!-- 背景图片 -->
			<image class="background_image" :src="$baseUrl + 'homepage/shareImg_jf2.jpg'" mode="aspectFit" />
			
			<!-- 一键领取按钮 -->
			<view class="claim_button" @click="handleClaim">
				<text class="claim_text">一键领取</text>
			</view>
			<button class="sharepage_login_button" 
				v-if="!isLogin"
			 	open-type="getPhoneNumber" 
				@getphonenumber="onGetPhoneNumber"
				:debug-mode="debugMode"
			/>
		</view>


		<!-- 邀请奖品弹窗 -->
		<InvitePrizePanel 
			:visible="isShowInvitePrizePanel"
			:inviteCount="inviteCount"
			:prizeName="prizeName"
			:prizeImage="prizeImage"
			:prizeType="prizeType"
			:memberId="memberId"
			@close="handleCloseInvitePrizePanel"
			@record="handleInvitePrizePanelRecord"
			@prize="handleInvitePrizePanelPrize"
		/>
		
		<!-- 分享登录弹窗 -->
		<sharepoplogin 
			:visible="showSharePopLogin" 
			@close="handleCloseSharePopLogin"
			@viewBenefits="handleViewBenefits"
		/>
		
		<!-- 分享未登录弹窗
		<sharenpopnologin 
			:visible="showShareNPopNoLogin" 
			@close="handleCloseShareNPopNoLogin"
			@viewBenefits="handleViewBenefits"
		/> -->
	</view>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue';
import { onShareAppMessage, onShow } from '@dcloudio/uni-app';
import sharepoplogin from '@/components/integralArea/sharepoplogin.vue';
import sharenpopnologin from '@/components/integralArea/sharenpopnologin.vue';
import { jump, JumpType, showLoading, hideLoading } from '../../utils';
import { useGlobalStore } from '@/stores/global';
import { useUserStore } from '@/stores/user';
import { useIntegralStore } from '@/stores/integral';
import md from '../../md';

// 分享登录弹窗状态
const showSharePopLogin = ref(false);

// 分享未登录弹窗状态
const showShareNPopNoLogin = ref(false);

const handlePageClick = () => {
	// console.log('handlePageClick');
	// if(!isLogin.value) {
	// 	needReinit.value = true;
	// 	jump({
	// 		type: JumpType.INNER,
	// 		url: "/pages/activity/register",
	// 	})
	// }
};

// 获取store实例
const userStore = useUserStore();
const globalStore = useGlobalStore();
const integralStore = useIntegralStore();

const isLogin = ref(false);

const isnew = ref(false);

const inviteCode = ref('');
const unionId = ref('');

const showPhone = ref(false);

const isShowInvitePrizePanel = ref(false);

const inviteCount = ref(0);
const prizeName = ref('');
const prizeImage = ref('');
const prizeType = ref('');
const memberId = ref('');

// 获取邀请码和unionId
const initInviteParams = () => {
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const options = currentPage.options || {};
	const inviteCode1 = options.inviteCode || '';
	
	inviteCode.value = inviteCode1;
	unionId.value = uni.getStorageSync('unionId');
	
	console.log('unionIdsharepage:', unionId.value);
	
	return { inviteCode: inviteCode1, unionId: unionId.value };
};

onMounted(async() => {
	md.sensorComponentLogTake({
		xcxComponentExposure: "true",
		pageName: "新人福利页",
		componentName: "新人福利页",
		componentContent: "立即领取"
	});

	showLoading();
	// 先进行自动登录获取基础信息，登录成功后执行页面初始化
	try {
		console.log('开始执行 normalAutoLogin...')
		await userStore.normalAutoLogin(initPage)
		console.log('normalAutoLogin 完成')
	} catch (error) {
		console.error('normalAutoLogin 失败:', error)
		// 即使登录失败也执行页面初始化
		await initPage()
	}

	// 先隐藏朋友圈分享
	uni.hideShareMenu({
		menus: ['shareTimeline']
	});

	
});

const initPage = async () => {
	// 调用邀请活动首页接口
	const integralStore = useIntegralStore();

	// 获取邀请码参数
	const { inviteCode: ivtCode, unionId: uid } = initInviteParams();

	console.log('originInviteBind---ivtCode--sharepage:', ivtCode);
	console.log('uid--sharepage:', uid);
	// 调用邀请绑定接口
	if (ivtCode && uid) {
		try {
			const bindRes = await integralStore.originInviteBind(uid, ivtCode);
			console.log('邀请绑定接口返回:', bindRes);
		} catch (error) {
			console.error('调用邀请绑定接口失败:', error);
		}
	}

	//获取邀请码和奖励
	const res = await integralStore.getOriginInviteHome(); 

	memberId.value = res.data?.memberId;
	console.log('res--sharepage:', res);

	// const unionId = uni.getStorageSync('unionId');

	

	if(res.success){
		const unclaimedPrize = res.data?.unclaimedPrize;
		if(res.data?.notLogin){
			isLogin.value = false;
			hideLoading();
		}else{
			isLogin.value = true;
			if(unclaimedPrize) {
				isShowInvitePrizePanel.value = true;
				inviteCount.value = res.data?.invitedCount;
				prizeName.value = unclaimedPrize?.prizeName;
				prizeImage.value = unclaimedPrize?.prizeImageUrl;
				prizeType.value = unclaimedPrize?.prizeType;
			}

			if(isLogin.value) {	
				console.log(111111111111111);
				// 如果有邀请码，调用助力接口
				if (ivtCode && isLogin.value) {
					await callAssistInvite(ivtCode, uid);
					hideLoading();
				}
			}

			hideLoading();
		}
		
	}else{
		console.log('获取邀请活动首页接口失败');
		isLogin.value = false;
		hideLoading();
		// uni.showToast({title: '网络问题，请稍后再试', icon: 'none'});
	}

	console.log('onMounted--sharepage:', isLogin.value);
	// 页面加载时显示分享未登录弹窗
	// showShareNPopNoLogin.value = true;
	
}

  // Phone authorization
const onGetPhoneNumber = async (e) => {
	console.log('onGetPhoneNumber', e.detail)
	showLoading('授权中...')
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const options = currentPage.options;
	const incomingCode = options.inviteCode;

	if (e.detail.errMsg === 'getPhoneNumber:ok') {
		try {
			// console.warn('onGetPhoneNumber', e.detail)
			// 隐藏授权弹窗

			console.log('onGetPhoneNumber-phoneCallback-sharepage:', userStore.phoneCallback);
			userStore.phoneCallback(e.detail, null, null, async () => {
				// 重新获取用户信息（登录后）getphonenumber
				await Promise.all([
				userStore.loadUserInfo(),
				userStore.loadMemberInfo(),
				])
				console.warn('授权后重新获取用户信息')

				// 获取邀请码参数
				const { inviteCode: ivtCode, unionId: uid } = initInviteParams();

				isLogin.value = true;
				// 如果有邀请码，调用助力接口
				if (ivtCode && isLogin.value) {
					await callAssistInvite(ivtCode, uid);
				}
				hideLoading()

			}, {
				wxLoginBusinessDTO: {
					originInviteShareCode: incomingCode
				}
			})
		} catch (error) {
			hideLoading()
			console.error('授权后处理失败:', error)
			uni.showToast({title: '授权失败', icon: 'none'});
		}
	} else {
		hideLoading()
		uni.showToast({title: '授权失败', icon: 'none'});
	}
};

// 调用助力接口
const callAssistInvite = async (ivtCode,unionId) => {

	console.log('callAssistInvite-ivtCode:', ivtCode);
	console.log('callAssistInvite-unionId:', unionId);
	showLoading('助力中...');
	try {
		// 获取用户unionId
		
		const res = await integralStore.assistInvite(ivtCode, unionId);
		if(res.success && res.data.newUser) {
			globalStore.invateUseType = 'new';
		}else{
			showSharePopLogin.value = true;
		}

		// if(res.success && res.data.newUser) {
		// 	globalStore.invateUseType = 'new';
		// } else {
		// 	globalStore.invateUseType = 'old';
		// 	gotoIntegral();
		// }
		console.log('助力接口返回:', res);
		hideLoading();
	} catch (error) {
		console.error('调用助力接口失败:', error);
		hideLoading();
	}
};

onShow(() => {
	if(isLogin.value) {


		// if(integralStore.assistInviteData.success && integralStore.assistInviteData.data.newUser) {
		// 	globalStore.invateUseType = 'new';
		// 	//新用户注册登录后调用助力接口
		// 	gotoIntegral();


		// 	// 如果有邀请码，调用助力接口
		// 	if (inviteCode.value) {
		// 		callAssistInvite(ivtCode, unionId.value);
		// 	}
		// 	isnew.value = false;
		// }
	}
});

// 关闭分享登录弹窗
const handleCloseSharePopLogin = () => {
	showSharePopLogin.value = false;
};

// 关闭分享未登录弹窗
const handleCloseShareNPopNoLogin = () => {
	showShareNPopNoLogin.value = false;
};

// 查看权益按钮点击
const handleViewBenefits = () => {
	console.log('查看我的权益');
	// 这里可以添加跳转到权益页面的逻辑
	// uni.showToast({
	// 	title: '跳转到权益页面',
	// 	icon: 'none'
	// });
	gotoIntegral();
};

// 一键领取按钮点击事件
const handleClaim = () => {
	md.sensorComponentLogTake({
		xcxComponentClick: "true",
		pageName: "新人福利页",
		componentName: "新人福利页",
		componentContent: "立即领取"
	});

	if(!isLogin.value) {
		showPhone.value = true;
		return;
	}

	// 设置邀请用户类型
	if(integralStore.assistInviteData?.data?.newUser) {
		globalStore.invateUseType = 'new';
		gotoIntegral();
	} else {
		showSharePopLogin.value = true;
		// globalStore.invateUseType = 'old';
	}

};

const gotoIntegral = () => {
	jump({
		url: '/pages/index/index?pageType=integral',
		type: JumpType.INNER
	});
};

const handleCloseInvitePrizePanel = () => {
  isShowInvitePrizePanel.value = false;
};

const handleInvitePrizePanelRecord = () => {
  console.log('查看邀请记录');
  isShowInvitePrizePanel.value = false;
  // 这里可以添加跳转到邀请记录页面的逻辑
};

const handleInvitePrizePanelPrize = () => {
  console.log('查看奖品');
  isShowInvitePrizePanel.value = false;
  // 这里可以添加跳转到奖品页面的逻辑
};

// // 分享配置
// onShareAppMessage(() => {
// 	return {
// 		title: '积分分享',
// 		path: '/pages/invate/sharepage',
// 		imageUrl: ''
// 	};
// });
</script>

<style lang="less" scoped>
@import './sharepage.less';
</style>
