<template>
	<view class="common_page" :style="{'min-height':h+'px', 'padding-top':mt+'px'}">
		<cus-header :title="title" bgColor="#FFFFFF"></cus-header>
		<view class="form">
			<view class="avatar">
				<view class="title"><span>*</span>头像</view>
				<view class="adfac" style="margin: 24rpx 0 52rpx;">
					<view class="imgbox">
						<image class="imgbox-avatar" :src="memberInfo?.avatarPath||defaultAvatar" @click="changeAvatar"></image>
					</view>
					<image class="add-avatar" src="https://oss.familydaf.cn/sxsnfile/20251219/0b4d0f26464945dbae17491f1b529229.png" @click="changeAvatar"></image>
				</view>
			</view>
			<view class="item adfacjb">
				<view class="left">个人公益名称</view>
				<view class="right">
					<input min="3" class="setinp"v-model="memberInfo.welfareName" placeholder-style="color: #A1A4A9;font-size: 28rpx;" placeholder="请输入最少三个字"></input>
				</view>
			</view>
			<view class="item adfacjb">
				<view class="left">个人公益口号</view>
				<view class="right">
					<input class="setinp"v-model="memberInfo.welfareSlogan" placeholder-style="color: #A1A4A9;font-size: 28rpx;" placeholder="请输入个人公益口号"></input>
				</view>
			</view>
		</view>
		<view class="form">
			<view class="title">成员信息</view>
			<view class="pre adfac" style="margin-top: 40rpx;">
				<view class="pre-title"><span>*</span>人员类型</view>
				<view class="pre-content adfac">
					<view class="pre-content-box adfac" @click="changeMember(1,'personnelType')">
						<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="pre-content-box adfac" @click="changeMember(2,'personnelType')">
						<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="pre adfac">
				<view class="pre-title"><span>*</span>姓名</view>
				<view class="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="pre adfac">
				<view class="pre-title"><span>*</span>身份证</view>
				<view class="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="pre adfac">
				<view class="pre-title"><span style="color: #FFFFFF;">*</span>义工号</view>
				<view class="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="pre adfac">
				<view class="pre-title"><span>*</span>性别</view>
				<view class="pre-content adfac">
					<view class="pre-content-box adfac" @click="changeMember(0,'gender')">
						<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="pre-content-box adfac" @click="changeMember(1,'gender')" style="margin-left: 114rpx;">
						<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="pre adfac" v-if="memberInfo.personnelType==2">
				<view class="pre-title"><span>*</span>就读学校</view>
				<view class="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="pre adfac">
				<view class="pre-title">会员渠道</view>
				<view class="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>
		<view class="btn" @click="handleSave">保存</view>
		<qf-image-cropper :width="500" :height="500" :radius="30" @crop="handleCrop" ref="qicRef" v-if="qicShow"></qf-image-cropper>
	</view>
</template>

<script setup name="">
	import { BaseApi2 } from '../common/api/baseApi';
	import CusHeader from '@/components/CusHeader/index.vue'
	import { onLoad } from '@dcloudio/uni-app' 
	import { ref, getCurrentInstance, nextTick } from 'vue'
	const { proxy } = getCurrentInstance()
	
	const title = ref('添加家庭成员')
	const defaultAvatar = ref('https://oss.familydaf.cn/sxsnfile/20251218/3821654e080945998d464f3c3aa64122.png')
	const memberInfo = ref({
		userId:'',
		personnelType:1,
		name:'',
		idCard:'',
		volunteerNo:'',
		gender:0,
		currentSchool:''
	})
	const qicShow = ref(false)
	// 渠道相关
	const channelList = ref([])          // 会员渠道列表（可选项）
	const selectedChannelId = ref('')    // 已选渠道 ID（字符串）
	const selectedChannelIndex = ref(-1) // picker 当前选中下标，-1 表示未选
	const hasSelectedChannel = ref(false)  // 用户是否主动选择过渠道
	const turnType = ref('')
	
	const loadChannelList = () => {
		return new Promise((resolve) => {
			proxy.$api.get('/channel/list', {}).then(({ data: res }) => {
				if (res.code !== 0) {
					resolve()
					return
				}
				channelList.value = res.data || []
				// 若 loadMemberChannel 已先完成并设置了 selectedChannelId，补充同步 index
				if (selectedChannelId.value) {
					const idx = channelList.value.findIndex(c => String(c.id) === selectedChannelId.value)
					if (idx >= 0) selectedChannelIndex.value = idx
				}
				resolve()
			})
		})
	}

	const loadMemberChannel = (memberId) => {
		proxy.$api.get('/member/channelList', { memberId }).then(({ data: res }) => {
			if (res.code !== 0) return
			const list = res.data || []
			if (list.length > 0) {
				selectedChannelId.value = String(list[0].id)
				const idx = channelList.value.findIndex(c => String(c.id) === selectedChannelId.value)
				if (idx >= 0) selectedChannelIndex.value = idx
			}
		})
	}

	const changeMember = (value,key) => {
		memberInfo.value[key] = value;
	}
	
	const handleSave = 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('请输入就读学校')
		memberInfo.value.gender = memberInfo.value.gender??1;
		
		const checkMsgs = ['welfareName','welfareSlogan','name'].map(k=>checkMsg(k));
		const tipRes = (await Promise.all(checkMsgs)).filter(item=>item!=='ok');
		if(tipRes&&tipRes.length) return proxy.$showModal(tipRes.join('、'))
		
		if(!memberInfo.value.userId) memberInfo.value.userId = JSON.parse(uni.getStorageSync('userInfo')).id;
		proxy.$api[memberInfo.value.id?'put':'post']('/core/family/member',memberInfo.value).then(({data:res})=>{
			if(res.code!==0) return proxy.$showToast(res.msg)
			const memberId = memberInfo.value.id || res.data?.id
			// 编辑时（memberInfo.value.id 存在）或用户主动选择了渠道，才调用 setMemberChannel
			if (memberId && (hasSelectedChannel.value || memberInfo.value.id)) {
				setMemberChannel(memberId)  // 异步，不 await，不阻断跳转
			}
			proxy.$showToast(memberInfo.value.id?'编辑成功':'添加成功')
			setTimeout(()=>{
				if(turnType.value==='my'){
					uni.reLaunch({
						url:'/pages/my'
					})
					return
				}
				uni.redirectTo({
					url:'/pagesMy/familyMember'
				})
			},1000)
		})
	}

	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,
			channelIds: selectedChannelId.value
		}).then(({ data: res }) => {
			if (res.code !== 0) proxy.$showToast(res.msg)
		}).catch(() => {
			proxy.$showToast('渠道设置失败，请稍后重试')
		})
	}
	
	const checkMsg = async msg => {
		const msgAlert = {
			welfareName:'家庭公益名称',
			welfareSlogan:'家庭公益口号',
			name:'姓名'
		}
		return new Promise((resolve,reject)=>{
			proxy.$api.detectionContent(memberInfo.value[msg]).then(res=>{
				resolve(res.code!==0?(`${msgAlert[msg]}：`+res.msg):'ok')
			})
		})
	}
	
	const getMemberInfo = (id) => {
		proxy.$api.get(`/core/family/member/${id}`).then(({data:res})=>{
			if(res.code!==0) return proxy.$showToast(res.msg)
			if(res.data){
				memberInfo.value = {...memberInfo.value,...res.data}
			}
		})
	}
	
	const changeAvatar = () => {
		uni.showActionSheet({
			itemList: ['从手机相册选择'],
			success: (res) => {
			  if (res.tapIndex === 0) { // 从手机相册选择
				chooseLocalImage();
			  }
			}
		});
	}
	
	// 从本地选择图片并显示
	const chooseLocalImage = () => {
	  uni.chooseImage({
		count: 1, // 只能选择一张
		sizeType: ['compressed'], // 压缩图片
		sourceType: ['album', 'camera'], // 可以从相册或相机选择
		success: (res) => {
		  const tempFilePaths = res.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)
				})
			})
		  }
		},
		fail: (err) => {
		  console.error('选择图片失败', err);
		}
	  });
	}
	
	
	const handleCrop = async (e) => {
		const result = await uploadFilePromise(e.tempFilePath);
		memberInfo.value.avatarPath = result||'';
		qicShow.value = false;
	}
	
	const uploadFilePromise = (url) => {
	  return new Promise((resolve, reject) => {
	    let a = 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)
	        }, 1000);
	      },
		  fail: err =>{
			resolve('');
		  }
	    });
	  });
	};
	
	onLoad(async (options)=>{
		turnType.value = options.type;
		await loadChannelList()
		const id = options?.id;
		if(id){
			title.value = '编辑家庭成员';
			getMemberInfo(id)
			loadMemberChannel(id)
		}
	})
</script>

<style scoped lang="scss">
	.common_page{
		padding-bottom: 184rpx;
		
		.form{
			background: #FFFFFF;
			border-radius: 24rpx;
			margin-top: 20rpx;
			padding: 36rpx 24rpx 0;
			
			.avatar{
				.title{
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 30rpx;
					color: #252525;
					line-height: 42rpx;
					label{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 30rpx;
						color: #F4657A;
						line-height: 42rpx;
					}
				}
				.imgbox{
					width: 122rpx;
					height: 122rpx;
					&-avatar{
						width: 100%;
						height: 100%;
						border-radius: 50%;
					}
				}
				.add-avatar{
					margin-left: 40rpx;
					width: 122rpx;
					height: 122rpx;
					border-radius: 50%;
				}
				border-bottom: 1rpx solid #E6E6E6;
			}
			.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);
				}
			}
			
			.title{
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 36rpx;
				color: #151B29;
				line-height: 48rpx;
			}
		
			.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;
					label{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 30rpx;
						color: #F4657A;
						line-height: 42rpx;
						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;
						}
					}
				}
			}
		}
		
		.btn{
			width: calc(100% - 80rpx);
			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;
			position: fixed;
			left: 40rpx;
			bottom: 64rpx;
		}
	}
</style>