<template>
	<view class="tab_page adffc" :style="{'height':h+'px', 'padding-top':mt+'px'}">
		<up-navbar title="我的公益" bgColor="#FFFFFF">
			<template #left></template>
		</up-navbar>
		<view class="tab adf">
			<view class="tab-pre" :class="{'active':tidx===''}" @click="changeTab('')">全部</view>
			<view class="tab-pre" :class="{'active':tidx===1}" @click="changeTab(1)">未开始</view>
			<view class="tab-pre" :class="{'active':tidx===2}" @click="changeTab(2)">进行中</view>
			<view class="tab-pre" :class="{'active':tidx===3}" @click="changeTab(3)">已结束</view>
			<view class="tab-pre" :class="{'active':tidx===-1}" @click="changeTab(-1)">已取消</view>
		</view>
		<view class="list" v-if="list.length">
			<up-list @scrolltolower="scrolltolower" style="height: 100%;">
				<up-list-item v-for="(item, index) in list" :key="index">
					<NonprofitItem :item="item" @handleCancel="handleCancel"></NonprofitItem>
				</up-list-item>
			</up-list>
		</view>
		<view class="dataEmpty" v-else>
			<page-empty :text="text"></page-empty>
		</view>
		<CusTabbar :tabbarIndex="1"></CusTabbar>
	</view>
</template>

<script setup name="">
	import CusTabbar from '@/components/CusTabbar/index.vue'
	import NonprofitItem from '@/components/pages/nonprofitItem/index.vue'
	import pageEmpty from '@/components/pageEmpty/index.vue'
	import { ref, getCurrentInstance, watch } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	const { proxy } = getCurrentInstance()
	
	const tidx = ref('')
	const text = ref('暂无进行中活动')
	const queryParams = ref({
		page: 1,
		limit: 10,
		activeState: '', //''全部 0待开始 1报名中 2进行中 3已结束
		userId:''
	})
	const statusCfg = ref({
		1:'未开始',
		2:'进行中',
		3:'已结束'
	})
	const isOver = ref(false)
	const list = ref([])
	
	const changeTab = index => {
		tidx.value = index;
		queryParams.value.activeState = index;
		initList();
		getList();
	}
	
	const scrolltolower = () => {
		if(isOver.value) return
		getList();
	}
	
	const initList = () => {
		queryParams.value.page = 1;
		isOver.value = false;
		list.value = [];
	}
	
	const getList = () => {
		proxy.$api.get('/core/activity/signup/myActivityList',queryParams.value).then(({data:res})=>{
			if(res.code!==0) return proxy.$showToast(res.msg)
			list.value = [...list.value,...res.data.list];
			list.value.forEach(l=>{
				l.activityStartTime = new Date(l.activityStartTime).Format('yyyy-MM-dd')
				l.activityEndTime = new Date(l.activityEndTime).Format('yyyy-MM-dd')
				l.age = getAge(l.idCard)
			})
			queryParams.value.page++;
			if(res.data.list.length) isOver.value = true;
		})
	}
	
	const handleCancel = () => {
		initList();
		getList();
	}
	
	const isValid = (idCard) => {
		// 正则表达式校验18位身份证号码（最后一位可以是数字或X/x）
		const regex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
		return typeof idCard === 'string' && regex.test(idCard);
	  }
	
	const getAge = (idCard) => {
		if (!isValid(idCard)) return 0
	
		// 从身份证的第7位开始，截取8位作为出生日期字符串 (YYYYMMDD)
		const birthDateStr = idCard.substring(6, 14);
		const birthYear = parseInt(birthDateStr.substring(0, 4), 10);
		const birthMonth = parseInt(birthDateStr.substring(4, 6), 10);
		const birthDay = parseInt(birthDateStr.substring(6, 8), 10);
	
		const today = new Date();
		const currentYear = today.getFullYear();
		const currentMonth = today.getMonth() + 1; // getMonth() 返回 0-11
		const currentDay = today.getDate();
	
		// 计算周岁
		let age = currentYear - birthYear;
	
		// 如果当前月份小于出生月份，或者月份相同但日期小于出生日期，说明今年的生日还没过
		if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
		  age--;
		}
	
		return age < 0 ? 0 : age; 
	}
	
	watch(()=>tidx.value,(newVal)=>{
		text.value = `暂无${statusCfg.value[newVal]}活动`;
	})
	
	onShow(()=>{
		let pages = getCurrentPages();
		let options = pages[pages.length-1]?.options;
		queryParams.value.userId = uni.getStorageSync('userInfo')&&JSON.parse(uni.getStorageSync('userInfo')).id;
		if(+options?.type) tidx.value = +options.type;
		queryParams.value.activeState = tidx.value;
		initList()
		getList()
	})
</script>

<style scoped lang="scss">
	.dataEmpty{
		padding-bottom: 184rpx;
	}
	.tab_page{
		padding: 0;
		.tab{
			height: 110rpx;
			padding: 40rpx 24rpx 0;
			box-sizing: border-box;
			background: #FFFFFF;
			&-pre{
				width: calc(100% / 5);
				position: relative;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 30rpx;
				color: #676775;
				line-height: 30rpx;
				text-align: center;
				&.active{
					font-weight: bold;
					font-size: 32rpx;
					color: #151B29;
					&::after{
						content: '';
						width: 100%;
						height: 6rpx;
						background: #252525;
						position: absolute;
						left: 0;
						bottom: 0;
					}
				}
			}
		}
		.list{
			flex: 1;
			overflow-y: auto;
			padding: 0 24rpx 184rpx;
			box-sizing: border-box;
		}
	}
</style>