<template>
	<view class="act915page" v-if="!loading">
		<span class="act915pagebg" :style="getBackgroundStyle()"></span>
		<span class="act915pagegoods1" :style="{ backgroundImage: `url(${$baseUrl}${getImageUrl('goods1')})` }"></span>
		<!-- 商品3区域 - 分成3个点击区域 -->
		<view class="act915pagegoods3-container">
			<span class="act915pagegoods3bg"
				:style="{ backgroundImage: `url(${$baseUrl}${getGoodsImage('goods3')})` }"></span>

			<!-- 三个商品点击区域 -->
			<view class="act915pagegoods3products">
				<!-- 商品1 - 左侧 -->
				<view class="act915pagegoods3product product-left" @click="handleGoods3Click(1)"></view>

				<!-- 商品2 - 中间 -->
				<view class="act915pagegoods3product product-center" @click="handleGoods3Click(2)"></view>

				<!-- 商品3 - 右侧 -->
				<view class="act915pagegoods3product product-right" @click="handleGoods3Click(3)"></view>
			</view>
		</view>
		<!-- 商品列表2区域 - 分成6个点击区域 -->
		<view class="act915pagegoodslist2-container">
			<span class="act915pagegoodslist2bg"
				:style="{ backgroundImage: `url(${$baseUrl}${getGoodsImage('goodslist2')})` }"></span>

			<!-- 6个商品点击区域 -->
			<view class="act915pagegoodslist2products">
				<!-- 商品1 - 第一行左侧 -->
				<view class="act915pagegoodslist2product product-1" @click="handleGoodsList2Click(1)"></view>

				<!-- 商品2 - 第一行中间 -->
				<view class="act915pagegoodslist2product product-2" @click="handleGoodsList2Click(2)"></view>

				<!-- 商品3 - 第一行右侧 -->
				<view class="act915pagegoodslist2product product-3" @click="handleGoodsList2Click(3)"></view>

				<!-- 商品4 - 第二行左侧 -->
				<view class="act915pagegoodslist2product product-4" @click="handleGoodsList2Click(4)"></view>

				<!-- 商品5 - 第二行中间 -->
				<view class="act915pagegoodslist2product product-5" @click="handleGoodsList2Click(5)"></view>

				<!-- 商品6 - 第二行右侧 -->
				<view class="act915pagegoodslist2product product-6" @click="handleGoodsList2Click(6)"></view>
			</view>
		</view>
		<!-- 商品列表1区域 - 分成6个点击区域 -->
		<view class="act915pagegoodslist1-container">
			<span class="act915pagegoodslist1bg"
				:style="{ backgroundImage: `url(${$baseUrl}${getGoodsImage('goodslist1')})` }"></span>

			<!-- 6个商品点击区域 -->
			<view class="act915pagegoodslist1products">
				<!-- 商品1 - 第一行左侧 -->
				<view class="act915pagegoodslist1product product-1" @click="handleGoodsList1Click(1)"></view>

				<!-- 商品2 - 第一行中间 -->
				<view class="act915pagegoodslist1product product-2" @click="handleGoodsList1Click(2)"></view>

				<!-- 商品3 - 第一行右侧 -->
				<view class="act915pagegoodslist1product product-3" @click="handleGoodsList1Click(3)"></view>

				<!-- 商品4 - 第二行左侧 -->
				<view class="act915pagegoodslist1product product-4" @click="handleGoodsList1Click(4)"></view>

				<!-- 商品5 - 第二行中间 -->
				<view class="act915pagegoodslist1product product-5" @click="handleGoodsList1Click(5)"></view>

				<!-- 商品6 - 第二行右侧 -->
				<view class="act915pagegoodslist1product product-6" @click="handleGoodsList1Click(6)"></view>
			</view>
		</view>

		<div class="act915pageinvitecon">
			<button class="act915pageinviteconbg" @click="handleInviteClick"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl('inviteConBg')})` }"
				open-type="share"></button>


			<div class="act915pageinviteconstatus">
				<span class="act915pageinviteconstatusno2"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl('inviteConStatusNo2')})` }"></span>
				<span class="act915pageinviteconstatusno1"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl('inviteConStatusNo1')})` }"></span>
				<span class="act915pageinviteconstatusyes2"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl('inviteConStatusYes2')})` }"></span>
				<span class="act915pageinviteconstatusyes1"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl('inviteConStatusYes1')})` }"></span>
			</div>
		</div>

		<span class="act915pagelotterybanner"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl('lotteryBanner')})` }"
			@click="handleLotteryClick"></span>

		<!-- Banner轮播图 -->
		<swiper class="act915pagebanner" :indicator-dots="true" :autoplay="false" :circular="true" :interval="3000"
			:duration="500">
			<swiper-item v-for="(banner, index) in bannerList" :key="index" @click="handleBannerClick(index)">
				<image class="act915pagebanneritem" :src="$baseUrl + getBannerImage(banner)" mode="aspectFill"></image>
			</swiper-item>
		</swiper>

		<!-- Full screen mask for new users -->
		<view class="full-mask" v-if="showMask">
			<button open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">授权手机号</button>
		</view>
	</view>
	<!-- 加载状态 -->
	<view v-else class="loading-container">
		<text>加载中...</text>
	</view>
</template>

<script setup>
import { ref, onMounted, computed, getCurrentInstance } from 'vue'
import { fetchAct915JSON, getAct915Home } from '@/api/activity0915/index.js'
import { useHomeStore } from '@/stores/home'; // Assuming homeStore path
import { invitationAssist } from '@/api/activity0915/index.js'; // Import invitationAssist
import DrawSucModal from '../lottery/components/drawSucModal/drawSucModal.vue'; // Import DrawSucModal if needed

// 组件名称
defineOptions({
	name: 'Act915Page'
})

// 响应式数据
const currentState = ref('normal') // 页面状态
const config = ref({}) // 配置对象
const bannerList = ref([]) // Banner列表
const loading = ref(true) // 加载状态

// New refs for sharing and phone authorization
const showMask = ref(false);
const showDrawSucModal = ref(false);
const currentAwardName = ref('');
const invitationCode = ref('');

// Share logic for right-top (normal share without code)
onShareAppMessage(() => {
	return {
		title: '分享标题', // Customize
		path: '/activity0915/act0915/act0915' // Without code
	};
});



// 获取背景样式的辅助函数
const getBackgroundStyle = () => {
	const backgroundImage = getImageUrl('background')
	if (backgroundImage) {
		// 获取全局属性
		const { proxy } = getCurrentInstance()
		const $baseUrl = proxy.$baseUrl
		return {
			backgroundImage: `url(${$baseUrl}${backgroundImage})`
		}
	} else {
		// 如果背景图片不存在，使用渐变背景
		return {
			background: `linear-gradient(to bottom, ${config.value?.background?.color}, ${config.value?.background?.color2})`
		}
	}
}

// 获取图片URL的辅助函数
const getImageUrl = (imageKey) => {
	// 根据不同的图片类型从对应的结构中获取
	switch (imageKey) {
		case 'background':
			return config.value?.background?.image || ''
		case 'goods1':
			return config.value?.goods?.goods1?.image || ''
		case 'inviteConBg':
			return config.value?.invite?.image || ''
		case 'inviteConStatusNo2':
			return config.value?.invite?.inviteConStatusNo2Img || ''
		case 'inviteConStatusNo1':
			return config.value?.invite?.inviteConStatusNo1Img || ''
		case 'inviteConStatusYes2':
			return config.value?.invite?.inviteConStatusYes2Img || ''
		case 'inviteConStatusYes1':
			return config.value?.invite?.inviteConStatusYes1Img || ''
		case 'lotteryBanner':
			return config.value?.lottery?.image || ''
		default:
			// 兼容原有的结构
			if (config.value?.images?.[imageKey]) {
				return config.value.images[imageKey]
			}
			if (config.value?.config?.images?.[imageKey]) {
				return config.value.config.images[imageKey]
			}
			if (config.value && config.value[imageKey]) {
				return config.value[imageKey]
			}
			return ''
	}
}

// 获取Banner图片的辅助函数
const getBannerImage = (banner) => {
	// 如果是融合结构（包含 image 和 link）
	if (banner && typeof banner === 'object' && banner.image) {
		return banner.image
	}
	// 兼容原有的字符串结构
	return banner || ''
}

// 获取商品图片的辅助函数
const getGoodsImage = (goodsKey) => {
	// 从商品数据结构中获取图片
	const goodsData = config.value.goods?.[goodsKey]
	if (goodsData && goodsData.image) {
		return goodsData.image
	}
	// 兼容原有的 config.images 结构
	return getImageUrl(goodsKey)
}

// 获取配置数据
const fetchConfig = async () => {
	try {
		loading.value = true
		const response = await fetchAct915JSON()
		console.log('915活动配置数据:', response)

		if (response && response.data) {
			config.value = response.data
			// 设置Banner列表
			if (config.value.act915pagebanner && Array.isArray(config.value.act915pagebanner)) {
				// 检查是否是融合结构（包含 image 和 link）
				if (config.value.act915pagebanner[0] && typeof config.value.act915pagebanner[0] === 'object' && config.value.act915pagebanner[0].image) {
					bannerList.value = config.value.act915pagebanner
				} else {
					// 兼容原有的字符串数组结构
					bannerList.value = config.value.act915pagebanner
				}
			} else if (config.value.config?.images) {
				bannerList.value = [
					config.value.config.images.banner,
					config.value.config.images.banner2,
					config.value.config.images.banner3
				].filter(Boolean)
			}
		}
	} catch (error) {

	} finally {
		loading.value = false
	}
}

// 获取915活动首页信息
const fetchAct915HomeData = async () => {
	try {
		console.log('开始请求 getAct915Home 接口...')
		const response = await getAct915Home()
		console.log('getAct915Home 接口返回结果:', response)
		console.log('getAct915Home 接口返回数据:', response.data)

		// 输出详细的返回信息
		if (response && response.data) {
			console.log('=== getAct915Home 接口返回详情 ===')
			console.log('状态码:', response.status)
			console.log('消息:', response.message)
			console.log('数据:', JSON.stringify(response.data, null, 2))
			console.log('================================')
		}

		return response
	} catch (error) {
		console.error('getAct915Home 接口请求失败:', error)
		console.error('错误详情:', error.message)
		console.error('错误状态:', error.status)
		return null
	}
}

const handleLotteryClick = () => {
	// 从配置中获取抽奖banner链接
	const lotteryLink = config.value?.lottery?.link
	if (lotteryLink) {
		jump(lotteryLink)
	} else {
		uni.navigateTo({
			url: '/activity0915/lottery/lottery'
		})
	}
}

// 统一的跳转处理函数
const jump = (linkConfig) => {
	if (!linkConfig || !linkConfig.url) {
		console.warn('链接配置无效:', linkConfig)
		return
	}

	const { type, url, extra } = linkConfig

	try {
		switch (type) {
			case 1: // 内部页面跳转
				uni.navigateTo({
					url: url,
					fail: (err) => {
						console.error('页面跳转失败:', err)
						uni.showToast({
							title: '页面跳转失败',
							icon: 'none'
						})
					}
				})
				break
			case 2: // 小程序跳转
				uni.navigateToMiniProgram({
					appId: extra?.appId,
					path: url,
					extraData: extra?.extraData || {},
					envVersion: extra?.envVersion || 'release',
					fail: (err) => {
						console.error('小程序跳转失败:', err)
						uni.showToast({
							title: '小程序跳转失败',
							icon: 'none'
						})
					}
				})
				break
			case 3: // 外部链接
				// #ifdef H5
				window.open(url, '_blank')
				// #endif
				// #ifdef MP-WEIXIN
				uni.setClipboardData({
					data: url,
					success: () => {
						uni.showToast({
							title: '链接已复制到剪贴板',
							icon: 'success'
						})
					}
				})
				// #endif
				break
			default:
				console.warn('未知的链接类型:', type)
				uni.showToast({
					title: '链接类型不支持',
					icon: 'none'
				})
		}
	} catch (error) {
		console.error('链接跳转处理失败:', error)
		uni.showToast({
			title: '跳转失败',
			icon: 'none'
		})
	}
}

// 商品3区域点击处理
const handleGoods3Click = (productId) => {
	console.log('点击商品3区域商品:', productId)

	// 从配置中获取商品信息
	const goods3Data = config.value.goods?.goods3
	const goods3List = goods3Data?.items || []
	const product = goods3List.find(item => item.id === productId)

	if (product && product.link) {
		// 直接处理跳转链接
		jump(product.link)
	} else {
		// 使用默认处理
		uni.showToast({
			title: `商品${productId}暂无跳转链接`,
			icon: 'none'
		})
	}
}

// 商品列表1区域点击处理
const handleGoodsList1Click = (productId) => {
	console.log('点击商品列表1区域商品:', productId)

	// 从配置中获取商品信息
	const goodsList1Data = config.value.goods?.goodslist1
	const goodsList1 = goodsList1Data?.items || []
	const product = goodsList1.find(item => item.id === productId)

	if (product && product.link) {
		// 直接处理跳转链接
		jump(product.link)
	} else {
		// 使用默认处理
		uni.showToast({
			title: `商品列表1-商品${productId}暂无跳转链接`,
			icon: 'none'
		})
	}
}

// 商品列表2区域点击处理
const handleGoodsList2Click = (productId) => {
	console.log('点击商品列表2区域商品:', productId)

	// 从配置中获取商品信息
	const goodsList2Data = config.value.goods?.goodslist2
	const goodsList2 = goodsList2Data?.items || []
	const product = goodsList2.find(item => item.id === productId)

	if (product && product.link) {
		// 直接处理跳转链接
		jump(product.link)
	} else {
		// 使用默认处理
		uni.showToast({
			title: `商品列表2-商品${productId}暂无跳转链接`,
			icon: 'none'
		})
	}
}


// Banner点击处理
const handleBannerClick = (index) => {
	console.log('点击Banner:', index)

	// 获取当前Banner数据
	const currentBanner = bannerList.value[index]

	// 如果是融合结构（包含 image 和 link）
	if (currentBanner && typeof currentBanner === 'object' && currentBanner.link) {
		jump(currentBanner.link)
	} else {
		// 兼容原有的分离结构
		const bannerLinks = config.value.links?.banner
		if (bannerLinks && bannerLinks[index]) {
			jump(bannerLinks[index])
		} else {
			uni.showToast({
				title: `Banner ${index + 1} 暂无跳转链接`,
				icon: 'none'
			})
		}
	}
}

// 邀请按钮点击处理
const handleInviteClick = () => {
	console.log('点击邀请按钮')


}

// 生命周期
onMounted(async () => {
	console.log('915活动页面已加载')
	await fetchConfig()
	console.log('Banner列表:', bannerList.value)
	console.log('配置数据:', config.value)

	// 请求 getAct915Home 接口
	const homeData = await fetchAct915HomeData();

	if (homeData && homeData.data) {
		invitationCode.value = homeData.data.invitationCode;

		// Check if new user (assuming !homeStore.isLogin means new user)
		if (!homeStore.isLogin) {
			showMask.value = true;
		} else {
			// Old user
			const unclaimed = homeData.data.unclaimedPrizes[0];
			if (unclaimed) {
				currentAwardName.value = `${unclaimed.prizeName} * ${unclaimed.quantity}`;
				showDrawSucModal.value = true;
			}
		}
	}

	// Get query params for invitationCode
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const options = currentPage.options;
	const incomingCode = options.invitationCode;
});

// Phone authorization
const onGetPhoneNumber = async (e) => {
	if (e.detail.errMsg === 'getPhoneNumber:ok') {
		// Handle phone authorization success (call API to login/register)
		// Assuming success, hide mask
		showMask.value = false;
		homeStore.isLogin = true; // Update store

		// Check for incoming invitationCode
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const options = currentPage.options;
		const incomingCode = options.invitationCode;

		if (incomingCode) {
			try {
				const res = await invitationAssist({ code: incomingCode });
				uni.showToast({ title: res.success ? '助力成功' : '助力失败' });
			} catch (error) {
				uni.showToast({ title: '助力失败' });
			}
		}
	} else {
		uni.showToast({ title: '授权失败' });
	}
};
</script>

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