<template>
	<!-- 店铺详情 -->
	<u-popup :show="show" :round="20" overlayOpacity="0.8" mode="bottom" @close="showClose" height="500">
		<view class="register-member-wrap">
			<view class="register-title">欢迎加入{{shopUserInfo.shopName?shopUserInfo.shopName:'本店'}}</view>
			<!-- <view class="register-tip">请完善个人信息完成会员注册</view> -->
			<view class="register-tip">请先完成股东信息提交</view>
			
			
			<view class="register-content">
				<view class="reg-head">
					<view class="reg-head-img">
						<!-- #ifdef MP-WEIXIN || H5 -->
						<button class="reg-head-img" type="default" open-type="chooseAvatar"
							@chooseavatar="onChooseAvatar">
							<image class="reg-head-img"
								:src="userHeadImg || 'https://czg-qr-order.oss-cn-beijing.aliyuncs.com/menber/head_default.png'"
								mode="aspectFill"></image>
						</button>
						<!-- #endif -->
						<!-- #ifdef MP-ALIPAY -->
						<button class="reg-head-img" @click="onChooseAvatar">
							<image class="reg-head-img"
								:src="userHeadImg || 'https://czg-qr-order.oss-cn-beijing.aliyuncs.com/menber/head_default.png'"
								mode="aspectFill"></image>
						</button>
						<!-- #endif -->

					</view>
				</view>
				<view class="reg-cell">
					<view class="lable">昵称<text style="color: #CD1A1A;">*</text></view>
					<u-input class="value" v-model="formInfo.nickName" fontSize="14px" type="text" input-align="left"
						placeholder="请输入昵称" :custom-style="{border:'none'}"
						placeholderStyle="color:#999;font-size: 28rpx" />
				</view>
				<view class="reg-cell" @click="calendarShow = true">
					<view class="lable">生日</view>
					<view class="value" :style="{color: formInfo.birthDay ? '#333' : '#999'}">
						{{ formInfo.birthDay || '请选择日期'}}
					</view>
					<!-- <u-calendar  @close="calendarShow = false" monthNum="99" minDate="1945-01-01" maxDate="2055-12-12" :show="calendarShow" mode="single" @confirm="confirmCalendar"></u-calendar> -->
					<!-- <u-picker :show="calendarShow" ref="uPicker" :columns="columns" @confirm="confirm" @change="changeHandler"></u-picker> -->
					<!-- <picker :show="calendarShow" mode="date"></picker> -->
					<up-datetime-picker mode="date" @cancel="calendarShow = false" :show="calendarShow"
						:minDate="-2208988800000" v-model="value1" itemHeight="66" visibleItemCount="5"
						@confirm="confirmTime"></up-datetime-picker>
					<up-icon name="arrow-down-fill" color="#000" size="10"></up-icon>
				</view>
				<view class="reg-cell">
					<view class="lable">性别<text style="color: #CD1A1A;">*</text></view>
					<up-radio-group v-model="formInfo.sex" active-color="#E3AD7F">
						<up-radio  :name="1" label="男"></up-radio>
						<up-radio  :name="0" label="女"></up-radio>
					</up-radio-group>
				</view>
				<view class="reg-cell">
					<view class="lable">手机号</view>
					<up-input class="value" v-model="formInfo.telephone" fontSize="14px" type="text" input-align="left"
						readonly placeholder="获取手机号" :custom-style="{border:'none'}"
						placeholder-style="color:#999;font-size: 28rpx" />
					<!-- #ifdef MP-WEIXIN || H5 -->
					<button class="getPhone" size="10" open-type="getPhoneNumber" @getphonenumber="getPhone">
					<!-- #endif -->
						<!-- #ifdef MP-ALIPAY -->
						<button class="getPhone" size="10" open-type="getAuthorize" scope='phoneNumber'
							@getAuthorize="getPhone">
						<!-- #endif -->
							<view class="text">{{'获取手机号'}}</view>
						</button>
				</view>
				<view class="agreement">
					<view class="agreement_tip">我已阅读并同意以下内容</view>
					<view class="agreement_item" @click="isProtocol = !isProtocol">
						<up-checkbox-group>
							<up-checkbox :checked="isProtocol" shape="circle" activeColor="#E3AD7F"
								@change="radioChange" size="15" iconSize="10"></up-checkbox>
						</up-checkbox-group>
						<text @click.stop="viewProtocol(1)" class="agreement_item_text">用户协议/隐私条款</text>
					</view>
					<!-- <view class="agreement_item">
						<u-checkbox-group>
							<u-checkbox shape="circle" activeColor="#E3AD7F" @change="radioChange" size="30"></u-checkbox>
						</u-checkbox-group>
						<text class="agreement_item_text">隐私条款</text>
					</view> -->
				</view>
				<view class="register_btn" @tap="$u.debounce(registerMember, 500)">确认提交</view>
			</view>
		</view>
	</u-popup>
</template>

<script setup>
	import {
		defineProps,
		reactive,
		ref,
		defineEmits,
		watch,
		watchEffect
	} from 'vue';

	import {
		APIshopUser,
		APIshopUserInfo
	} from '@/common/api/member.js'
	import {
		shopUserConfirm
	} from '@/common/api/account/index.js'
	import {
		APIuserphone
	} from '@/common/api/api.js'

	const props = defineProps({
		shopUserInfo: {
			type: Object,
			default: () => ({})
		},
		detailtype: {
			type: String,
			default: ''
		},
		shopId: {
			type: String,
			default: ''
		},
	});
	const show=defineModel(false)
	// 定义事件发射器
	const emits = defineEmits(['emitsmemberOpen','update']);

	// 定义要触发的事件

	const formInfo = reactive({
		nickName: "",
		telephone: "",
		birthDay: "",
		sex:1,
	})
	const userHeadImg = ref('')
	
	watchEffect(()=>{
		formInfo.nickName= `${props.shopUserInfo.nickName}`.trim() ==='微信用户' ? '' :(props.shopUserInfo.nickName||'')
		formInfo.telephone=props.shopUserInfo.phone||''
		formInfo.birthDay=props.shopUserInfo.birthDay||''
		formInfo.sex=props.shopUserInfo.sex||1
		userHeadImg.value=props.shopUserInfo.headImg||''
	})
	const value1 = Number(new Date())

	const calendarShow = ref(false)

	// 用户图片


	//显示隐藏
	const isProtocol = ref(false)

	const init = async () => {

		// if (uni.cache.get('shopUserInfo') && props.shopId||uni.cache.get('shopId') == uni.cache.get('shopUserInfo').id) {
		// 	shopUserInfo = uni.cache.get('shopUserInfo');
		// } else {
		// 	let res = await this.api.shopUserInfo({
		// 		"shopId": props.shopId||uni.cache.get('shopId'),
		// 		"userId": uni.cache.get('userInfo').id,
		// 	})
		// 	if (res.code == 0) {
		// 		shopUserInfo = res.data;
		// 	}
		// }
		// memberOpen.value = shopUserInfo.isVip == 0 ? true : false;
		// userHeadImg.value = shopUserInfo.headImg;
		// formInfo.nickName = shopUserInfo.nickName && shopUserInfo.nickName != '微信用户' ? shopUserInfo
		// 	.nickName : '';
		// formInfo.telephone = shopUserInfo.telephone;
		// formInfo.birthDay = shopUserInfo.birthDay

	}

	// 返回
	const showClose = () => {
		// uni.navigateBack()
		show.value=false
	}

	// 
	const radioChange = (n) => {
		isProtocol.value = n;
	}

	// 查看协议
	const viewProtocol = () => {
		wx.openPrivacyContract({
			success: () => {}, // 打开成功
			fail: () => {}, // 打开失败
			complete: () => {}
		})
	}

	//上传头像
	const onChooseAvatar = (e) => {
		//#ifdef MP-WEIXIN
		let avatarUrl = e.detail.avatarUrl
		uni.uploadFile({
			url: uni.conf.baseUrl + '/account/user/common/upload',
			filePath: avatarUrl,
			header: {
				shopId: props.shopId||uni.cache.get('shopId'),
				token: uni.cache.get('token') || '',
				'content-type': 'multipart/form-data'
			},
			fileType: 'image',
			name: "file",
			formData: {
				file: avatarUrl,
			},
			success: (uploadFileRes) => {
				let {
					data
				} = JSON.parse(uploadFileRes.data)
				userHeadImg.value = data
			},
			fail: (res) => {
				console.log(res)
			}
		});
		// #endif
		//#ifdef MP-ALIPAY
		uni.chooseImage({
			count: 1, // 默认9，设置图片的数量
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function(res) {
				// 成功选择图片后
				let avatarUrl = res.tempFilePaths[0]; // 获取文件路径

				my.uploadFile({
					url: uni.conf.baseUrl + '/account/user/common/upload',
					filePath: avatarUrl,
					header: {
						environment: 'app',
						type: 'android',
						version: '1.7.3',
						'content-type': 'multipart/form-data'
					},
					fileType: 'image',
					name: "file",
					formData: {
						file: avatarUrl,
					},
					success: (uploadFileRes) => {
						let {
							data
						} = JSON.parse(uploadFileRes.data)
						userHeadImg.value = data
					},
					fail: (res) => {
						console.log(res)
					}
				});
			},
			fail: (res) => {
				console.log(res)
			}
		});
		// #endif
	}


	// 确定生日
	const confirmTime = (e) => {
		calendarShow.value = false;
		formInfo.birthDay = getDate(e.value);
	}

	// 获取手机号
	const getPhone = (d) => {
		// #ifdef MP-WEIXIN
		if (d.detail.iv) {
			uni.login({
				provider: 'weixin',
				success: async (data) => {
					let res = await APIuserphone({
						code: data.code,
						encryptedData: d.detail.encryptedData,
						iv: d.detail.iv,
						source: "wechar"
					})
					formInfo.telephone = res
				}
			})
		}
		// #endif
		// #ifdef MP-ALIPAY
		// 支付宝小程序环境
		my.getAuthCode({
			scopes: 'auth_user',
			success: (res) => {
				console.log(res)
				my.getPhoneNumber({
					success: async (data) => {
						let res = await APIuserphone({
							encryptedData: JSON.parse(data.response).response,
							source: "alipay"
						})
						formInfo.telephone = res
						// console.log(this.phonetitle)
					}
				});
			}
		});
		// #endif
	}

	// 格式化时间戳
	const getDate = (time) => {
		const date = new Date(time);
		// const date = new Date();
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();


		month = month > 9 ? month : '0' + month;
		day = day > 9 ? day : '0' + day;
		return `${year}-${month}-${day}`;
	}


	const registerMember = async () => {
		if (formInfo.nickName == "" || formInfo.nickName == null) {
			uni.showToast({
				title: '请输入会员昵称',
				icon: 'none'
			});
			return;
		}

		if (formInfo.telephone == "" || formInfo.telephone == null) {
			uni.showToast({
				title: '请获取手机号',
				icon: 'none'
			});
			return;
		}
		if (!isProtocol.value) {
			uni.showToast({
				title: '请勾选协议',
				icon: 'none'
			});
			return;
		}
		let idSet = new Set(
		  props.shopUserInfo.shopConfirm 
		    ? props.shopUserInfo.shopConfirm.split(',') 
		    : []
		);
		
		const shopIdToAdd = props.shopId || uni.cache.get('shopId');
		if (shopIdToAdd) {
		  idSet.add(shopIdToAdd);
		}
		let idArr = Array.from(idSet).filter(v=>v!=='');
		const submitForm={
			// id: uni.cache.get('userInfo').id,
			shopId: props.shopId||uni.cache.get('shopId'),
			nickName: formInfo.nickName,
			headImg: userHeadImg.value,
			phone: formInfo.telephone,
			birthDay: formInfo.birthDay,
			sex:formInfo.sex,
			shopConfirm:idArr.join(',')
		}
		// await APIshopUser(submitForm)
		await shopUserConfirm({
			id:props.shopUserInfo.id,
			shopId: props.shopId||uni.cache.get('shopId'),
			nickName: formInfo.nickName,
			headImg: userHeadImg.value,
			phone: formInfo.telephone,
			birthDay: formInfo.birthDay,
			sex:formInfo.sex,
			shopConfirm:idArr.join(',')
		})
		let APIshopUserInfores = await APIshopUserInfo({
			shopId: props.shopId||uni.cache.get('shopId')
		})
		uni.cache.set('orderVIP', APIshopUserInfores)
		uni.cache.set('ordershopUserInfo', APIshopUserInfores.shopInfo)
		
		uni.showToast({
			title:props.shopUserInfo.phone? '修改成功': '注册成功',
			icon: 'none'
		})
		emits('update',APIshopUserInfores)
		show.value=false
		// 定义自定义事件
		// setTimeout(() => {
		// 	uni.navigateBack()
		// }, 1500)
		emits('emitsmemberOpen',submitForm);

	}
</script>

<style lang="scss" scoped>
	.u-datetime-picker {
		height: 300px !important;
	}

	.register-member-wrap {
		padding: 64rpx 24rpx;
		display: flex;
		flex-direction: column;

		.register-title {
			font-weight: bold;
			font-size: 36rpx;
			color: #333333;
			margin-bottom: 16rpx;
		}

		.register-tip {
			font-weight: 400;
			font-size: 24rpx;
			color: #999999;
		}

		.register-content {
			display: flex;
			flex-direction: column;

			.reg-head {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-top: 64rpx;

				.reg-head-img {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					padding: 0;
					position: relative;
				}

				.reg-head-edit {
					width: 24rpx;
					height: 24rpx;
					position: absolute;
					bottom: 0;
					right: 14rpx;
				}
			}

			.reg-cell {
				display: flex;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 2rpx solid #E5E5E5;

				.lable {
					width: 120rpx;
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
				}

				.value {
					font-weight: 400;
					font-size: 28rpx;
					color: #333;
					padding: 12rpx 0 12rpx 18rpx;
				}

				.u-input {
					input {
						font-size: 28rpx !important;
					}
				}

				.getPhone {
					background-color: none;
					border: 2rpx solid #E3AD7F;
					color: #E3AD7F;
					font-size: 24rpx;
					padding: 5rpx 30rpx;
					// #ifdef MP-ALIPAY
					padding-top: 0;
					display: initial;
					height: 70rpx;
					line-height: 70rpx;
					box-sizing: border-box;
					border-radius: 5rpx;
					// #endif
				}
			}

			.agreement {
				display: flex;
				flex-direction: column;
				margin-top: 48rpx;

				.agreement_tip {
					font-weight: 400;
					font-size: 24rpx;
					color: #666666;
				}

				.agreement_item {
					display: flex;
					padding-top: 32rpx;
					padding-bottom: 16rpx;
					align-items: center;

					.agreement_item_text {
						font-weight: 500;
						font-size: 24rpx;
						color: #E3AD7F;
					}
				}
			}

			.register_btn {
				width: 572rpx;
				height: 90rpx;
				line-height: 90rpx;
				text-align: center;
				background: #E3AD7F;
				border-radius: 48rpx 48rpx 48rpx 48rpx;
				font-weight: 500;
				font-size: 36rpx;
				color: #FFFFFF;
				margin: 30rpx auto 0 auto;
			}
		}
	}
</style>