<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
	<view class="container">
		<!-- 顶部标题 -->
		<!-- <view class="header">
      <text class="title">我的</text>
    </view> -->

		<!-- 用户信息区域 -->
		<view class="user-info">
			<view class="avatar-wrapper">
				<image class="avatar" @click="avatarClick()" :src="headPortraitUrl" mode="aspectFill" @error="avatarError"></image>
			</view>
			<view class="user-detail">
				<view class="username">{{userName}}</view>
				<view class="phone">{{phonenumber}}</view>
			</view>
			<view class="star-icon" @click="goCollectPage">
				<uni-icons type="star" size="24" color="#ff9900"></uni-icons>
			</view>
		</view>
		<!-- 余额 -->
		<!-- <view class="services">
			<text class="services-title">我的余额</text>
			<view style="width: 100%;display: flex;height: 10vh;align-items: center;">
				<view style="display: flex;align-items: center;width: 50%;height: 100%;justify-content: center;">
					<text style="font-size: 40rpx;color: #333;margin-right: 6rpx;">¥</text>
					<text style="font-size: 48rpx;font-weight: 700;color: #FF6816;">{{ (accountAllBal/100).toFixed(2) }}</text>
					<text style="font-size: 28rpx;color: #333;margin-left: 6rpx;">元</text>
				</view>
				<view style="border: 1px solid #ccc;height: 60%;"></view>
				<view style="display: flex;align-items: center;width: 45%;height: 100%;justify-content: center;">
					<u-button shape="squrd" color="#fff" @click="getWalletBalance" style="width: 60%;margin: 0 auto;height: 40px;font-size: 30rpx;border-color: #176faa;color: #176faa;">
					  查询余额
					</u-button>
				</view>
			</view>
		</view> -->

		<!-- 我的服务区域 -->
		<view class="services">
			<text class="services-title">我的服务</text>
			<view class="grid-container"> 
				<!-- 个人信息 -->
				<view class="grid-item" @click="navigateTo('/pages/mine/me/index')">
					<view class="icon-wrapper">
						<image style="width: 120rpx;height: 120rpx;" src="/static/images/my/personalInfo.png"></image>
					</view>
					<text class="icon-text">个人信息</text>
				</view> 
				<!-- 通知公告 -->
				<view class="grid-item" @click="navigateTo('/pages/mine/announcement/index')">
					<view class="icon-wrapper">
						<image style="width: 120rpx;height: 120rpx;" src="/static/images/my/notice.png"></image>
					</view>
					<text class="icon-text">通知公告</text>
				</view> 
				<!-- 投诉建议 -->
				<view class="grid-item" @click="navigateTo('/pages/feedback/index')">
					<view class="icon-wrapper">
						<image style="width: 120rpx;height: 120rpx;" src="/static/images/my/complaints.png"></image>
					</view>
					<text class="icon-text">投诉建议</text>
				</view>
				<!-- 食堂评价 -->
				<view class="grid-item" @click="navigateTo('/pages/review/index')">
					<view class="icon-wrapper"> 
						<image style="width: 120rpx;height: 120rpx;" src="/static/images/my/evaluation.png"></image>
					</view>
					<text class="icon-text">食堂评价</text>
				</view>
				<!-- 体检报告 -->
				<view class="grid-item" @click="navigateTo('/pages/survey/index')">
					<view class="icon-wrapper"> 
						<image style="width: 120rpx;height: 120rpx;" src="/static/images/my/report.png"></image>
					</view>
					<text class="icon-text">健康监测</text>
				</view>
				<!-- 营养科普 -->
				<view class="grid-item" @click="navigateTo('/pages/mine/healthScience/index')">
					<view class="icon-wrapper"> 
						<image style="width: 120rpx;height: 120rpx;" src="/static/images/my/complaints.png"></image>
					</view>
					<text class="icon-text">营养科普</text>
				</view>

				
			</view>
		</view>
		
		<u-button shape="circle" color="#FF6816" @click="onLoginOut" style="width: 90%;margin: 0 auto;height: 40px;position:absolute;bottom: 50px;left: 5%;font-size: 30rpx;">
		  退出登录
		</u-button>
		
		<u-action-sheet :actions="list" :show="avatarShow" safeAreaInsetBottom closeOnClickOverlay cancelText="取消"
			round="10" @close="avatarShow = false" @select="avatarSelect"></u-action-sheet>
	</view>
</template>

<script>
	import { getUserHeaderPhoto,saveUserHeaderPhoto,uploadAvatar,} from "@/api/system/user";
	import { getWalletBalanceAPI } from "@/api/mine/index.js";
	import Cookies from "js-cookie";
	import config from '@/config'
	import { getToken } from '@/utils/auth'
	import { showConfirm } from '@/utils/common'
	import { uploadBase64 } from "@/api/upload"
	import { pathToBase64, base64ToPath } from 'image-tools';
	export default {
		data() {
			return { 
				fontValue:uni.getStorageSync('fontSize') || 8,
				userName: uni.getStorageSync('userName')||"",
				phonenumber: uni.getStorageSync('phonenumber')||"",
				headPortraitUrl:"/static/images/my/face.png",
				defaultImg: '/static/images/my/face.png',
				avatarShow: false,
				list: [{
					name: '上传头像',
					val: 1
				}, {
					name: '查看头像',
					val: 2
				}],
				accountAllBal: 0 ,// 钱包余额
			}
		},
		onLoad() {
			// this.getWalletBalance()
		},
		methods: {
			// 获取钱包余额
			async getWalletBalance(userId) {
				let param = {
					"userId": uni.getStorageSync('userId'),  
				}
			  const { data: res } = await getWalletBalanceAPI(param)
			  this.accountAllBal = res.accountAllBal
			  console.log(res, '余额信息--')
			},
			
			//退出
			onLoginOut() {
				this.$modal.confirm('确定注销并退出系统吗？').then(() => {
					Cookies.remove('token')
					Cookies.remove('App-Token')
					uni.removeStorageSync('token')
					uni.removeStorageSync('App-Token') 
					uni.reLaunch({ url: '/pages/login' })
				  // this.$store.dispatch('LogOut').then(() => {
					 //  Cookies.remove('token')
					 //  Cookies.remove('App-Token')
					 //  uni.reLaunch({ url: '/pages/login' })
				  // })
				})
			},
			avatarClick() {
				this.avatarShow = true
			},
			avatarSelect(e) {
				if (e.val == 1) {
					//上传头像 
					uni.chooseImage({//选择图片
						count: 1,
						success: resImage => {
							console.log(resImage)
							// this.headPortraitUrl = resImage.tempFilePaths[0]
							//转base64
							this.imgToBase64(resImage.tempFilePaths[0]).then(base64 => {
								console.log(base64)
								//base64上传
								this.uploadHeadImg(base64)
							}) 
						}
					});
				}else if(e.val == 2) {
					//查看头像
					uni.previewImage({
						urls: [this.headPortraitUrl]
					});
				}
			},
			//base64上传
			uploadHeadImg(base64){
				let param = {
					"MERCHANT-ID":"378915229716713472",
					"uploadKey":'cust',
					"base64File":base64
				}
				uploadBase64(param).then(res => {
					console.log(res)
					if(res.code==200){
						this.saveHeadImg(res.data) 
					}else{
						uni.showToast({
						  title: res.msg,
						  icon: 'none'
						}) 
					}
				}) 
			},
			//头像保存接口
			async saveHeadImg(data){
				console.log(data)
				let param = {
					"headPortraitUrl": data.fileNameUrl,
					"userId": uni.getStorageSync('userId')
				}
				console.log(param) 
				const res = await saveUserHeaderPhoto(param)
				console.log(res)
				if(res.code==200){
					uni.showToast({
					  title: "上传成功",
					  icon: 'none'
					})
					this.getUserHeaderImg()
				}else{
					uni.showToast({
					  title: res.msg,
					  icon: 'none'
					}) 
				}
				
			},
			imgToBase64(data) {
			  return new Promise((resolve, reject) => {
						pathToBase64(data).then(base64 => {
							resolve(base64)
						}).catch(error => {
							console.error(error)
							reject(error)
						})
			  })
			},
			getUserHeaderImg() {
				getUserHeaderPhoto({"userId":uni.getStorageSync('userId'),"sourceType": "7"}).then(res => {
					console.log(res)
					this.headPortraitUrl=res.headPortraitUrl;
					if(!this.headPortraitUrl) {
						this.headPortraitUrl = this.defaultImg
					}  
				})
			},
			avatarError(e) {
				console.log(e)
				if (e.type == 'error') {
					this.headPortraitUrl = this.defaultImg
				}
			},
			goCollectPage(){ 
				uni.navigateTo({url: "/pages/mine/collect/index"})
			},
			navigateTo(url) {
				uni.navigateTo({
					url
				})
			}
		},
		// onUnload() {
		// 	uni.switchTab({
		// 	  url: '/pages/index'
		// 	})
		// },
		// onBackPress(e) {
		// 	//e.from === 'backbutton' 说明如果点击的是物理返回键或导航栏的返回键就进行以下操作
		// 	if (e.from === 'backbutton') {
		// 	  //返回值为true 时,表示不执行默认的返回（默认返回上一页），执行自定义的返回
		// 	  uni.switchTab({
		// 	    url: '/pages/index'
		// 	  })
		// 	  //如果要限制必须写成true
		// 	  return true;
		// 	}
		// }
	}
</script>

<style lang="scss">
	.container {
		height: 96vh;
		background-color: #F9FBFF;
		// padding-top: 3vh;
	}

	.header {
		padding: 14px 16px 16px;
		background: #F9FBFF;

		.title {
			font-size: 36rpx;
			font-weight: 500;
			color: #333;
		}
	}

	.user-info {
		height: 20vh;
		display: flex;
		align-items: center;
		padding: 16px;
		background: #fff;
		margin-bottom: 20px;

		.avatar-wrapper {
			margin-right: 30rpx;

			.avatar {
				width: 80px;
				height: 80px;
				border-radius: 40px;
			}
		}

		.user-detail {
			flex: 1;

			.username {
				margin-left: 15px;
				font-size: 36rpx;
				font-weight: 600;
				color: #333;
			}
			.phone{
				margin-left: 15px;
				margin-top:15px;
				color: #787878;
			}
		}

		.star-icon {
			padding: 8px;
		}
	}

	.services {
		background: #fff;
		padding: 16px;
		height: auto;
		margin-bottom: 20px;

		.services-title {
			font-size: 32rpx;
			color: #333;
			margin-bottom: 26px;

			font-weight: 400;
		}

		.grid-container {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20px;

			.grid-item {
				display: flex;
				flex-direction: column;
				align-items: center;

				.icon-wrapper {
					// width: 48px;
					// height: 48px;
					//border-radius: 24px;
					//background: #f5f5f5;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-bottom: 3px;
				}

				.icon-text {
					font-size: 28rpx;
					color: #0F274B;
				}
			}
		}
	}
</style>