<template>
	<view class="tab_page" :style="{'height':h+'px', 'padding-top':mt+'px'}">
		<up-navbar title=" " bgColor="transparent">
			<template #left></template>
		</up-navbar>
		<image src="https://oss.familydaf.cn/sxsnfile/20251218/0ac9931a34bd432a8a44ef619fa51362.png" class="top_bg_img" mode="widthFix"></image>
		<view class="info">
			<view class="info-top adfacjb">
				<view class="info-top-left adfac">
					<image class="avatar" :src="userInfo?.avatarPath||'https://oss.familydaf.cn/sxsnfile/20251218/3821654e080945998d464f3c3aa64122.png'" @click="handleTurnPage('/pagesMy/information')"></image>
					<view class="text" @click.prevent="showLogin">
						<view class="text-top adfac">{{userInfo?userInfo?.realName:'未登录'}}<text class="lv-inline" v-if="userInfo&&isFamilyMember" @click.stop="handleTurnPage('/pagesMy/levelDetail')">&nbsp;Lv&nbsp;{{userInfo?.userLevel||0}}&nbsp;</text></view>
						<view class="text-bottom no adfac" v-if="userInfo&&!isFamilyMember">编号：{{userInfo?.uniqueNo||''}}</view>
						<view class="text-bottom no adfac" v-if="numInfo?.channelNames">所属渠道：<text>{{numInfo?.channelNames}}</text></view>
						<view class="text-bottom" v-if="!userInfo">去登录注册&nbsp;>></view>
					</view>
				</view>
				<div class="info-top-change adfac" v-if="userInfo" @click="handleChangeUser">
					<image src="https://oss.familydaf.cn/sxsnfile/20260105/7242f7d209f646a29e5570fa73da352d.png"></image>
					<text>切换用户</text>
				</div>
			</view>
			<view class="info-tip">
				<view class="info-tip-pre adfacjb" @click="handleTurnPage('/pagesMy/information')">
					<view class="left">{{isFamilyMember?'个人':'家庭'}}公益名称：<text v-if="userInfo">{{userInfo?.welfareName||''}}</text><text style="color: #657588;" v-else>暂无，快去填写吧~</text></view>
					<view class="right">
						<image src="https://oss.familydaf.cn/sxsnfile/20251218/938f573288ad401fbd1e57404a870059.png"></image>
					</view>
				</view>
				<view class="info-tip-pre adfacjb" @click="handleTurnPage('/pagesMy/information')">
					<view class="left">{{isFamilyMember?'个人':'家庭'}}公益口号：<text v-if="userInfo">{{userInfo?.welfareSlogan||''}}</text><text style="color: #657588;" v-else>暂无，快去填写吧~</text></view>
					<view class="right">
						<image src="https://oss.familydaf.cn/sxsnfile/20251218/938f573288ad401fbd1e57404a870059.png"></image>
					</view>
				</view>
<!-- 				<view class="info-tip-pre adfacjb" v-if="isFamilyMember&&numInfo?.channelNames">
					<view class="left">所属渠道：<text>{{numInfo?.channelNames}}</text></view>
				</view> -->
			</view>
		</view>
		<view class="box" style="margin-top: 40rpx;">
			<view class="box-title">公益记录</view>
			<view class="box-card adfacjb">
				<view class="box-card-pre adffcac red" @click="handleTurnPage('/pagesMy/heartNumber?loveValue='+(isFamilyMember?(numInfo?.loveValueBalance??0):numInfo?.loveValue))">
					<image class="top" src="https://oss.familydaf.cn/sxsnfile/20251218/046c057625704329a478d535cd1b4364.png"></image>
					<view class="num">{{isFamilyMember?(numInfo?.loveValueBalance||0):(numInfo?.loveValue||0)}}</view>
					<view class="text adf">
						<text>{{isFamilyMember?'爱心值余额':'我的爱心值'}}</text>
						<image src="https://oss.familydaf.cn/sxsnfile/20251218/2e8332c5f36a45cab3af336aa324d20c.png"></image>
					</view>
				</view>
				<view class="box-card-pre adffcac purple" @click="handleTurnPage('/pagesMy/archives')">
					<image class="top" src="https://oss.familydaf.cn/sxsnfile/20251218/ee5fffc2b10647ef9492150aed6bb29d.png"></image>
					<view class="num">{{numInfo?.myArchives||0}}</view>
					<view class="text adf">
						<text>我的档案</text>
						<image src="https://oss.familydaf.cn/sxsnfile/20251218/6e9e879da03944a4911b48550e915641.png"></image>
					</view>
				</view>
				<view class="box-card-pre adffcac orange" @click="handleTurnPage('/pagesMy/volunteerHours?volunteerHours='+numInfo?.volunteerHours)">
					<image class="top" src="https://oss.familydaf.cn/sxsnfile/20251218/3fdb7e3c0d3c444ab03dd5f51a5e3fe0.png"></image>
					<view class="num">{{(numInfo?.volunteerHours||0).toFixed(2)}}</view>
					<view class="text adf">
						<text>义工时长(h)</text>
						<image src="https://oss.familydaf.cn/sxsnfile/20251218/625a9a7d454c4e7985bd7e12a9f1af93.png"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="box" @click="handleTurnPage('/pagesMy/achievement')" v-if="isFamilyMember">
			<view class="box-title">我的成就</view>
			<view class="box-achievement adfacjb">
				<view class="box-achievement-left">收获<span>{{numInfo?.myMedals||0}}</span>项成就</view>
				<view class="box-achievement-right adfacjb">
					<view class="imgs"></view>
					<view class="jt">
						<image src="https://oss.familydaf.cn/sxsnfile/20251218/938f573288ad401fbd1e57404a870059.png"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="box">
			<view class="box-title">其他功能</view>
			<view class="box-other adfacjb">
				<view class="box-other-pre adffcac" @click="handleTurnPage('/pagesMy/practice')">
					<image src="https://oss.familydaf.cn/sxsnfile/20251218/f6d2c342d9414909b4626e34909917c7.png"></image>
					<text>申领社会实践记录</text>
				</view>
				<view class="box-other-pre adffcac" @click="handleTurnPage('/pagesMy/familyMember')">
					<image src="https://oss.familydaf.cn/sxsnfile/20251218/248ed751f8bf4821b29cd236ec2dc78b.png"></image>
					<text>家庭成员</text>
				</view>
				<view class="box-other-pre adffcac" @click="handleTurnPage('/pagesMy/exclusiveScroll')" v-if="!isFamilyMember">
					<image src="https://oss.familydaf.cn/sxsnfile/20251218/7ee3c42e8408489fb0768406d72b73b4.png"></image>
					<text>我的专享券</text>
				</view>
				<view class="box-other-pre adffcac" @click="handleBackUser" v-else>
					<image src="https://oss.familydaf.cn/sxsnfile/20260105/5b8a24ffd1e34486a6aa5d88260677d0.png"></image>
					<text>返回家庭页</text>
				</view>
			</view>
		</view>
		<div class="dialog adffc" v-if="changeShow">
			<div class="change adffc">
				<div class="change-top adfacjc">
					<text>切换用户</text>
					<image src="https://oss.familydaf.cn/sxsnfile/20260105/2ffe44b1abef403788b21aca09f6a8c3.png" @click="changeShow=false"></image>
				</div>
				<div class="change-list">
					<div class="change-list-item adfacjb" v-for="(item,index) in familyMemberList" :key="item.id" @click="selectFamilyMember(index)">
						<div class="change-list-item-left">
							<view class="change-list-item-left-top adfac">
								<view class="name">{{item.name||''}}</view>
								<image class="sex" v-if="item.gender==1" src="https://oss.familydaf.cn/sxsnfile/20251218/473d5677fbdb4106acdb9a163377d27f.png"></image>
								<image class="sex" v-else-if="item.gender==0" src="https://oss.familydaf.cn/sxsnfile/20251218/02bc40a1c47b40f1a36b55cd0553211c.png"></image>
								<view class="age" :class="{'women':item.gender==1,'man':item.gender==0}">{{item.age}}岁</view>
							</view>
							<view class="change-list-item-left-bottom">
								身份证 {{item.idCardCopy}}
							</view>
						</div>
						<div class="change-list-item-right">
							<image v-if="item.select" src="https://oss.familydaf.cn/sxsnfile/20251218/c11b9a1b56f34e1189621f4270f0349a.png"></image>
							<image v-else src="https://oss.familydaf.cn/sxsnfile/20251218/2a2f7bdefb474a3e93faa00aef6d0e1f.png"></image>
						</div>
					</div>
				</div>
				<div class="change-btn" @click="changeUserConfirm">确定</div>
			</div>
		</div>
		<CusTabbar :tabbarIndex="2"></CusTabbar>
		<login-register></login-register>
	</view>
</template>

<script setup name="">
	import CusTabbar from '@/components/CusTabbar/index.vue'
	import { ref, onMounted, watch, nextTick, getCurrentInstance } from 'vue'
	const { proxy } = getCurrentInstance();
	import { useUserStore } from '@/common/stores/user';
	const userStore = useUserStore();
	import { useGlobalShare } from '@/common/composables/useGlobalShare';
	const { isLogin } = useGlobalShare();
	
	const userInfo = ref(null)
	const numInfo = ref(null)
	const isFamilyMember = ref(false)
	const changeShow = ref(false)
	const familyMemberList = ref([])
	const familyMemberInfo = ref(null)
	const memberId = ref('')
	
	const showLogin = () => {
		if(!isLogin()) return
		handleTurnPage('/pagesMy/information')
	}
	
	const handleChangeUser = () => {
		changeShow.value = true;
		getMemberList();
	}
	
	const getMemberList = () => {
		const userId = uni.getStorageSync('userInfo')?JSON.parse(uni.getStorageSync('userInfo'))?.id:'';
		proxy.$api.get('/core/family/member/page',{page:1,limit:-1,userId}).then(({data:res})=>{
			if(res.code!==0) return proxy.$showToast(res.msg)
			familyMemberList.value = res.data.list;
			familyMemberList.value.forEach(l=>{
				l.select = false;
				l.age = getAge(l.idCard)
				l.idCardCopy = l.idCard.replace(/^(\d{6})(\d{8})(\d{3}[\dX])$/i,'$1********$3')
			})
		})
	}
	
	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; 
	}
	
	const selectFamilyMember = index => {
		familyMemberList.value.forEach((f,i)=>{
			familyMemberList.value[i].select = index===i;
		})
	}
	
	const handleBackUser = () => {
		memberId.value = '';
		familyMemberInfo.value = null;
		isFamilyMember.value = false;
		uni.removeStorageSync('isFamilyMember');
		uni.removeStorageSync('familyMemberInfo');
	}
	
	const changeUserConfirm = () => {
		const selectedUser = familyMemberList.value.find(f=>f.select)
		if(!selectedUser) return proxy.$showToast('请选择要切换的用户')
		memberId.value = selectedUser?.id||'';
		familyMemberInfo.value = selectedUser;
		isFamilyMember.value = true;
		userInfo.value = {...deepClone(userInfo.value),...deepClone(selectedUser)};
		uni.setStorageSync('isFamilyMember',true);
		uni.setStorageSync('familyMemberInfo',JSON.stringify(familyMemberInfo.value));
		changeShow.value = false;
	}
	
	const handleTurnPage = (url) => {
		if(!isLogin()) return
		if(url == '/pagesMy/information'){
			if(isFamilyMember.value){
				uni.navigateTo({
					url:'/pagesMy/familyMemberVindicate?id='+(JSON.parse(uni.getStorageSync('familyMemberInfo'))?.id||'')+'&type=my'
				})
				return
			}
		}
		if(url == '/pagesMy/achievement'){
			url = `/pagesMy/achievement?numInfo=`+JSON.stringify(numInfo.value)+`&userLevel=`+userInfo.value?.userLevel
		}
		uni.navigateTo({ url })
	}
	
	const deepClone = (obj) => {
		  if (obj === null || typeof obj !== 'object') {
			return obj;
		  }
		  
		  if (Array.isArray(obj)) {
			return obj.map(item => deepClone(item));
		  }
		  
		  const clonedObj = {};
		  
		  for (const key in obj) {
			clonedObj[key] = deepClone(obj[key]);
		  }
		  
		  return clonedObj;
	}
	
	const getUserInfo = () => {
		try{
			let mid = deepClone(memberId.value);
			if(uni.getStorageSync('isFamilyMember')) mid = uni.getStorageSync('familyMemberInfo')?JSON.parse(uni.getStorageSync('familyMemberInfo')).id:'';
			proxy.$api.get(`/wx/userWelfareData`,{memberId:mid}).then(({data:res})=>{
				if(res.code!==0) return proxy.$showToast(res.msg)
				userInfo.value = res.data;
				numInfo.value = res.data;
				if(uni.getStorageSync('isFamilyMember')){
					uni.setStorageSync('isFamilyMember',JSON.stringify(res.data));
				}else {
					uni.setStorageSync('userInfo',JSON.stringify({...JSON.parse(uni.getStorageSync('userInfo')),...res.data}));
				}
			})
		}catch(e){
			userInfo.value = null
			numInfo.value = null
		}
	}
	
	watch(()=>userStore.token,(newVal,oldVal)=>{
		if(oldVal!=newVal&&newVal){
			setTimeout(()=>{
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				});
			},200)
			nextTick(()=>{
				getUserInfo()
			})
		}
	})
	
	watch(()=>memberId.value,(newVal,oldVal)=>{
		if(oldVal!=newVal){
			nextTick(()=>{
				getUserInfo()
			})
		}
	})
	
	onMounted(()=>{
		isFamilyMember.value = uni.getStorageSync('isFamilyMember')?true:false;
		if(uni.getStorageSync('familyMemberInfo')) memberId.value = JSON.parse(uni.getStorageSync('familyMemberInfo')).id;
		if(uni.getStorageSync('userInfo')){
			getUserInfo()
		}
	})
</script>

<style scoped lang="scss">
	.dialog{
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background: rgba(0, 0, 0, .4);
		z-index: 1001;
		justify-content: flex-end;
		.change{
			width: 100%;
			height: 920rpx;
			background: #FFFFFF;
			border-radius: 24rpx 24rpx 0rpx 0rpx;
			padding: 48rpx 30rpx 64rpx;
			box-sizing: border-box;
			&-top{
				position: relative;
				text{
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 36rpx;
					color: #151B29;
					line-height: 36rpx;
				}
				image{
					width: 36rpx;
					height: 36rpx;
					position: absolute;
					right: 0;
				}
			}
			&-list{
				flex: 1;
				margin-top: 48rpx;
				overflow-y: auto;
				&-item{
					box-shadow: inset 0rpx -1rpx 0rpx 0rpx #E5E7EB;
					width: 100%;
					padding: 36rpx 0;
					&-left{
						&-top{
							.name{
								font-family: PingFang-SC, PingFang-SC;
								font-weight: bold;
								font-size: 32rpx;
								color: #151B29;
								line-height: 32rpx;
							}
							.sex{
								width: 44rpx;
								height: 32rpx;
								margin-left: 16rpx;
							}
							.age{
								border-radius: 13rpx;
								font-family: PingFangSC, PingFang SC;
								font-weight: 400;
								font-size: 20rpx;
								line-height: 24rpx;
								padding: 4rpx 10rpx;
								margin-left: 13rpx;
								&.women{
									background: rgba(244,101,122,0.14);
									color: #F4657A;
								}
								&.man{
									background: rgba(5,169,254,0.12);
									color: #05A9FE;
								}
							}
						}
						&-bottom{
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							font-size: 24rpx;
							color: #989998;
							line-height: 24rpx;
							margin-top: 23rpx;
						}
					}
					&-right{
						image{
							width: 36rpx;
							height: 36rpx;
						}
					}
				}
			}
			&-btn{
				width: 100%;
				height: 90rpx;
				background: #B7F358;
				border-radius: 45rpx;
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 32rpx;
				color: #151B29;
				line-height: 90rpx;
				text-align: center;
				letter-spacing: 2rpx;
				margin-top: 20rpx;
				
			}
		}
	}
	
	.tab_page{
		.info{
			margin-top: 40rpx;
			position: relative;
			padding: 0 24rpx 0 16rpx;
			&-top{
				position: relative;
				&-left{
					.avatar{
						width: 148rpx;
						height: 148rpx;
						border-radius: 50%;
					}
					.text{
						margin-left: 24rpx;
						&-top{
							font-family: PingFang-SC, PingFang-SC;
							font-weight: bold;
							font-size: 40rpx;
							color: #151B29;
							line-height: 40rpx;
							.lv-inline{
								display: inline-block;
								width: 137rpx;
								height: 42rpx;
								background: url('https://oss.familydaf.cn/sxsnfile/20251218/b6e6f5b45ad34f91bbaf66c9890fc2cd.png') no-repeat;
								background-size: 100% 100%;
								font-family: PingFangSC, PingFang SC;
								font-weight: 600;
								font-size: 26rpx;
								color: #FFFFFF;
								line-height: 42rpx;
								padding-left: 16rpx;
								box-sizing: border-box;
								vertical-align: middle;
							}
						}
						&-bottom{
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							font-size: 26rpx;
							color: #151B29;
							line-height: 26rpx;
							margin-top: 26rpx;
							&.lv{
								width: 137rpx;
								height: 42rpx;
								background: url('https://oss.familydaf.cn/sxsnfile/20251218/b6e6f5b45ad34f91bbaf66c9890fc2cd.png') no-repeat;
								background-size: 100% 100%;
								font-family: PingFangSC, PingFang SC;
								font-weight: 600;
								font-size: 26rpx;
								color: #FFFFFF;
								line-height: 38rpx;
								padding-left: 16rpx;
								box-sizing: border-box;
								margin-top: 18rpx;
							}
							&.no{
								font-family: PingFangSC, PingFang SC;
								font-weight: 400;
								font-size: 26rpx;
								color: #657588;
								line-height: 26rpx;
							}
						}
					}
				}
				&-right{
					image{
						width: 48rpx;
						height: 48rpx;
					}
				}
				&-change{
					padding: 0 20rpx 0 16rpx;
					height: 60rpx;
					background: #B7F358;
					border-radius: 30rpx 0rpx 0rpx 30rpx;
					position: absolute;
					top: 24rpx;
					right: -48rpx;
					image{
						width: 32rpx;
						height: 32rpx;
					}
					text{
						font-family: PingFang-SC, PingFang-SC;
						font-weight: bold;
						font-size: 24rpx;
						color: #151B29;
						line-height: 30rpx;
						margin-left: 8rpx;
					}
				}
			}
			&-tip{
				margin-top: 4rpx;
				&-pre{
					margin-top: 36rpx;
					.left{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #252525;
						line-height: 28rpx;
					}
					.right{
						image{
							width: 32rpx;
							height: 32rpx;
						}
					}
				}
			}
		}
		.box{
			background: #FFFFFF;
			border-radius: 24rpx;
			padding: 40rpx 24rpx 36rpx;
			margin-top: 20rpx;
			position: relative;
			&-title{
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 36rpx;
				color: #151B29;
				line-height: 40rpx;
			}
			&-card{
				margin-top: 72rpx;
				&-pre{
					width: calc(100% / 3 - 8rpx);
					height: 200rpx;
					position: relative;
					background-size: 100% 100%;
					background-repeat: no-repeat;
					.top{
						width: 82rpx;
						height: 82rpx;
						position: absolute;
						left: 50%;
						margin-left: -41rpx;
						top: -32rpx;
					}
					.num{
						font-family: DINAlternate, DINAlternate;
						font-weight: bold;
						font-size: 40rpx;
						line-height: 40rpx;
						text-align: center;
						margin-top: 86rpx;
					}
					.text{
						margin-top: 20rpx;
						text{
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							font-size: 24rpx;
							line-height: 24rpx;
						}
						image{
							width: 26rpx;
							height: 26rpx;
							margin-left: 6rpx;
						}
					}
					&.red{
						background-image: url('https://oss.familydaf.cn/sxsnfile/20251218/57acefa1a0084d1e980002e165668bc9.png');
						.num,.text text{
							color: #FC5768;
						}
					}
					&.purple{
						background-image: url('https://oss.familydaf.cn/sxsnfile/20251218/e0f97b6ca8864d2ca0c3dc48b07dae58.png');
						.num,.text text{
							color: #8360E8;
						}
					}
					&.orange{
						background-image: url('https://oss.familydaf.cn/sxsnfile/20251218/eabb899f7ab14010b61fb30ed24bd818.png');
						.num,.text text{
							color: #FF8200;
						}
					}
				}
			}
			&-achievement{
				margin-top: 24rpx;
				&-left{
					width: 210rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #676775;
					line-height: 24rpx;
					label{
						font-weight: bold;
						font-size: 32rpx;
						color: #EA3044;
						line-height: 32rpx;
						margin: 0 7rpx;
					}
				}
				&-right{
					width: calc(100% - 210rpx);
					.jt{
						image{
							width: 32rpx;
							height: 32rpx;
						}
					}
				}
			}
			&-other{
				margin-top: 39rpx;
				&-pre{
					width: calc(100% / 3);
					image{
						width: 48rpx;
						height: 48rpx;
					}
					text{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #151B29;
						line-height: 33rpx;
						text-align: center;
						margin-top: 16rpx;
					}
				}
			}
		}
	}
</style>