<template>
	<view class="tab_page adffc" :style="{'height':h+'px', 'padding-top':mt+'px'}">
		<up-navbar title=" " bgColor="transparent">
            <template #left>
				<view class="u-nav-slot" slot="left" style="display: flex;background-color: transparent;">
					<image src="https://oss.familydaf.cn/sxsnfile/20260105/087c26c68a18424c83763a768a2fd81d.png" style="width: 370rpx;height: 40rpx;"></image>
				</view>
			</template>
		</up-navbar>
		<image src="https://oss.familydaf.cn/sxsnfile/20251218/ee40161fef4647f0b736d118e554dc2f.png" class="top_bg_img" mode="widthFix"></image>
		<view class="c-box adffc">
			<view class="c-box-lunbo">
				<up-swiper
					:list="bannarList"
					@change="e => current = e.current"
					@click="bannerClick"
					:autoplay="true"
					:interval="2000"
					:duration="200"
					:circular="true"
					imgMode="scaleToFill"
					height="326rpx"
				>
					<template #indicator>
						<view class="indicator adf">
							<view class="indicator__dot" v-for="(item, index) in bannarList" :key="index"
								:class="[index === current && 'indicator__dot--active']">
							</view>
						</view>
					</template>
				</up-swiper>
			</view>
			<view class="c-box-title adfacjb">
				<view class="c-box-title-left">公益活动</view>
				<view class="c-box-title-right adfac" @click="toTurnPage('/pagesHome/allActivity',false)">更多 <up-icon name="arrow-right" size="30rpx" style="margin-left: 10rpx;"></up-icon></view>
			</view>
			<view class="c-box-type">
				<scroll-view class="scroll-view_H" scroll-x="true" scroll-with-animation="true" :scroll-left="scrollLeft">
					<view class="scroll-view-item_H" :id="'svih_'+index" v-for="(item,index) in typeList" :key="index" @click="changeType(item,index)">
						<view class="cl_item" :class="{'active':tlIndex===index}">
							<text>{{item.name}}</text>
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="c-box-list" v-if="activityList.length">
				<up-list @scrolltolower="scrolltolower" style="height: 100%;">
					<up-list-item v-for="(item, index) in activityList" :key="item.id">
						<NonprofitActivety :item="item" :index="index"></NonprofitActivety>
					</up-list-item>
				</up-list>
			</view>
			<view class="dataEmpty" v-else>
				<page-empty></page-empty>
			</view>
		</view>
		<login-register></login-register>
		<CusTabbar :tabbarIndex="0"></CusTabbar>
	</view>
</template>

<script setup name="">
	import CusTabbar from '@/components/CusTabbar/index.vue'
	import NonprofitActivety from '@/components/pages/nonprofitActivety/index.vue'
	import PageEmpty from '@/components/pageEmpty/index.vue'
	import { ref, getCurrentInstance, onMounted, nextTick, watch } from 'vue'
	const { proxy } = getCurrentInstance()
	import { useUserStore } from '@/common/stores/user';
	const userStore = useUserStore();
	import { onLoad } from '@dcloudio/uni-app'

	const parseUrlParams = (url) => {
		const result = {}
		const queryStr = url.indexOf('?') !== -1 ? url.split('?')[1] : (url.indexOf('#') !== -1 ? url.split('#')[1] : '')
		if (!queryStr) return result
		queryStr.split('&').forEach(pair => {
			const [key, val] = pair.split('=')
			if (key) result[decodeURIComponent(key)] = decodeURIComponent(val || '')
		})
		return result
	}

	onLoad((options) => {
		console.log('[onLoad] options:', JSON.stringify(options))
		console.log('[onLoad] options.q:', options.q, '| typeof:', typeof options.q)
		console.log('[onLoad] 条件判断 options && options.q:', !!(options && options.q))
		if (options && options.q) {
			console.log('[onLoad] 进入 if 分支')
			const url = decodeURIComponent(options.q)
			console.log('[onLoad] 解码后 url:', url)
			const params = parseUrlParams(url)
			console.log('[onLoad] 解析参数:', JSON.stringify(params))
			const channelId = params.channel
			console.log('[onLoad] channelId:', channelId)
			if (!channelId) {
				console.log('[onLoad] channelId 为空，退出')
				return
			}
			const token = uni.getStorageSync('token')
			console.log('[onLoad] token:', token ? '有值' : '无值（未登录）')
			if (!token) return
			proxy.$api.post(`/channel/bind?channelId=${channelId}`, {}).then(({ data: res }) => {
				console.log('[onLoad] bind 结果:', JSON.stringify(res))
				if (res.code === 0) {
					uni.showToast({ title: '渠道加入成功', icon: 'success', duration: 2000 })
				} else {
					console.error('渠道绑定失败:', res.msg)
				}
			})
		}
	})
	
	const bannarList = ref([])
	const bannarOrigin = ref([])
	const current = ref(0)
	const typeList = ref([])
	const tlIndex = ref(0)
	const scrollLeft = ref(0)
	const isOver = ref(false)
	const activityList = ref([])
	const queryParams = ref({
		page:1,
		limit:10,
		categoryId:'',
		userId:''
	})
	
	const bannerClick = e => {
		let banner = bannarOrigin.value[e];
		if(banner&&banner?.redirect){
			if(banner?.redirectType==1){//微信公众号
				uni.navigateTo({
					url:'/pages/webView?src='+banner?.redirect
				})
			}else if(banner?.redirectType==2){//微信小程序
				uni.navigateToMiniProgram({
					appId:banner?.redirect
				})
			}
		}
	}
	
	const changeType = (item,index) => {
		queryParams.value.categoryId = item.id;
		tlIndex.value = index;
		// if(typeList.value.length>4){
		// 	if(index<3) scrollLeft.value = 0
		// 	else{
		// 		scrollLeft.value = (index-2)*172/2;
		// 	}
		// }
		initList();
		getActivityList();
	}
	
	const initList = () => {
		queryParams.value.page = 1;
		isOver.value = false;
		activityList.value = [];
	}
	
	const toTurnPage = (url,needLogin) => {
		if(!needLogin){
			uni.navigateTo({ url })
		}
	}
	
	const getSwiperList = () => {
		proxy.$api.get('/core/advertisement/manage/page',{page:1,limit:-1}).then(({data:res})=>{
			if(res.code!==0) return proxy.$showToast(res.msg)
			const list = res.data.list.filter(l=>l.enable==1);
			bannarOrigin.value = list;
			bannarList.value = list.map(l=>l.fileUrl);
		})
	}
	
	const getTypeList = () => {
		proxy.$api.get('/core/activity/category/list').then(({data:res})=>{
			if(res.code!==0) return proxy.$showToast(res.msg)
			typeList.value = [{id:'',name:'全部'},...res.data.map(d=>({id:d.id,name:d.categoryName}))];
		})
	}
	
	const scrolltolower = () => {
		if(isOver.value) return
		getActivityList()
	}
	
	const getActivityList = () => {
		proxy.$api.get('/core/activity/page',queryParams.value).then(({data:res})=>{
			if(res.code!==0) return proxy.$showToast(res.msg)
			activityList.value = [...activityList.value,...res.data.list];
			activityList.value.forEach(a=>{
				let cc = calculateCountdown(a?.signupEndTime);
				a.endTimeText = cc===-1?a?.signupEndTime:(`还有${cc.days}天${cc.hours}小时${cc.minutes}分钟`)
				a.signupEndTime = a.signupEndTime?new Date(a.signupEndTime).Format('yyyy.MM.dd hh:mm'):''
			})
			queryParams.value.page++;
			if(res.data.list.length===0) isOver.value = true;
		})
	}
	
	const calculateCountdown = (datetime) => {
		  if(!datetime) return -1;
		  
		  const targetDate = new Date(datetime);
		  const now = new Date();
		  const difference = targetDate.getTime() - now.getTime();
		  if (difference <= 0) return -1;
		  
		  const days = Math.floor(difference / (1000 * 60 * 60 * 24));
		  const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
		  const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
		  return {
		    days,
		    hours,
		    minutes
		  };
	}
	
	watch(()=>userStore.token,(newVal,oldVal)=>{
		if(oldVal!=newVal&&newVal){
			setTimeout(()=>{
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				});
			},200)
			nextTick(()=>{
				getActivityList()
			})
		}
	})

	onMounted(()=>{
		if(uni.getStorageSync('userInfo')){
			queryParams.value.userId = JSON.parse(uni.getStorageSync('userInfo'))?.id;
		}
		getSwiperList()
		getTypeList()
		getActivityList()
	})

	import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
	onShareAppMessage(() => {
		return {
			title: '善行少年 - 公益活动平台',
			path: '/pages/home'
		}
	})
	onShareTimeline(() => {
		return {
			title: '善行少年 - 公益活动平台',
			path: '/pages/home'
		}
	})
</script>

<style scoped lang="scss">
	::v-deep .indicator__dot{
		width: 48rpx;
		height: 4rpx;
		background: #E2E5E9;
		border-radius: 2rpx;
		margin: 0 8rpx;
	}
	::v-deep .indicator__dot--active{
		width: 48rpx;
		height: 4rpx;
		background: #00AE57;
		border-radius: 2rpx;
	}
	::v-deep .u-swiper__wrapper__item__wrapper__image{
		border-radius: 24rpx !important;
	}
	
	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}
	
	.scroll-view-item_H {
		display: inline-block;
		// width: 152rpx;
		height: 100%;
		margin-left: 20rpx;
		&:first-child{
			margin-left: 0;
		}
	}
	
	.tab_page{
		.c-box{
			width: 100%;
			height: 100%;
			overflow-y: auto;
			position: relative;
			&-lunbo{
				width: 100%;
				height: 326rpx;
				margin-top: 20rpx;
			}
			&-title{
				margin-top: 58rpx;
				&-left{
					width: 170rpx;
					height: 44rpx;
					padding-left: 2rpx;
					font-family: PingFang-SC, PingFang-SC;
					font-weight: 800;
					font-size: 36rpx;
					color: #151B29;
					line-height: 36rpx;
					background-image: url('https://oss.familydaf.cn/sxsnfile/20251218/6198fa26a7ff4fc1bce530fbdfaa20db.png');
					background-size: 170rpx 31rpx;
					background-position: 0 20rpx;
					background-repeat: no-repeat;
				}
				&-right{
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 28rpx;
					color: #676775;
					line-height: 33rpx;
				}
			}
			&-type{
				width: 100%;
				height: 68rpx;
				margin-top: 31rpx;
				.cl_item{
					// width: 152rpx;
					padding: 0 21rpx;
					height: 68rpx;
					background: #FFFFFF;
					border-radius: 34rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 28rpx;
					color: #676775;
					line-height: 68rpx;
					text-align: center;
					&.active{
						background: #B7F358;
						font-weight: bold;
						font-size: 30rpx;
						color: #151B29;
					}
				}
			}
			&-list{
				width: 100%;
				flex: 1;
				overflow-y: auto;
				margin-top: 20rpx;
			}
		}
	}
</style>