<template>
	<view class="login-register" v-if="userStore.showLoginModal">
		<!-- 注册步骤1：用户信息 -->
		<view class="lr-box" v-if="!userStore.isRegister && userStore.registerStep === 1">
			<image src="https://oss.familydaf.cn/sxsnfile/20251218/8814a4934a77448086318c3bba9e9286.png" class="lr-box-topbg" mode="widthFix"></image>
			<view class="lr-box-top adfacjb">
				<image class="lr-box-top-left" src="https://oss.familydaf.cn/sxsnfile/20251218/0868874c940144e5b3e79dba08a9d9ff.png"></image>
				<image class="lr-box-top-right" src="https://oss.familydaf.cn/sxsnfile/20251218/ec7dbd753ab044e18abc0eedf3540fad.png" @click="close"></image>
			</view>
			<view class="lr-box-title">
				<p class="p">欢迎来到善行少年</p>
				<p class="p tip">首次登录需要简单填写信息即可进入</p>
			</view>
			<view class="lr-box-form">
				<view class="lr-box-form-item adfacjb">
					<view class="lr-box-form-item-left adfac">
						<view class="text"><span style="color: #F4657A;">*</span>手机号码</view>
						<input v-model="register.phone" border="none" placeholder="请输入手机号码" style="margin-left: 32rpx; flex: 1;"></input>
					</view>
					<view class="lr-box-form-item-right">
						<button class="yjsq" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber" privacy-desc="用于获取您的手机号码，方便您快速注册。">一键授权</button>
					</view>
				</view>
				<view class="lr-box-form-item adfacjb">
					<view class="lr-box-form-item-left adfac">
						<view class="text"><span style="color: #F4657A;">*</span>头像</view>
						<up-upload
							:fileList="fileList"
							@afterRead="afterRead"
							@delete="deletePic"
							:maxCount="1"
							width="120rpx"
							height="120rpx"
						>
							<image src="https://oss.familydaf.cn/sxsnfile/20251218/d43706a3b02a439b8c9981db87912c1f.png"
							mode="widthFix" style="width: 120rpx;height: 120rpx;"></image>
						</up-upload>
					</view>
					<view class="lr-box-form-item-right">
						<button class="yjsq" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">设置</button>
					</view>
				</view>
				<view class="lr-box-form-item adfacjb">
					<view class="lr-box-form-item-left">
						<view class="text"><span style="color: #F4657A;">*</span>用户名</view>
					</view>
					<view class="lr-box-form-item-right">
						<input v-model="register.nickName" border="none" inputAlign="right" placeholder="请输入真实姓名"></input>
					</view>
				</view>
				<view class="lr-box-form-item adfacjb">
					<view class="lr-box-form-item-left">
						<view class="text">家庭公益名称</view>
					</view>
					<view class="lr-box-form-item-right">
						<input v-model="register.welfareName" border="none" inputAlign="right" placeholder="请输入至少三个字"></input>
					</view>
				</view>
				<view class="lr-box-form-item adfacjb">
					<view class="lr-box-form-item-left">
						<view class="text">家庭公益口号</view>
					</view>
					<view class="lr-box-form-item-right">
						<input v-model="register.welfareSlogan" border="none" inputAlign="right" placeholder="家庭公益口号"></input>
					</view>
				</view>
			</view>
			<view class="lr-box-btns">
				<view class="btn" @click="toNextStep">下一步</view>
			</view>
		</view>

		<!-- 注册步骤2：添加孩子信息 -->
		<view class="lr-box step2" v-else-if="!userStore.isRegister && userStore.registerStep === 2">
			<image src="https://oss.familydaf.cn/sxsnfile/20251218/8814a4934a77448086318c3bba9e9286.png" class="lr-box-topbg" mode="widthFix"></image>
			<view class="lr-box-top adfacjb">
				<image class="lr-box-top-left" src="https://oss.familydaf.cn/sxsnfile/20251218/0868874c940144e5b3e79dba08a9d9ff.png"></image>
				<image class="lr-box-top-right" src="https://oss.familydaf.cn/sxsnfile/20251218/ec7dbd753ab044e18abc0eedf3540fad.png" @click="close"></image>
			</view>
			<view class="lr-box-title">
				<p class="p">添加孩子信息</p>
				<p class="p tip">请填写孩子的基本信息完成注册</p>
			</view>
			<scroll-view scroll-y class="lr-box-scroll">
				<view class="member-form">
					<view class="member-avatar">
						<view class="member-avatar-title"><span>*</span>头像</view>
						<view class="adfac" style="margin: 24rpx 0 32rpx;">
							<view class="member-avatar-imgbox" @click="changeMemberAvatar">
								<image class="member-avatar-imgbox-img" :src="memberInfo.avatarPath||defaultAvatar"></image>
							</view>
							<image class="member-avatar-add" src="https://oss.familydaf.cn/sxsnfile/20251219/0b4d0f26464945dbae17491f1b529229.png" @click="changeMemberAvatar"></image>
						</view>
					</view>
					<view class="member-item adfacjb">
						<view class="member-item-left">个人公益名称</view>
						<view class="member-item-right">
							<input v-model="memberInfo.welfareName" placeholder-style="color: #A1A4A9;font-size: 28rpx;" placeholder="请输入最少三个字"></input>
						</view>
					</view>
					<view class="member-item adfacjb">
						<view class="member-item-left">个人公益口号</view>
						<view class="member-item-right">
							<input v-model="memberInfo.welfareSlogan" placeholder-style="color: #A1A4A9;font-size: 28rpx;" placeholder="请输入个人公益口号"></input>
						</view>
					</view>
					<view class="member-section-title">成员信息</view>
					<view class="member-pre adfac">
						<view class="member-pre-title"><span>*</span>人员类型</view>
						<view class="member-pre-content adfac">
							<view class="member-pre-content-box adfac" @click="memberInfo.personnelType=1">
								<image v-if="memberInfo.personnelType==1" src="https://oss.familydaf.cn/sxsnfile/20251218/ef2d43944c7e4cea8c6ebe0b4179f0fc.png"></image>
								<image v-else src="https://oss.familydaf.cn/sxsnfile/20251218/a27c9b23939d4d5085ff790ed4bd2d6a.png"></image>
								<text>成人</text>
							</view>
							<view class="member-pre-content-box adfac" @click="memberInfo.personnelType=2">
								<image v-if="memberInfo.personnelType==2" src="https://oss.familydaf.cn/sxsnfile/20251218/ef2d43944c7e4cea8c6ebe0b4179f0fc.png"></image>
								<image v-else src="https://oss.familydaf.cn/sxsnfile/20251218/a27c9b23939d4d5085ff790ed4bd2d6a.png"></image>
								<text>学生</text>
							</view>
						</view>
					</view>
					<view class="member-pre adfac">
						<view class="member-pre-title"><span>*</span>姓名</view>
						<view class="member-pre-content">
							<input v-model="memberInfo.name" style="font-size: 30rpx;color: #252525;text-align: right;" placeholder-style="color: #A1A4A9;font-size: 28rpx;" placeholder="请输入姓名"></input>
						</view>
					</view>
					<view class="member-pre adfac">
						<view class="member-pre-title"><span>*</span>身份证</view>
						<view class="member-pre-content">
							<input v-model="memberInfo.idCard" style="font-size: 30rpx;color: #252525;text-align: right;" placeholder-style="color: #A1A4A9;font-size: 28rpx;" placeholder="请输入身份证"></input>
						</view>
					</view>
					<view class="member-pre adfac">
						<view class="member-pre-title"><span style="color: #FFFFFF;">*</span>义工号</view>
						<view class="member-pre-content">
							<input v-model="memberInfo.volunteerNo" style="font-size: 30rpx;color: #252525;text-align: right;" placeholder-style="color: #A1A4A9;font-size: 28rpx;" placeholder="请输入义工号"></input>
						</view>
					</view>
					<view class="member-pre adfac">
						<view class="member-pre-title"><span>*</span>性别</view>
						<view class="member-pre-content adfac">
							<view class="member-pre-content-box adfac" @click="memberInfo.gender=0">
								<image v-if="memberInfo.gender==0" src="https://oss.familydaf.cn/sxsnfile/20251218/ef2d43944c7e4cea8c6ebe0b4179f0fc.png"></image>
								<image v-else src="https://oss.familydaf.cn/sxsnfile/20251218/a27c9b23939d4d5085ff790ed4bd2d6a.png"></image>
								<text>男</text>
							</view>
							<view class="member-pre-content-box adfac" style="margin-left: 114rpx;" @click="memberInfo.gender=1">
								<image v-if="memberInfo.gender==1" src="https://oss.familydaf.cn/sxsnfile/20251218/ef2d43944c7e4cea8c6ebe0b4179f0fc.png"></image>
								<image v-else src="https://oss.familydaf.cn/sxsnfile/20251218/a27c9b23939d4d5085ff790ed4bd2d6a.png"></image>
								<text>女</text>
							</view>
						</view>
					</view>
					<view class="member-pre adfac" v-if="memberInfo.personnelType==2">
						<view class="member-pre-title"><span>*</span>就读学校</view>
						<view class="member-pre-content">
							<input v-model="memberInfo.currentSchool" style="font-size: 30rpx;color: #252525;text-align: right;" placeholder-style="color: #A1A4A9;font-size: 28rpx;" placeholder="请输入就读学校"></input>
						</view>
					</view>
					<view class="member-pre adfac">
						<view class="member-pre-title">会员渠道</view>
						<view class="member-pre-content">
							<picker v-if="channelList.length > 0" :range="channelList" range-key="channelName" :value="selectedChannelIndex" @change="onChannelChange">
								<view style="font-size: 30rpx;color: #252525;text-align: right;">
									{{ selectedChannelIndex >= 0 ? channelList[selectedChannelIndex].channelName : '请选择渠道' }}
								</view>
							</picker>
							<view v-else style="font-size: 30rpx;color: #A1A4A9;text-align: right;">暂无可用渠道</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="lr-box-btns">
				<view class="btn" @click="toAddChild">完成注册</view>
			</view>
		</view>

		<!-- 登录面板 -->
		<view class="lr-box login" v-else-if="userStore.isRegister">
			<image src="https://oss.familydaf.cn/sxsnfile/20251218/8814a4934a77448086318c3bba9e9286.png" class="lr-box-topbg" mode="widthFix"></image>
			<view class="lr-box-top login adfacjb">
				<image class="lr-box-top-left login" src="https://oss.familydaf.cn/sxsnfile/20251218/78c8c9fba0eb45d2ad8ed365c96988ee.png"></image>
				<image class="lr-box-top-right" src="https://oss.familydaf.cn/sxsnfile/20251218/ec7dbd753ab044e18abc0eedf3540fad.png" @click="close"></image>
			</view>
			<view class="lr-box-memo">公益献爱心 真情暖人心！</view>
			<view class="lr-box-login">
				<button class="phone-login" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumberLogin" privacy-desc="用于获取您的手机号码，方便您进行登录。">手机号登录</button>
			</view>
		</view>

		<qf-image-cropper :width="500" :height="500" :radius="30" @crop="handleMemberCrop" ref="qicRef" v-if="qicShow"></qf-image-cropper>
	</view>
</template>

<script setup name="">
	import { ref, getCurrentInstance, nextTick } from 'vue'
	import { BaseApi2 } from '@/common/api/baseApi.js'
	const { proxy } = getCurrentInstance()
	import { useUserStore } from '@/common/stores/user.js';
	const userStore = useUserStore();

	const register = ref({
		phone:null,
		avatarPath:null,
		nickName:null,
		welfareName:null,
		welfareSlogan:null,
	})
	const fileList = ref([])

	// 孩子信息
	const defaultAvatar = ref('https://oss.familydaf.cn/sxsnfile/20251218/3821654e080945998d464f3c3aa64122.png')
	const memberInfo = ref({
		userId:'',
		personnelType: 2,
		name:'',
		idCard:'',
		volunteerNo:'',
		gender: 0,
		currentSchool:'',
		avatarPath:'',
		welfareName:'',
		welfareSlogan:''
	})
	const channelList = ref([])
	const selectedChannelId = ref('')
	const selectedChannelIndex = ref(-1)
	const hasSelectedChannel = ref(false)
	const qicShow = ref(false)

	const close = () => {
		userStore.closeLoginModal();
	}

	const decryptPhoneNumber = e => {
		if(e.detail.code) getPhone(e.detail.code);
	}

	const onChooseAvatar = e => {
		register.value.avatarPath = e.detail.avatarUrl;
		// 更新 fileList 以显示头像
		fileList.value = [{
			url: e.detail.avatarUrl,
			status: 'success'
		}];
	}

	const getPhone = code => {
		proxy.$api.get(`/wx/getPhone/${code}`).then(({data:res})=>{
			if(res.code !== 0) return proxy.$showToast(res.msg)
			register.value.phone = res.data;
		})
	}

	// 第一步：用户信息校验并注册，成功后进入第二步
	const toNextStep = async () => {
		if(!proxy.$reg.mobile(register.value.phone)) return proxy.$showToast('请输入正确的手机号码')
		if(!register.value.avatarPath) return proxy.$showToast('请设置头像')
		if(!register.value.nickName) return proxy.$showToast('请输入真实姓名')

		const success = await userStore.register(register.value);
		if(success) {
			loadChannelList()
		}
	}

	// 第二步：添加孩子信息
	const toAddChild = async () => {
		if(!memberInfo.value.avatarPath) return proxy.$showToast('请上传头像')
		if(memberInfo.value.welfareName && memberInfo.value.welfareName.length < 3) return proxy.$showToast('个人公益名称至少三个字')
		if(!memberInfo.value.name) return proxy.$showToast('请输入姓名')
		if(!proxy.$reg.idCard(memberInfo.value.idCard)) return proxy.$showToast('请输入正确的身份证号')
		if(!memberInfo.value.currentSchool && memberInfo.value.personnelType == 2) return proxy.$showToast('请输入就读学校')

		// 内容安全检测
		const checkMsgs = ['welfareName','welfareSlogan','name']
			.filter(k => memberInfo.value[k])
			.map(k => checkMsg(k));
		if(checkMsgs.length) {
			const tipRes = (await Promise.all(checkMsgs)).filter(item => item !== 'ok');
			if(tipRes && tipRes.length) return proxy.$showModal(tipRes.join('、'))
		}

		// 设置userId
		const userInfo = JSON.parse(uni.getStorageSync('userInfo'))
		memberInfo.value.userId = userInfo.id

		proxy.$api.post('/core/family/member', memberInfo.value).then(({data:res}) => {
			if(res.code !== 0) return proxy.$showToast(res.msg)
			const memberId = res.data?.id
			if(memberId && hasSelectedChannel.value) {
				setMemberChannel(memberId)
			}
			userStore.completeRegister()
		})
	}

	const checkMsg = async (key) => {
		const msgAlert = {
			welfareName:'个人公益名称',
			welfareSlogan:'个人公益口号',
			name:'姓名'
		}
		return new Promise((resolve) => {
			proxy.$api.detectionContent(memberInfo.value[key]).then(res => {
				resolve(res.code !== 0 ? (`${msgAlert[key]}：` + res.msg) : 'ok')
			})
		})
	}

	// 渠道相关
	const loadChannelList = () => {
		proxy.$api.get('/channel/list', {}).then(({ data: res }) => {
			if (res.code !== 0) return
			channelList.value = res.data || []
		})
	}

	const onChannelChange = (e) => {
		const idx = e.detail.value
		selectedChannelIndex.value = idx
		selectedChannelId.value = String(channelList.value[idx].id)
		hasSelectedChannel.value = true
	}

	const setMemberChannel = (memberId) => {
		proxy.$api.post(`/member/setChannels?memberId=${memberId}&channelIds=${selectedChannelId.value}`, {}).catch(() => {})
	}

	// 孩子头像选择
	const changeMemberAvatar = () => {
		uni.showActionSheet({
			itemList: ['从手机相册选择'],
			success: (res) => {
				if (res.tapIndex === 0) {
					uni.chooseImage({
						count: 1,
						sizeType: ['compressed'],
						sourceType: ['album', 'camera'],
						success: (imgRes) => {
							const tempFilePaths = imgRes.tempFilePaths;
							if (tempFilePaths && tempFilePaths.length > 0) {
								proxy.$api.detectionContent(tempFilePaths[0], 2).then(res => {
									if(res.code !== 0) return proxy.$showToast(res.msg)
									qicShow.value = true;
									nextTick(() => {
										proxy.$refs.qicRef.initImage(tempFilePaths[0], true)
									})
								})
							}
						}
					});
				}
			}
		});
	}

	const handleMemberCrop = async (e) => {
		const result = await uploadFilePromise(e.tempFilePath);
		memberInfo.value.avatarPath = result || '';
		qicShow.value = false;
	}

	const uploadFilePromise = (url) => {
		return new Promise((resolve) => {
			uni.uploadFile({
				url: BaseApi2 + '/sys/oss/upload',
				filePath: url,
				name: 'file',
				success: (res) => {
					setTimeout(() => {
						let data = JSON.parse(res.data)
						if(data && data.code === 0){
							resolve(data.data);
						} else {
							proxy.$showToast(data?.msg)
							resolve('')
						}
					}, 1000);
				},
				fail: () => { resolve(''); }
			});
		});
	};

	const afterRead = e => {}
	const deletePic = event => {
		fileList.value.splice(event.index, 1);
		register.value.avatarPath = '';
	}

	// 登录
	const decryptPhoneNumberLogin = e => {
		if(e.detail.code) toPhoneLogin(e.detail.code);
	}

	const toPhoneLogin = code => {
		wx.login({
			success(res){
				userStore.login({code:res.code,phoneCode:code});
			}
		})
	}
</script>

<style scoped lang="scss">
	.login-register{
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, .4);
		z-index: 9999;
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
		.lr-box{
			background: #F7F7F7;
			border-radius: 24rpx 24rpx 0rpx 0rpx;
			padding: 58rpx 30rpx 68rpx;
			position: relative;
			&.login{
				padding: 32rpx 40rpx 128rpx;
			}
			&.step2{
				padding: 58rpx 30rpx 68rpx;
				max-height: 85vh;
				display: flex;
				flex-direction: column;
			}
			&-topbg{
				width: 100%;
				position: absolute;
				left: 0;
				top: 0;
			}
			&-top{
				position: relative;
				padding: 0 10rpx 0 34rpx;
				&.login{
					padding: 0;
				}
				&-left{
					width: 158rpx;
					height: 88rpx;
					&.login{
						width: 224rpx;
						height: 48rpx;
					}
				}
				&-right{
					width: 28rpx;
					height: 28rpx;
				}
			}
			&-title{
				position: relative;
				margin-top: 18rpx;
				padding-left: 34rpx;
				.p{
					font-family: PingFangSC, PingFang SC;
					font-weight: 600;
					font-size: 44rpx;
					color: #151B29;
					line-height: 62rpx;
					&.tip{
						font-weight: 400;
						font-size: 26rpx;
						color: rgba(21,27,41,0.61);
						line-height: 37rpx;
						margin-top: 10rpx;
					}
				}
			}
			&-form{
				position: relative;
				margin-top: 10rpx;
				&-item{
					height: 120rpx;
					background: #FFFFFF;
					border-radius: 16rpx;
					border: 1rpx solid #E0E1E4;
					padding: 0 30rpx;
					margin-top: 20rpx;
					&-left{
						flex: 1;
						min-width: 0;
						.text{
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							font-size: 30rpx;
							color: #151B29;
							line-height: 42rpx;
							white-space: nowrap;
						}
						image{
							width: 60rpx;
							height: 60rpx;
							border-radius: 50%;
							margin-left: 28rpx;
						}
					}
					&-right{
						flex-shrink: 0;
						padding-left: 20rpx;
						box-sizing: border-box;
						.yjsq{
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							font-size: 28rpx;
							color: #0593FE;
							line-height: 40rpx;
							background-color: transparent;
							text-align: right;
							padding: 0;
							&::after{
								width: auto;
								border: none;
							}
						}
					}
				}
			}
			&-scroll{
				flex: 1;
				overflow: hidden;
			}
			&-btns{
				margin-top: 20rpx;
				padding: 0 10rpx;
				overflow: hidden;
				.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;
					&.login{
						background: #ECEEF5;
					}
				}
			}
			&-memo{
				position: relative;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 26rpx;
				color: #151B29;
				line-height: 36rpx;
				letter-spacing: 4rpx;
				margin-top: 41rpx;
			}
			&-login{
				margin-top: 82rpx;
				.phone-login{
					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;
					&::after{
						border: none;
					}
				}
			}
		}
	}

	// 孩子信息表单样式
	.member-form{
		padding: 0 10rpx;
		.member-avatar{
			border-bottom: 1rpx solid #E6E6E6;
			padding-bottom: 24rpx;
			&-title{
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 30rpx;
				color: #252525;
				line-height: 42rpx;
				span{ color: #F4657A; }
			}
			&-imgbox{
				width: 122rpx;
				height: 122rpx;
				&-img{
					width: 100%;
					height: 100%;
					border-radius: 50%;
				}
			}
			&-add{
				margin-left: 40rpx;
				width: 122rpx;
				height: 122rpx;
				border-radius: 50%;
			}
		}
		.member-item{
			height: 90rpx;
			box-shadow: inset 0rpx -1rpx 0rpx 0rpx #E6E6E6;
			&-left{
				width: 200rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #676775;
				line-height: 40rpx;
			}
			&-right{
				width: calc(100% - 200rpx);
				text-align: right;
			}
		}
		.member-section-title{
			font-family: PingFang-SC, PingFang-SC;
			font-weight: bold;
			font-size: 36rpx;
			color: #151B29;
			line-height: 48rpx;
			margin-top: 40rpx;
		}
		.member-pre{
			padding: 25rpx 0;
			box-shadow: inset 0rpx -1rpx 0rpx 0rpx #F2F2F2;
			&-title{
				width: 209rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #676775;
				line-height: 40rpx;
				span{ color: #F4657A; margin-right: 4rpx; }
			}
			&-content{
				width: calc(100% - 209rpx);
				display: flex;
				align-items: center;
				justify-content: flex-end;
				&-box{
					margin-left: 80rpx;
					image{
						width: 28rpx;
						height: 28rpx;
					}
					text{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 30rpx;
						color: #252525;
						line-height: 42rpx;
						margin-left: 16rpx;
					}
				}
			}
		}
	}
</style>
