<template>
	<view class="page">
		<scroll-view scroll-y class="page-scroll">
			<view class="section-card">
				<view class="section-title">基础信息</view>
				<view class="info-list">
<!--					<view class="info-item info-item&#45;&#45;form">-->
<!--						<view class="info-main">-->
<!--							<view class="info-label">登录账号</view>-->
<!--							<view class="info-value">{{ profile.username || '-' }}</view>-->
<!--						</view>-->
<!--					</view>-->
					<view class="info-item info-item--form">
						<view class="info-main">
							<view class="info-label">姓名</view>
							<uv-input
								class="info-input"
								:value="editingRealName"
								maxlength="20"
								placeholder="请输入姓名"
								placeholder-style="color: #b2a7a1;"
								border="none"
								@input="handleRealNameInput"
							/>
						</view>
					</view>
					<view class="info-item info-item--form">
						<view class="info-main">
							<view class="info-label">昵称</view>
							<uv-input
								class="info-input"
								:value="editingNickname"
								maxlength="20"
								placeholder="请输入昵称"
								placeholder-style="color: #b2a7a1;"
								border="none"
								@input="handleNicknameInput"
							/>
						</view>
						<view class="info-action" @tap="fillWechatNickname">读取微信昵称</view>
					</view>
					<view class="info-item info-item--form">
						<view class="info-main">
							<view class="info-label">性别</view>
							<picker
								mode="selector"
								:range="genderOptions"
								:value="genderIndex"
								@change="handleGenderChange"
							>
								<view class="info-input info-input--picker">
									{{ editingGender || '请选择性别' }}
								</view>
							</picker>
						</view>
					</view>
					<view class="info-item info-item--form">
						<view class="info-main">
							<view class="info-label">手机号码</view>
							<view class="info-value">{{ profile.phone || '-' }}</view>
						</view>
						<view v-if="profile.phone" class="info-action" @tap="copyText(profile.phone)">复制</view>
					</view>
				</view>
				<view class="info-actions">
					<view class="nickname-btn nickname-btn--primary" @tap="saveProfileBasic">保存基础信息</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		getCurrentUser,
		getLocalProfileOverride,
		getUserProfile,
		saveLocalProfileOverride,
		updateUserProfileData
	} from './service'

	export default {
		data() {
			return {
				editingNickname: '',
				editingRealName: '',
				editingGender: '',
				genderOptions: ['男', '女', '未知'],
				profile: {
					userId: '',
					nickname: '',
					realName: '',
					username: '',
					avatar: '',
					phone: '',
					email: '',
					organizationName: '',
					tenantName: '',
					merchantName: '',
					sexName: '',
					sex: '',
					address: '',
					province: '',
					city: '',
					region: '',
					introduction: '',
					roles: []
				}
			}
		},
		computed: {
			displayName() {
				return this.profile.nickname || this.profile.realName || this.profile.username || '未命名用户'
			},
			roleText() {
				const roles = Array.isArray(this.profile.roles) ? this.profile.roles : []
				if (roles.length) {
					return roles.map((item) => item.roleName).filter(Boolean).join(' / ')
				}
				return '暂无角色信息'
			},
			organizationText() {
				return this.profile.organizationName || this.profile.merchantName || this.profile.tenantName || '暂无组织信息'
			},
			avatarText() {
				return (this.displayName || '我').slice(0, 2)
			},
			genderIndex() {
				const index = this.genderOptions.indexOf(this.editingGender)
				return index > -1 ? index : 0
			}
		},
		onShow() {
			this.loadProfile()
		},
		onPullDownRefresh() {
			this.loadProfile(true)
		},
		methods: {
			getProfileUserId() {
				return Number(this.profile.userId || getCurrentUser().userId || 0) || ''
			},
			applyLocalProfileOverride() {
				const override = getLocalProfileOverride(this.getProfileUserId())
				if (override.nickname !== undefined) {
					this.profile = {
						...this.profile,
						nickname: String(override.nickname || '').trim()
					}
				}
				if (override.realName !== undefined) {
					this.profile = {
						...this.profile,
						realName: String(override.realName || '').trim()
					}
				}
				if (override.sex !== undefined || override.sexName !== undefined) {
					const nextGender = String(override.sexName || override.sex || '').trim()
					this.profile = {
						...this.profile,
						sex: nextGender,
						sexName: nextGender
					}
				}
				this.editingNickname = this.profile.nickname || ''
				this.editingRealName = this.profile.realName || ''
				this.editingGender = this.profile.sexName || this.profile.sex || ''
			},
			async loadProfile(fromPullDown = false) {
				try {
					const tokenUser = getCurrentUser()
					this.profile = {
						...this.profile,
						...tokenUser
					}
					const result = await getUserProfile()
					this.profile = {
						...this.profile,
						...(result || {})
					}
					this.applyLocalProfileOverride()
				} catch (error) {
					this.applyLocalProfileOverride()
					if (fromPullDown) {
						uni.showToast({
							title: (error && error.message) || '用户资料加载失败',
							icon: 'none'
						})
					}
				} finally {
					if (fromPullDown) {
						uni.stopPullDownRefresh()
					}
				}
			},
			handleNicknameInput(event) {
				const value = typeof event === 'string' ? event : (event.detail && event.detail.value) || ''
				this.editingNickname = String(value || '')
			},
			handleRealNameInput(event) {
				const value = typeof event === 'string' ? event : (event.detail && event.detail.value) || ''
				this.editingRealName = String(value || '')
			},
			handleGenderChange(event) {
				const index = Number((event.detail && event.detail.value) || 0)
				this.editingGender = this.genderOptions[index] || ''
			},
			async saveProfileBasic() {
				const nickname = String(this.editingNickname || '').trim()
				const realName = String(this.editingRealName || '').trim()
				const gender = String(this.editingGender || '').trim()
				try {
					await updateUserProfileData({
						userId: this.getProfileUserId() || undefined,
						nickname,
						realName,
						sex: gender,
						sexName: gender
					})
					this.profile = {
						...this.profile,
						nickname,
						realName,
						sex: gender,
						sexName: gender
					}
					this.editingNickname = nickname
					this.editingRealName = realName
					this.editingGender = gender
					saveLocalProfileOverride(this.getProfileUserId(), {
						nickname,
						realName,
						sex: gender,
						sexName: gender
					})
					uni.showToast({
						title: '资料已保存',
						icon: 'none'
					})
				} catch (error) {
					uni.showToast({
						title: (error && error.message) || '保存失败',
						icon: 'none'
					})
				}
			},
			fillWechatNickname() {
				// #ifdef MP-WEIXIN
				const assignNickname = (userInfo) => {
					const nickname = String((userInfo && (userInfo.nickName || userInfo.nickname)) || '').trim()
					if (!nickname) {
						uni.showToast({
							title: '未读取到微信昵称',
							icon: 'none'
						})
						return
					}
					this.editingNickname = nickname
					uni.showToast({
						title: '已读取微信昵称',
						icon: 'none'
					})
				}
				if (typeof uni.getUserProfile === 'function') {
					uni.getUserProfile({
						desc: '用于完善用户昵称',
						success: (res) => {
							assignNickname(res && res.userInfo)
						},
						fail: () => {
							uni.showToast({
								title: '未授权读取微信昵称',
								icon: 'none'
							})
						}
					})
					return
				}
				if (typeof uni.getUserInfo === 'function') {
					uni.getUserInfo({
						success: (res) => {
							assignNickname(res && res.userInfo)
						},
						fail: () => {
							uni.showToast({
								title: '读取微信昵称失败',
								icon: 'none'
							})
						}
					})
					return
				}
				uni.showToast({
					title: '当前环境不支持读取微信昵称',
					icon: 'none'
				})
				return
				// #endif
				// #ifndef MP-WEIXIN
				uni.showToast({
					title: '仅微信小程序支持读取微信昵称',
					icon: 'none'
				})
				// #endif
			},
			copyText(value) {
				uni.setClipboardData({
					data: String(value || ''),
					success: () => {
						uni.showToast({
							title: '已复制',
							icon: 'none'
						})
					}
				})
			},
			goPage(url) {
				uni.navigateTo({
					url
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background:
			radial-gradient(circle at top center, rgba(20, 150, 242, 0.1), transparent 28%),
			linear-gradient(180deg, #f5fbff 0%, #eef7ff 100%);
	}

	.page-scroll {
		height: 100vh;
		padding: 24rpx 24rpx 40rpx;
	}

	.hero-card,
	.section-card {
		border-radius: 32rpx;
		background: rgba(255, 255, 255, 0.94);
		border: 1rpx solid rgba(20, 150, 242, 0.08);
		box-shadow: 0 10rpx 28rpx rgba(34, 94, 142, 0.08);
	}

	.hero-card {
		padding: 34rpx 30rpx;
		background: linear-gradient(145deg, #0d6fba 0%, #1496f2 58%, #5bc2ff 100%);
		color: #fff;
	}

	.hero-top {
		display: flex;
		align-items: center;
	}

	.avatar-image,
	.avatar-text {
		width: 112rpx;
		height: 112rpx;
		border-radius: 32rpx;
		background: rgba(255, 255, 255, 0.16);
	}

	.avatar-text {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		font-weight: 700;
	}

	.hero-main {
		flex: 1;
		min-width: 0;
		margin-left: 22rpx;
	}

	.hero-name {
		font-size: 38rpx;
		font-weight: 700;
	}

	.hero-role,
	.hero-org {
		margin-top: 10rpx;
		font-size: 24rpx;
		line-height: 1.6;
		color: rgba(255, 255, 255, 0.84);
	}

	.hero-stats {
		display: grid;
		grid-template-columns: repeat(3, minmax(0, 1fr));
		gap: 16rpx;
		margin-top: 28rpx;
	}

	.stat-item {
		padding: 20rpx 16rpx;
		border-radius: 24rpx;
		background: rgba(255, 255, 255, 0.12);
		text-align: center;
	}

	.stat-value {
		font-size: 28rpx;
		font-weight: 700;
	}

	.stat-label {
		margin-top: 8rpx;
		font-size: 22rpx;
		color: rgba(255, 255, 255, 0.82);
	}

	.section-card {
		margin-top: 24rpx;
		padding: 26rpx;
	}

	.section-title {
		font-size: 30rpx;
		font-weight: 700;
		color: #1f2329;
	}

	.info-list {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
		margin-top: 18rpx;
	}

	.info-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 16rpx;
		padding: 20rpx 18rpx;
		border-radius: 24rpx;
		background: #faf5f2;
	}

	.info-main {
		flex: 1;
		min-width: 0;
	}

	.info-label {
		font-size: 22rpx;
		color: #8b817c;
	}

	.info-value {
		margin-top: 8rpx;
		font-size: 25rpx;
		line-height: 1.6;
		color: #2b3037;
		word-break: break-all;
	}

	.info-action {
		flex-shrink: 0;
		font-size: 22rpx;
		color: #1496f2;
	}

	.info-item--form {
		align-items: flex-start;
	}

	:deep(.info-input.uv-input) {
		width: 100%;
		height: 92rpx;
		margin-top: 12rpx;
		padding: 0 24rpx !important;
		border-radius: 24rpx;
		background: #ffffff !important;
		border: 1rpx solid #eadfd7 !important;
		box-sizing: border-box;
	}

	:deep(.info-input.uv-input .uv-input__content__field-wrapper__field) {
		font-size: 26rpx;
		color: #2b3037;
	}

	.info-input--picker {
		display: flex;
		align-items: center;
	}

	.info-actions {
		margin-top: 18rpx;
	}

	.nickname-btn {
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 22rpx;
		font-size: 24rpx;
		font-weight: 700;
		text-align: center;
	}

	.nickname-btn--ghost {
		background: #eef6ff;
		color: #1496f2;
	}

	.nickname-btn--primary {
		background: linear-gradient(135deg, #0d6fba 0%, #1496f2 100%);
		color: #fff;
	}

	.nickname-tip {
		margin-top: 14rpx;
		font-size: 22rpx;
		line-height: 1.6;
		color: #8b817c;
	}

	.bio-text {
		margin-top: 18rpx;
		font-size: 24rpx;
		line-height: 1.8;
		color: #746a65;
	}

	.quick-grid {
		display: grid;
		grid-template-columns: repeat(3, minmax(0, 1fr));
		gap: 16rpx;
		margin-top: 18rpx;
	}

	.quick-card {
		padding: 22rpx 18rpx;
		border-radius: 24rpx;
		background: #fbf6f1;
		text-align: center;
	}

	.quick-icon {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 72rpx;
		height: 72rpx;
		margin: 0 auto;
		border-radius: 22rpx;
		background: rgba(20, 150, 242, 0.1);
		color: #1496f2;
		font-size: 28rpx;
		font-weight: 700;
	}

	.quick-title {
		margin-top: 14rpx;
		font-size: 24rpx;
		font-weight: 700;
		color: #2b3037;
	}
</style>
