<template>
	<view class="page">
		<scroll-view scroll-y class="page-scroll">
			<common-hero title="用户资料" :use-image-bg="true" :reduce-top="24"></common-hero>

			<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"
								type="nickname"
								:value="editingNickname"
								maxlength="20"
								placeholder="请输入昵称"
								placeholder-style="color: #b2a7a1;"
								border="none"
								@input="handleNicknameInput"
							/>
						</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-input info-input--picker" @tap="openOrganizationPicker">
								{{ editingOrganizationName || '请选择所属组织机构' }}
							</view>
						</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 v-if="organizationPickerVisible" class="organization-mask" @tap="closeOrganizationPicker">
			<view class="organization-panel" @tap.stop>
				<view class="organization-head">
					<view class="organization-title">选择所属组织机构</view>
					<view class="organization-close" @tap="closeOrganizationPicker">关闭</view>
				</view>
				<input
					v-model="organizationKeyword"
					class="organization-search"
					type="text"
					placeholder="搜索组织机构"
					placeholder-style="color: #b2a7a1;"
				/>
				<scroll-view scroll-y class="organization-scroll">
					<view v-if="filteredOrganizationTree.length" class="organization-tree">
						<view
							v-for="item in filteredOrganizationTree"
							:key="item.value"
							class="organization-tree-node"
						>
							<view
								class="organization-item"
								:class="{ 'organization-item--active': String(item.value) === String(editingOrganizationId) }"
								:style="{ paddingLeft: `${20 + item.level * 28}rpx` }"
							>
								<view class="organization-item-main" @tap="selectOrganization(item)">
									<view class="organization-item-name">{{ item.rawLabel || item.text }}</view>
								</view>
								<view
									v-if="item.children && item.children.length"
									class="organization-item-toggle"
									@tap.stop="toggleOrganizationNode(item.value)"
								>
									{{ isOrganizationExpanded(item.value) ? '收起' : '展开' }}
								</view>
							</view>
						</view>
					</view>
					<view v-else class="organization-empty">没有匹配的组织机构</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import CommonHero from '../components/common-hero/common-hero.vue'
	import {
		getCurrentUser,
		getLocalProfileOverride,
		getUserProfile,
		listOrganizations,
		saveLocalProfileOverride,
		updateUserProfileData
	} from '../pages/mine/service'

	export default {
		components: {
			CommonHero
		},
		data() {
			return {
				editingNickname: '',
				editingRealName: '',
				editingGender: '',
				editingOrganizationId: '',
				editingOrganizationName: '',
				genderOptions: ['男', '女', '未知'],
				organizationTree: [],
				organizationPickerVisible: false,
				organizationKeyword: '',
				organizationExpandedMap: {},
				profile: {
					userId: '',
					nickname: '',
					realName: '',
					username: '',
					avatar: '',
					phone: '',
					email: '',
					organizationId: '',
					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
			},
			filteredOrganizationTree() {
				const keyword = String(this.organizationKeyword || '').trim().toLowerCase()
				const source = Array.isArray(this.organizationTree) ? this.organizationTree : []
				if (!keyword) {
					return this.flattenVisibleOrganizationTree(source)
				}
				const filteredTree = this.filterOrganizationTree(source, keyword)
				return this.flattenVisibleOrganizationTree(filteredTree, true)
			}
		},
		onShow() {
			this.loadProfile()
			this.loadOrganizationOptions()
		},
		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
					}
				}
				if (override.organizationId !== undefined || override.organizationName !== undefined) {
					this.profile = {
						...this.profile,
						organizationId: override.organizationId || '',
						organizationName: String(override.organizationName || '').trim()
					}
				}
				this.editingNickname = this.profile.nickname || ''
				this.editingRealName = this.profile.realName || ''
				this.editingGender = this.profile.sexName || this.profile.sex || ''
				this.editingOrganizationId = this.profile.organizationId || ''
				this.editingOrganizationName = this.profile.organizationName || ''
			},
			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()
					}
				}
			},
			async loadOrganizationOptions() {
				try {
					const organizationList = await listOrganizations()
					if (!Array.isArray(organizationList) || !organizationList.length) {
						this.organizationTree = []
						this.organizationExpandedMap = {}
						return
					}
					this.organizationTree = this.buildOrganizationTree(organizationList)
					this.organizationExpandedMap = this.buildOrganizationExpandedMap(this.organizationTree, this.editingOrganizationId)
					if (this.editingOrganizationId && !this.editingOrganizationName) {
						const matched = this.findOrganizationNodeByValue(this.organizationTree, this.editingOrganizationId)
						if (matched) {
							this.editingOrganizationName = this.buildOrganizationLabel(this.organizationTree, this.editingOrganizationId)
						}
					}
				} catch (error) {
					this.organizationTree = []
					this.organizationExpandedMap = {}
				}
			},
			normalizeOrganizationNode(item) {
				return {
					text: item.organizationName || item.name || item.label || '',
					value: Number(item.organizationId || item.id || item.value || 0) || String(item.organizationId || item.id || item.value || ''),
					rawLabel: item.organizationName || item.name || item.label || '',
					parentId: Number(item.parentId || item.parentID || item.pid || 0) || 0,
					children: []
				}
			},
			buildOrganizationTree(list) {
				const source = Array.isArray(list) ? list : []
				const nodeMap = {}
				source.forEach((item) => {
					const normalized = this.normalizeOrganizationNode(item)
					if (normalized.text && normalized.value !== '') {
						nodeMap[String(normalized.value)] = normalized
					}
				})
				const roots = []
				Object.keys(nodeMap).forEach((key) => {
					const current = nodeMap[key]
					const parentKey = String(current.parentId || 0)
					if (current.parentId && nodeMap[parentKey]) {
						nodeMap[parentKey].children.push(current)
					} else {
						roots.push(current)
					}
				})
				return roots
			},
			findOrganizationNodeByValue(list, targetValue) {
				const source = Array.isArray(list) ? list : []
				const normalizedTarget = String(targetValue || '')
				for (let index = 0; index < source.length; index += 1) {
					const item = source[index]
					if (String(item.value) === normalizedTarget) {
						return item
					}
					if (Array.isArray(item.children) && item.children.length) {
						const matched = this.findOrganizationNodeByValue(item.children, targetValue)
						if (matched) {
							return matched
						}
					}
				}
				return null
			},
			findOrganizationPathNodes(list, targetValue, path = []) {
				const source = Array.isArray(list) ? list : []
				const normalizedTarget = String(targetValue || '')
				for (let index = 0; index < source.length; index += 1) {
					const item = source[index]
					const nextPath = path.concat(item)
					if (String(item.value) === normalizedTarget) {
						return nextPath
					}
					if (Array.isArray(item.children) && item.children.length) {
						const matched = this.findOrganizationPathNodes(item.children, targetValue, nextPath)
						if (matched) {
							return matched
						}
					}
				}
				return null
			},
			buildOrganizationLabel(list, targetValue) {
				const pathNodes = this.findOrganizationPathNodes(list, targetValue) || []
				return pathNodes.map((item) => item.rawLabel || item.text).filter(Boolean).join(' / ')
			},
			buildOrganizationExpandedMap(list, targetValue) {
				const expandedMap = {}
				const pathNodes = this.findOrganizationPathNodes(list, targetValue) || []
				pathNodes.forEach((item) => {
					expandedMap[String(item.value)] = true
				})
				return expandedMap
			},
			filterOrganizationTree(list, keyword) {
				return (Array.isArray(list) ? list : [])
					.map((item) => {
						const children = this.filterOrganizationTree(item.children || [], keyword)
						const text = String(item.rawLabel || item.text || '').toLowerCase()
						if (text.includes(keyword) || children.length) {
							return {
								...item,
								children
							}
						}
						return null
					})
					.filter(Boolean)
			},
			flattenVisibleOrganizationTree(list, forceExpand = false, level = 0) {
				const result = []
				;(Array.isArray(list) ? list : []).forEach((item) => {
					result.push({
						...item,
						level
					})
					const shouldExpand = forceExpand || this.isOrganizationExpanded(item.value)
					if (shouldExpand && Array.isArray(item.children) && item.children.length) {
						result.push(...this.flattenVisibleOrganizationTree(item.children, forceExpand, level + 1))
					}
				})
				return result
			},
			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] || ''
			},
			openOrganizationPicker() {
				if (!this.organizationTree.length) {
					uni.showToast({
						title: '暂无组织机构数据',
						icon: 'none'
					})
					return
				}
				this.organizationKeyword = ''
				this.organizationPickerVisible = true
			},
			closeOrganizationPicker() {
				this.organizationPickerVisible = false
			},
			isOrganizationExpanded(value) {
				return !!this.organizationExpandedMap[String(value)]
			},
			toggleOrganizationNode(value) {
				const key = String(value)
				this.organizationExpandedMap = {
					...this.organizationExpandedMap,
					[key]: !this.organizationExpandedMap[key]
				}
			},
			selectOrganization(item) {
				this.editingOrganizationId = item.value
				this.editingOrganizationName = this.buildOrganizationLabel(this.organizationTree, item.value)
				this.closeOrganizationPicker()
			},
			async saveProfileBasic() {
				const nickname = String(this.editingNickname || '').trim()
				const realName = String(this.editingRealName || '').trim()
				const gender = String(this.editingGender || '').trim()
				const organizationId = this.editingOrganizationId
				const organizationName = String(this.editingOrganizationName || '').trim()
				try {
					await updateUserProfileData({
						userId: this.getProfileUserId() || undefined,
						nickname,
						realName,
						sex: gender,
						sexName: gender,
						organizationId,
						organizationName
					})
					this.profile = {
						...this.profile,
						nickname,
						realName,
						sex: gender,
						sexName: gender,
						organizationId,
						organizationName
					}
					this.editingNickname = nickname
					this.editingRealName = realName
					this.editingGender = gender
					this.editingOrganizationId = organizationId
					this.editingOrganizationName = organizationName
					saveLocalProfileOverride(this.getProfileUserId(), {
						nickname,
						realName,
						sex: gender,
						sexName: gender,
						organizationId,
						organizationName
					})
					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;
		min-height: 92rpx;
		margin-top: 12rpx;
		padding: 0 24rpx;
		border-radius: 24rpx;
		background: #ffffff;
		border: 1rpx solid #eadfd7;
		box-sizing: border-box;
		font-size: 26rpx;
		color: #2b3037;
	}

	.organization-mask {
		position: fixed;
		inset: 0;
		z-index: 99;
		background: rgba(44, 28, 23, 0.28);
		display: flex;
		align-items: flex-end;
	}

	.organization-panel {
		width: 100%;
		max-height: 76vh;
		padding: 28rpx 24rpx calc(24rpx + env(safe-area-inset-bottom));
		border-radius: 32rpx 32rpx 0 0;
		background: #fff;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
	}

	.organization-head {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 16rpx;
	}

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

	.organization-close {
		padding: 10rpx 18rpx;
		border-radius: 18rpx;
		background: rgba(20, 150, 242, 0.08);
		color: #1496f2;
		font-size: 24rpx;
	}

	.organization-search {
		width: 100%;
		height: 88rpx;
		margin-top: 20rpx;
		padding: 0 24rpx;
		border-radius: 24rpx;
		background: #ffffff;
		border: 1rpx solid #eadfd7;
		box-sizing: border-box;
		font-size: 26rpx;
		color: #2b3037;
	}

	.organization-scroll {
		flex: 1;
		min-height: 0;
		margin-top: 20rpx;
	}

	.organization-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 16rpx;
		padding: 10rpx 20rpx;
		border-radius: 22rpx;
		//background: #faf5f2;
	}

	.organization-item + .organization-item {
		margin-top: 14rpx;
	}

	.organization-item--active {
		background: rgba(20, 150, 242, 0.08);
		border: 1rpx solid rgba(20, 150, 242, 0.22);
	}

	.organization-item-name {
		font-size: 25rpx;
		line-height: 1.6;
		color: #2b3037;
		word-break: break-all;
	}

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

	.organization-item-toggle {
		flex-shrink: 0;
		padding: 8rpx 16rpx;
		border-radius: 999rpx;
		background: rgba(20, 150, 242, 0.08);
		font-size: 22rpx;
		color: #1496f2;
	}

	.organization-empty {
		padding: 56rpx 0 32rpx;
		text-align: center;
		font-size: 24rpx;
		color: #8b817c;
	}

	.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>
