<template>
	<view class="container">
		<!-- <image class="bkg" mode="aspectFill" src="@/static/order-bg.png"></image> -->
		<!-- 顶部导航 -->
		<u-navbar title="我的" :is-back="false" back-icon-color="#fff" :background="{'background':'#1479ff'}"
			title-color="#fff" :border-bottom="false"></u-navbar>
		<view class="b-border"></view>
		<view @click="showMyInfo = true" class="top">
			<image class="avatar" mode="aspectFit" :src="avatar_img || vuex_default_icon"></image>

			<view class="info">
				<view class="info-name">{{ vuex_user.name || '微信用户' }}</view>
				<view class="info-mobile">手机号：{{ vuex_user.mobile || '' }}</view>
			</view>
		</view>
		<view class="panel panel2">
			<!-- <view class="row" @click="toUrl">
				<u-icon class="row__icon" name="heart" color="#1479ff"></u-icon>
				<view>我的订单</view>
			</view> -->
			<!-- <view class="row" @click="createOrder">
				<u-icon class="row__icon" name="plus-circle" color="#1479ff"></u-icon>
				<view>新建订单</view>
			</view> -->
			<view class="row" @click="loginOut">
				<u-icon class="row__icon" name="account" color="#1479ff"></u-icon>
				<view>退出</view>
			</view>
		</view>

		<!-- 设置头像 -->
		<view class="myinfo">
			<u-popup v-model="showMyInfo" mode="bottom" :border-radius="30">
				<view class="form-wrapper">
					<u-form :model="form" ref="uForm" label-width="140rpx">
						<u-form-item label="头像">
							<button class="btn-normal" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
								<image :src="avatar_img || vuex_default_icon"></image>
							</button>
						</u-form-item>
					</u-form>
				</view>
				<!-- 操作按钮 -->
				<view class="footer">
					<view class="btn-wrapper">
						<view class="btn-item btn-item-main" @click="saveInfo">保存</view>
					</view>
				</view>
			</u-popup>
		</view>
		<TabBar :tabbarList="tabbarList" :current="currentTabIndex" :key="loginRole" />
	</view>
</template>

<script>
	import {
		ROOTPATH as baseUrl
	} from "@/common/config.js"
	import { nurseTabbar, staffTabbar,operatorTabbar } from '@/common/tabbarConfig.js'
	import TabBar from '@/components/tab-bar/tab-bar.vue'

	export default {
		components: { TabBar },
		data() {
			return {
				loginRole: uni.getStorageSync('login_role') || 'nurse',
				statusBarHeight: 40,
				showMyInfo: false,
				form: {
					avatar: ''
				},
				avatar_img: ''
			};
		},
		computed: {
			tabbarList() {
				return this.loginRole === 'nurse' ? nurseTabbar : this.loginRole === 'operator' ? operatorTabbar : staffTabbar
			},
			currentTabIndex() {
				const path = '/' + (this.$mp?.page?.route || this.$route?.path || '')
				return this.tabbarList.findIndex(item => path === item.pagePath)
			}
		},
		onLoad() {
			this.statusBarHeight = uni.getMenuButtonBoundingClientRect().top;
			this.getUserInfo()
		},
		onShow() {
			this.loginRole = uni.getStorageSync('login_role') || 'nurse'
		},
		onShareAppMessage() {
			return {
				title: '医康养服务', // 分享标题
				path: '/pages/index/index', // 分享路径，通常指向首页
			}
		},
		methods: {
			toUrl() {
				// uni.navigateTo({
				// 	url: '/package_sub/order/order'
				// })

			},
			loginOut() {
				let that = this
				uni.showModal({
					content: "是否确认退出？",
					success(res) {
						if (res.confirm) {
							// 获取登录角色
							const loginRole = uni.getStorageSync('login_role')
							// 根据角色选择不同的登出接口
							let logoutApi = null
							switch(loginRole) {
								case 'nurse':
									logoutApi = that.$u.api.loginOut  // 护工登出
									break
								case 'staff':
									logoutApi = that.$u.api.staffLogout  // 工作人员登出
									break
								case 'operator':
									logoutApi = that.$u.api.operatorLogout  // 运营人员登出
									break
								default:
									that.base.toast("无效的角色信息")
									return
							}
							
							logoutApi().then(res => {
								that.base.toast("退出成功", 1500, function() {
									setTimeout(() => {
										// 清除所有缓存
										uni.removeStorageSync('lifeData')
										uni.removeStorageSync('login_role')  // 清除角色缓存
										uni.redirectTo({
											url: '/package_sub/login/login'
										})
									}, 1500)
								})
							}).catch(err => {
								console.error("登出失败", err)
								that.base.toast("登出失败，请稍后重试")
							})
						}
					}
				})
			},
			createOrder() {
				uni.navigateTo({
					url: '/package_sub/order/service'
				})
			},
			onChooseAvatar(e) {
				console.log(e)
				// 获取登录角色
				const loginRole = uni.getStorageSync('login_role')
				// 根据角色选择不同的上传接口
				let uploadUrl = ''
				switch(loginRole) {
					case 'nurse':
						uploadUrl = baseUrl + "/api/nurse/upload-file"  // 护工上传
						break
					case 'staff':
						uploadUrl = baseUrl + "/api/worker/upload-file"  // 工作人员上传
						break
					case 'operator':
						uploadUrl = baseUrl + "/api/admin/upload-file"  // 运营人员上传
						break
					default:
						uni.showToast({
							title: '无效的角色信息',
							icon: 'none'
						})
						return
				}
				
				let a = uni.uploadFile({
					url: uploadUrl,
					filePath: e.detail.avatarUrl,
					name: 'file',
					header: {
						['Authorization']: `Bearer ${this.vuex_token}`
					},
					success: (res) => {
						uni.showToast({
							title: '上传成功',
							duration: 1000,
							icon: 'none'
						})
						console.log("res", res)
						let data = JSON.parse(res.data)
						this.form.avatar = data.id
					},
					fail: (err) => {
						console.error("上传失败", err)
						uni.showToast({
							title: '上传失败，请稍后重试',
							icon: 'none'
						})
					}
				})
			},
			async saveInfo() {
				let that = this
				if (this.base.isNull(this.form.avatar)) {
					this.base.toast("请上传头像")
					return
				}
				
				// 获取登录角色
				const loginRole = uni.getStorageSync('login_role')
				// 根据角色选择不同的保存接口
				let saveApi = null
				switch(loginRole) {
					case 'nurse':
						saveApi = this.$u.api.saveUser  // 护工保存
						break
					case 'staff':
						saveApi = this.$u.api.saveStaffUser  // 工作人员保存
						break
					case 'operator':
						saveApi = this.$u.api.saveOperatorUser  // 运营人员保存
						break
					default:
						uni.showToast({
							title: '无效的角色信息',
							icon: 'none'
						})
						return
				}
				
				try {
					const res = await saveApi({
						avatar: that.form.avatar,
						id:this.vuex_user.id
					})
					that.base.toast('更新成功', 1000, function() {
						setTimeout(function() {
							that.showMyInfo = false
							that.getUserInfo()
						}, 1000)
					})
				} catch (err) {
					console.error("保存失败", err)
					uni.showToast({
						title: '保存失败，请稍后重试',
						icon: 'none'
					})
				}
			},
			async getUserInfo() {
				// 获取登录角色
				const loginRole = uni.getStorageSync('login_role')
				// 根据角色选择不同的获取用户信息接口
				let userApi = null
				switch(loginRole) {
					case 'nurse':
						userApi = this.$u.api.getUser  // 护工信息
						break
					case 'staff':
						userApi = this.$u.api.getStaffUser  // 工作人员信息
						break
					case 'operator':
						userApi = this.$u.api.getOperatorUser  // 运营人员信息
						break
					default:
						uni.showToast({
							title: '无效的角色信息',
							icon: 'none'
						})
						return
				}
				
				try {
					const user = await userApi()
					this.form.avatar = user.avatar ? user.avatar : ''
					this.avatar_img = user.avatar_detail ? user.avatar_detail.url : ''
					this.$u.vuex('vuex_user', user)
				} catch (err) {
					console.error("获取用户信息失败", err)
					uni.showToast({
						title: '获取用户信息失败',
						icon: 'none'
					})
				}
			}
		},

	}
</script>

<style lang="scss">
	.container {
		min-height: 100vh;
		position: relative;
		background: #f5f5f5;
		font-size: 32rpx;

		.bkg {
			width: 100vw;
			z-index: 0;
			height: 686rpx;
			position: absolute;
			top: 0;
			left: 0;
		}

		.b-border {
			width: 100%;
			height: 30rpx;
			border-radius: 0 0 120rpx 120rpx;
			background-color: #1479ff;
		}

		.top {
			display: flex;
			align-items: center;
			position: relative;
			background: #fff;
			border-radius: 20rpx;
			margin: 30rpx;
			box-shadow: 0 4rpx 16rpx #e6eaf1;
			padding: 30rpx;

			.avatar {
				width: 100rpx;
				height: 100rpx;
				border-radius: 80rpx;
			}

			.info {
				padding-left: 40rpx;

				&-name {
					line-height: 2;
					font-weight: 600;
				}
			}
		}

		.panel {
			position: relative;
			background: #fff;
			border-radius: 10rpx;
			margin: 40rpx 25rpx 0;
			padding: 28rpx 25rpx;
		}

		.panel2 {
			.row {
				display: flex;
				padding: 20rpx 10rpx;
				border-bottom: 2rpx #dee2e6 solid;

				&__icon {
					margin-right: 20rpx;
					color: $uni-color-primary;
					font-size: 36rpx;
				}
			}
		}

		.form-wrapper {
			margin: 20rpx auto 20rpx auto;
			padding: 0 40rpx;
			width: 94%;
			box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
			border-radius: 16rpx;
			background: #fff;

			.btn-normal {
				display: block;
				margin: 0;
				padding: 0;
				line-height: normal;
				background: none;
				border-radius: 0;
				box-shadow: none;
				border: none;
				font-size: unset;
				text-align: unset;
				overflow: visible;
				color: inherit;

				image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 100%;
					border: 2px solid #fff;
					margin-right: 30rpx;
				}
			}

			.btn-normal::after {
				border: none
			}
		}

		.footer {
			margin-top: 80rpx;
			margin-bottom: 40rpx;

			.btn-wrapper {
				height: 100%;
				// display: flex;
				// align-items: center;
				padding: 0 20rpx;
			}

			.btn-item {
				flex: 1;
				font-size: 28rpx;
				height: 86rpx;
				color: #fff;
				border-radius: 50rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.btn-item-main {
				background: #d61b24;
				color: #fff;
			}
		}
	}
</style>