<template>
	<view class="step-container">
		<!-- 步骤指示器 -->
		<view class="step-header">
			<text class="step-title">STEP {{ currentStep }}</text>
			<view class="step-progress">
				<view class="progress-bar">
					<view class="progress-inner" :style="{ width: currentStep === 1 ? '50%' : '100%' }"></view>
				</view>
			</view>
		</view>

		<!-- 步骤1：个人信息 -->
		<view v-if="currentStep === 1" class="step-content">
			<view class="step-subtitle">定制个人信息</view>
			
			<!-- 头像上传 -->
			<view class="avatar-section">
				<view class="avatar-wrapper" @click="chooseAvatar">
					<image v-if="userInfo.avatar" :src="userInfo.avatar" mode="aspectFill" class="avatar"></image>
					<view v-else class="avatar-placeholder">
						<image src="/static/icons/camera.png" mode="aspectFit" class="camera-icon"></image>
					</view>
				</view>
			</view>

			<!-- 昵称输入 -->
			<view class="input-section">
				<view class="input-label">我的名字</view>
				<view class="input-wrapper">
					<input 
						type="text" 
						v-model="userInfo.nickname" 
						placeholder="取一个独一无二的名字吧~"
						placeholder-class="input-placeholder"
					/>
					<image 
						v-if="userInfo.nickname" 
						src="/static/icons/clear.png" 
						mode="aspectFit" 
						class="clear-icon"
						@click="userInfo.nickname = ''"
					></image>
				</view>
			</view>

			<!-- 性别选择 -->
			<view class="gender-section">
				<view class="input-label">性别</view>
				<view class="gender-options">
					<view 
						class="gender-item" 
						:class="{ active: userInfo.gender === 'male' }"
						@click="userInfo.gender = 'male'"
					>
						<image src="/static/icons/male.png" mode="aspectFit" class="gender-icon"></image>
						<text>男生</text>
					</view>
					<view 
						class="gender-item" 
						:class="{ active: userInfo.gender === 'female' }"
						@click="userInfo.gender = 'female'"
					>
						<image src="/static/icons/female.png" mode="aspectFit" class="gender-icon"></image>
						<text>女生</text>
					</view>
					<view 
						class="gender-item" 
						:class="{ active: userInfo.gender === 'other' }"
						@click="userInfo.gender = 'other'"
					>
						<image src="/static/icons/other.png" mode="aspectFit" class="gender-icon"></image>
						<text>其他</text>
					</view>
				</view>
			</view>

			<!-- 生日选择 -->
			<view class="birthday-section">
				<view class="input-label">我的生日</view>
				<view class="birthday-picker" @click="showDatePicker = true">
					<text :class="{ placeholder: !userInfo.birthday }">{{ userInfo.birthday || '告诉我你的生日吧' }}</text>
					<image src="/static/icons/arrow-right.png" mode="aspectFit" class="arrow-icon"></image>
				</view>
			</view>
		</view>

		<!-- 步骤2：兴趣选择 -->
		<view v-if="currentStep === 2" class="step-content">
			<view class="step-subtitle">定制个人兴趣圈</view>
			<view class="interest-section">
				<text class="interest-tip">请选择</text>
				<!-- 兴趣选择圆圈 -->
				<view class="interest-circles">
					<view 
						v-for="(interest, index) in interests" 
						:key="index"
						class="interest-circle"
						:class="{ active: selectedInterests.includes(interest.id) }"
						@click="toggleInterest(interest.id)"
					>
						{{ interest.name }}
					</view>
				</view>

				<!-- 添加兴趣爱好 -->
				<view class="add-interests">
					<text class="add-title">添加兴趣爱好</text>
					<view class="interest-tags">
						<view 
							v-for="(tag, index) in interestTags" 
							:key="index"
							class="interest-tag"
							:class="{ active: selectedTags.includes(tag.id) }"
							@click="toggleTag(tag.id)"
						>
							{{ tag.name }}
							<text v-if="selectedTags.includes(tag.id)" class="remove-tag" @click.stop="removeTag(tag.id)">×</text>
						</view>
						<view class="add-tag" @click="showAddTag = true">
							<image src="/static/icons/add.png" mode="aspectFit" class="add-icon"></image>
							创建新偏好
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-button" :class="{ 'step2': currentStep === 2 }" @click="handleNext">
			{{ currentStep === 1 ? '下一步' : '完成' }}
		</view>

		<!-- 日期选择弹窗 -->
		<uni-datetime-picker
			v-if="showDatePicker"
			type="date"
			:value="userInfo.birthday"
			@confirm="onDateConfirm"
			@close="showDatePicker = false"
		/>

		<!-- 添加标签弹窗 -->
		<uni-popup v-if="showAddTag" @close="showAddTag = false">
			<view class="add-tag-popup">
				<input 
					type="text" 
					v-model="newTag" 
					placeholder="请输入新的兴趣爱好"
					@confirm="addNewTag"
				/>
				<button @click="addNewTag">添加</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		requestAndroidPermission,
		gotoAppPermissionSetting
	} from '../index/permission.js'
	export default {
		components: {},
		data() {
			return {
				showRights: false,
				title: '',
				currentStep: 1,
				sel: 1,
				info: {},
				showPop: false,
				nickname: '',
				wechat: '',
				sex: 1,
				age: 18,
				height: 160,
				weight: 50,
				avator: '../../static/me/avator.png',
				ziye: '',
				qianmin: '',

				xueli_sel: '',
				xueli: ['初中', '初中', '中专', '高中', '专科', '本科', '研究生', '硕士', '博士'],
				xinzuo_sel: '',
				xinzuo: ['水瓶座', '双鱼座', '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座'],

				list_tag: [
					'篮球', '排球', '足球', '羽毛球', '健身达人', '美食达人'
				],
				sel_tags: [],
				selectedTags: [],
				tagList: [
					{ name: '游戏', size: 'large' },
					{ name: '音乐', size: 'medium' },
					{ name: '盲盒', size: 'large' },
					{ name: '小可爱', size: 'small' },
					{ name: '娃娃人', size: 'medium' },
					{ name: '纹身', size: 'large' },
					{ name: '洛丽塔', size: 'small' },
					{ name: '女装', size: 'medium' },
					{ name: '萌球', size: 'small' }
				],
				userInfo: {
					avatar: '',
					nickname: '',
					gender: '',
					birthday: ''
				},
				interests: [
					{ id: 1, name: '电影' },
					{ id: 2, name: '宠物' },
					{ id: 3, name: 'Hip-Hop' },
					{ id: 4, name: '旅行' },
					{ id: 5, name: '潮玩' },
					{ id: 6, name: '运动' },
					{ id: 7, name: '游戏' },
					{ id: 8, name: '二次元' }
				],
				selectedInterests: [],
				interestTags: [
					{ id: 1, name: 'ACG' },
					{ id: 2, name: '明日方舟' },
					{ id: 3, name: '手游深度玩家' },
					{ id: 4, name: '游戏人生' },
					{ id: 5, name: '碧蓝档案' },
					{ id: 6, name: '夏目友人帐' },
					{ id: 7, name: 'FATE' }
				],
				showDatePicker: false,
				showAddTag: false,
				newTag: ''
			}
		},
		onLoad() {
			this.currentStep = 1;
			let tagStr =
				"篮球、羽毛球、兵乓球、足球、滑板、滑旱冰、跑步、跳绳、举重、听音乐、看电影、绘画、写小说、看书、做弹弓玩、做木剑玩、做橡皮枪玩、积木、用麻将搭金字塔、拼图、拆装、扑克牌、小汽车、手表、鞋之类的、弹吉他、钢琴、萨克斯、葫芦丝、大号、小号、折纸、剪纸、品茶、涂鸦、英雄联盟、qq堂、cs、cf、地下城勇士、桌面游戏";
			this.list_tag = tagStr.split("、");
			this.getInfoData();
		},
		onShow() {},
		methods: {
			onBack() {},
			chkSel() {
				if (this.sel == 1) {
					this.sel = 0;
				} else {
					this.sel = 1;
				}
			},
			chkSex(sex) {
				this.sex = sex;
			},
			delTag(tg) {
				let list_tag2 = [];
				for (let i = 0; i < this.sel_tags.length; i++) {
					if (this.sel_tags[i] != tg && this.sel_tags[i] != '') {
						list_tag2.push(this.sel_tags[i]);
					}
				}
				this.sel_tags = list_tag2;
			},
			selTags(itm) {
				let that = this;
				let isIn = false;
				for (let entry of this.sel_tags) {
					// console.log(entry); // 1, "string", false
					if (entry == itm) {
						isIn = true;
						break;
					}
				}
				return isIn;
			},
			chkTag(itm) {
				if (this.selTags(itm)) {
					let tmpTags = [];
					for (let entry of this.sel_tags) {
						// console.log(entry); // 1, "string", false
						if (entry != itm && entry != '') {
							tmpTags.push(entry);
						}
					}
					this.sel_tags = tmpTags;
				} else {
					if (this.sel_tags.length >= 10) {
						this.$refs['ToastW3'].showToast({
							title: "最多选择10个标签",
							animation: 0
						});
						return;
					}
					this.sel_tags.push(itm);
				}
			},
			sliderChange1(e) {
				this.age = e.detail.value;
			},
			sliderChange2(e) {
				this.height = e.detail.value;
			},
			sliderChange3(e) {
				this.weight = e.detail.value;
			},
			SetXueli() {
				let that = this;
				uni.showActionSheet({
					itemColor: '#000000',
					itemList: this.xueli,
					success: function(res) {
						that.xueli_sel = that.xueli[res.tapIndex];
						// console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			SetXinzuo() {
				let that = this;
				uni.showActionSheet({
					itemColor: '#000000',
					itemList: this.xinzuo,
					success: function(res) {
						that.xinzuo_sel = that.xinzuo[res.tapIndex];
						// console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			getInfoData() {
				console.log(this.$apiHost + '/Member/getinfoData');
				uni.request({
					url: this.$apiHost + '/Member/getinfoData', //仅为示例，并非真实接口地址。
					data: {
						uuid: getApp().globalData.uuid
					},
					header: {
						'content-type': 'application/json' //自定义请求头信息
					},
					success: (res) => {
						console.log("res", res.data)
						this.nickname = res.data.nickname;
						this.wechat = res.data.wechat;
						this.sex = res.data.sex || 2;
						this.age = res.data.age || 18;
						this.height = res.data.height || 160;
						this.weight = res.data.weight || 50;
						this.xueli_sel = res.data.xueli;
						this.xinzuo_sel = res.data.xinzuo;
						this.ziye = res.data.ziye;
						this.qianmin = res.data.qianmin;
						if (res.data.avator != "") {
							this.avator = res.data.avator;
						}
						if (res.data.aihao != null && res.data.aihao != undefined) {
							if (res.data.aihao.length > 0) {
								this.sel_tags = res.data.aihao.split(",");
							}
						}
					}
				});
			},

			submitData() {
				let aihao = this.sel_tags.join(',')
				let obj2 = {
					uuid: getApp().globalData.uuid,
					avator: this.avator,
					nickname: this.nickname,
					wechat: this.wechat,
					sex: this.sex,
					age: this.age,
					height: this.height,
					weight: this.weight,
					xueli: this.xueli_sel,
					xinzuo: this.xinzuo_sel,
					ziye: this.ziye,
					qianmin: this.qianmin,
					aihao: aihao
				}
				// console.log("obj2", obj2);
				uni.request({
					url: this.$apiHost + '/Member/setinfoData', //仅为示例，并非真实接口地址。
					data: obj2,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'sign': getApp().globalData.headerSign
					},
					dataType: 'json',
					// header: {
					// 	'content-type': 'application/json', //自定义请求头信息
					// 	'Access-Control-Allow-Origin': '*'
					// },
					success: (res) => {
						console.log("res", res.data)
						this.$refs['ToastW3'].showToast({
							title: res.data.str,
							animation: 0
						});
						if (res.data.success == "yes") {
							uni.switchTab({
								url: "/pages/index/index",
							});
						}
					}
				});
			},
			// upload() {
			// 	let that = this;
			// 	this.$refs['DialogBox'].confirm({
			// 		title: '提示',
			// 		content: '该权限用于获取设备拍摄或获取本地应用相册，进行头像的图片上传。',
			// 		DialogType: 'inquiry',
			// 		btn1: '拒绝',
			// 		btn2: '同意',
			// 		animation: 0
			// 	}).then((res) => {
			// 		that.upload2();
			// 	})
			// },
			upload() {
				this.checkRights();
				console.log("----upload");
				var _self = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册、相机选择
					extension: ['.png', '.jpeg', '.jpg'],
					success: function(res) {
						console.log('res:', res)
						_self.imglocal = res.tempFilePaths[0]
						const tempFilePaths = res.tempFilePaths[0];
						console.log('tempFilePaths:', tempFilePaths);
						// 图片上传
						const uploadTask = uni.uploadFile({
							url: _self.$apiHost + '/Xweb/upload_img?skey=' + _self.skey, // post请求地址
							filePath: res.tempFilePaths[0],
							name: 'file', // 待确认
							success: function(uploadFileRes) {
								let resdata = JSON.parse(uploadFileRes.data)
								console.log('Success11:', uploadFileRes);
								console.log('Success21:', resdata);
								if (resdata.success == 'yes') {
									_self.avator = resdata.url;
								}
							},
							fail: function(uploadFileFail) {
								console.log('Error:', uploadFileFail.data);
							},
							complete: () => {
								console.log('Complete:');
							}
						});
					},
					error: function(e) {
						console.log(e);
					}
				});
			},
			checkRights() {
				let that = this;
				that.showRights = true;
				requestAndroidPermission('android.permission.CAMERA')
					.then(result => {
						that.showRights = false;
						// 根据返回的结果进行处理
						if (result === 1) {} else if (result === 0) {
							console.log('权限被拒绝');
						} else if (result === -1) {
							console.log('权限被永久拒绝');
						}
					})
					.catch(error => {
						that.showRights = true;
						console.log('权限申请失败：', error);
					});
			},
			selectTag(index) {
				const tagIndex = this.selectedTags.indexOf(index);
				if (tagIndex === -1) {
					// 如果未选中，则添加到选中数组
					this.selectedTags.push(index);
				} else {
					// 如果已选中，则从数组中移除
					this.selectedTags.splice(tagIndex, 1);
				}
			},
			chooseAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.userInfo.avatar = res.tempFilePaths[0]
					}
				})
			},
			toggleInterest(id) {
				const index = this.selectedInterests.indexOf(id)
				if (index === -1) {
					this.selectedInterests.push(id)
				} else {
					this.selectedInterests.splice(index, 1)
				}
			},
			toggleTag(id) {
				const index = this.selectedTags.indexOf(id)
				if (index === -1) {
					this.selectedTags.push(id)
				} else {
					this.selectedTags.splice(index, 1)
				}
			},
			removeTag(id) {
				const index = this.selectedTags.indexOf(id)
				if (index !== -1) {
					this.selectedTags.splice(index, 1)
				}
			},
			addNewTag() {
				if (this.newTag.trim()) {
					const newId = this.interestTags.length + 1
					this.interestTags.push({
						id: newId,
						name: this.newTag.trim()
					})
					this.selectedTags.push(newId)
					this.newTag = ''
					this.showAddTag = false
				}
			},
			onDateConfirm(date) {
				this.userInfo.birthday = this.$u.timeFormat(date, 'yyyy-mm-dd')
				this.showDatePicker = false
			},
			handleNext() {
				if (this.currentStep === 1) {
					// 验证第一步数据
					if (!this.userInfo.nickname) {
						uni.showToast({
							title: '请输入昵称',
							icon: 'none'
						})
						return
					}
					if (!this.userInfo.gender) {
						uni.showToast({
							title: '请选择性别',
							icon: 'none'
						})
						return
					}
					this.currentStep = 2
				} else {
					// 验证第二步数据
					if (this.selectedInterests.length === 0 && this.selectedTags.length === 0) {
						uni.showToast({
							title: '请至少选择一个兴趣',
							icon: 'none'
						})
						return
					}
					// 提交所有数据
					this.submitUserInfo()
				}
			},
			submitUserInfo() {
				const data = {
					...this.userInfo,
					interests: this.selectedInterests,
					tags: this.selectedTags
				}
				
				uni.showLoading({
					title: '保存中...'
				})

				// 调用API保存用户信息
				uni.request({
					url: this.$apiHost + '/user/updateProfile',
					method: 'POST',
					data: data,
					header: {
						'content-type': 'application/json',
						'sign': getApp().globalData.headerSign
					},
					success: (res) => {
						if (res.data.success === 'yes') {
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							})
							// 延迟跳转
							setTimeout(() => {
								uni.switchTab({
									url: '/pages/index/index'
								})
							}, 1500)
						} else {
							uni.showToast({
								title: res.data.msg || '保存失败',
								icon: 'none'
							})
						}
					},
					fail: () => {
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						})
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	@import 'normal.scss';

	.popSel {
		position: fixed;
		z-index: 999999;
		top: 0;
		left: 0;
		background-color: #121212;
		width: 100vh;
		height: 100vh;
	}

	.tag_all_select {
		padding: 20rpx;
		
		.tag_items {
			display: flex;
			flex-wrap: wrap;
			gap: 30rpx;
			justify-content: center;
			align-items: center;
			
			.tag_item {
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 50%;
				background: rgba(255,255,255,0.1);
				color: #fff;
				font-size: 26rpx;
				transition: all 0.3s ease;
				cursor: pointer;
				
				&.small {
					width: 120rpx;
					height: 120rpx;
				}
				
				&.medium {
					width: 160rpx;
					height: 160rpx;
					font-size: 28rpx;
				}
				
				&.large {
					width: 200rpx;
					height: 200rpx;
					font-size: 32rpx;
				}
				
				&.active {
					transform: scale(1.2);
					background: rgba(255,255,255,0.2);
					box-shadow: 0 0 20rpx rgba(255,255,255,0.3);
					z-index: 1;
				}
				
				&:not(.active):hover {
					transform: scale(1.05);
				}
			}
		}
	}

	.step-container {
		min-height: 100vh;
		background: #fff;
		padding: 60rpx 40rpx;
		box-sizing: border-box;
	}

	.step-header {
		margin-bottom: 60rpx;
		
		.step-title {
			font-size: 48rpx;
			font-weight: bold;
			color: #000;
			margin-bottom: 20rpx;
		}
		
		.step-progress {
			height: 6rpx;
			background: #F1F1F1;
			border-radius: 3rpx;
			
			.progress-inner {
				height: 100%;
				background: #000;
				border-radius: 3rpx;
				transition: width 0.3s;
			}
		}
	}

	.step-content {
		.step-subtitle {
			font-size: 36rpx;
			font-weight: bold;
			color: #000;
			margin-bottom: 40rpx;
		}
	}

	.avatar-section {
		display: flex;
		justify-content: center;
		margin-bottom: 60rpx;
		
		.avatar-wrapper {
			width: 180rpx;
			height: 180rpx;
			border-radius: 50%;
			overflow: hidden;
			background: #F8F8F8;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.avatar {
				width: 100%;
				height: 100%;
			}
			
			.avatar-placeholder {
				width: 60rpx;
				height: 60rpx;
				
				.camera-icon {
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	.input-section {
		margin-bottom: 40rpx;
		
		.input-label {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 20rpx;
		}
		
		.input-wrapper {
			position: relative;
			
			input {
				width: 100%;
				height: 88rpx;
				background: #F8F8F8;
				border-radius: 44rpx;
				padding: 0 30rpx;
				font-size: 28rpx;
			}
			
			.clear-icon {
				position: absolute;
				right: 30rpx;
				top: 50%;
				transform: translateY(-50%);
				width: 32rpx;
				height: 32rpx;
			}
		}
	}

	.gender-section {
		margin-bottom: 40rpx;
		
		.gender-options {
			display: flex;
			justify-content: space-between;
			
			.gender-item {
				flex: 1;
				height: 160rpx;
				background: #F8F8F8;
				border-radius: 20rpx;
				margin: 0 10rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				
				&.active {
					background: #E8FFD5;
				}
				
				.gender-icon {
					width: 60rpx;
					height: 60rpx;
					margin-bottom: 10rpx;
				}
				
				text {
					font-size: 24rpx;
					color: #333;
				}
			}
		}
	}

	.interest-section {
		.interest-tip {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 30rpx;
		}
		
		.interest-circles {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
			margin-bottom: 60rpx;
			
			.interest-circle {
				width: 140rpx;
				height: 140rpx;
				border-radius: 50%;
				background: #F8F8F8;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				color: #333;
				
				&.active {
					background: #ACF934;
					color: #000;
				}
			}
		}
	}

	.interest-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		
		.interest-tag {
			padding: 16rpx 30rpx;
			background: #F8F8F8;
			border-radius: 30rpx;
			font-size: 28rpx;
			color: #333;
			display: flex;
			align-items: center;
			
			&.active {
				background: #ACF934;
				color: #000;
			}
			
			.remove-tag {
				margin-left: 10rpx;
				font-size: 32rpx;
			}
		}
		
		.add-tag {
			padding: 16rpx 30rpx;
			background: #F8F8F8;
			border-radius: 30rpx;
			font-size: 28rpx;
			color: #666;
			display: flex;
			align-items: center;
			
			.add-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 10rpx;
			}
		}
	}

	.bottom-button {
		position: fixed;
		left: 40rpx;
		right: 40rpx;
		bottom: 40rpx;
		height: 88rpx;
		background: #000;
		border-radius: 44rpx;
		color: #fff;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		
		&.step2 {
			background: #ACF934;
			color: #000;
		}
	}
</style>