<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta> 
	<view class="top-view"></view>
	<view class="center-box">
		<!-- 用户信息区域 -->
		<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>
		<!-- 我的服务区域 -->
		<!-- <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>
		</view> -->
		<u-button shape="circle" color="#3888FF" @click="onLoginOut" style="width: 90%;margin: 0 auto;height: 40px;position:absolute;bottom: 50px;left: 5%;font-size: 30rpx;">
		  退出登录
		</u-button>
	</view>
	<u-action-sheet :actions="list" :show="avatarShow" safeAreaInsetBottom closeOnClickOverlay cancelText="取消"
		round="10" @close="avatarShow = false" @select="avatarSelect"></u-action-sheet>
 
</template>

<script>
	import { getUserHeaderPhoto,saveUserHeaderPhoto,uploadAvatar,getUserInfo} from "@/api/system/user";
	import ImageCompressor from 'image-compressor.js'; 
	import Cookies from "js-cookie";   
	import { uploadBase64 } from "@/api/upload"
	import { pathToBase64, base64ToPath } from 'image-tools';
	export default {
		data() {
			return { 
				fontValue:uni.getStorageSync('fontSize') || 8,
				userName: "",
				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.getUserInfo() 
		},
		methods: {
			getUserInfo() {
				getUserInfo().then(res => {
					this.headPortraitUrl= res.user.avatar||"/static/images/my/face.png";
					this.userName = res.user.userName;
					this.phonenumber = res.user.phonenumber;
				})
			}, 
			//退出
			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)   
							 if(resImage.tempFiles[0].size>1024*1024){
								uni.showToast({
								  title: "头像图片不可大于1MB",
								  icon: 'none'
								})
							 }else{
								let data = {name: 'avatarfile', filePath: resImage.tempFilePaths[0]}
								uploadAvatar(data).then(response => {
									if(response.code==200){
										this.getUserInfo()
									} 
								})   	
							 }
								
							// this.compressFile(resImage.tempFiles[0]).then(res => { 
							// 	const compressRes = res
							// 	console.log(compressRes)
							// 	// console.log(URL.createObjectURL(compressRes))
							// 	let data = {name: 'avatarfile', filePath: compressRes}
							// 	uploadAvatar(data).then(response => {
							// 		// this.getUserInfo()
							// 	})   
							// })  
							
						}
					});
				}else if(e.val == 2) {
					//查看头像
					uni.previewImage({
						urls: [this.headPortraitUrl]
					});
				}
			},
			//图片压缩
			compressFile(file) {
			  return new Promise((resolve, reject) => {
			    const options = {
			      success(result) {
			        // 将压缩后的 Blob 转换为 File 对象（如果组件支持Blob则不用这一步）
			        const compressedFile = new File([result], file.name, {
			          type: file.type,
			          lastModified: Date.now(),
			        });
			        return resolve(URL.createObjectURL(compressedFile));
			      },
			      error(e) {
			        return reject(e);
			      },
			    };
			    // 1-3MB
			    if (file.size > 0.5 * 1024 * 1024 && file.size <= 3 * 1024 * 1024) {
			      options.quality = 0.3; // 压缩质量
			      options.convertSize = false;//不进行图像尺寸的调整
			      options.checkOrientation = false; // 图片翻转，默认为false
			    }
			    // 3-4MB
			    if (file.size > 3 * 1024 * 1024 && file.size <= 4 * 1024 * 1024) {
			      options.quality = 0.25; // 压缩质量
			      options.convertSize = false;//不进行图像尺寸的调整
			      options.checkOrientation = false; // 图片翻转，默认为false
			    }
			    // 5-6MB
			    if (file.size > 5 * 1024 * 1024 && file.size <= 6 * 1024 * 1024) {
			      options.quality = 0.2; // 压缩质量
			      options.convertSize = false;//不进行图像尺寸的调整
			      options.checkOrientation = false; // 图片翻转，默认为false
			    }
			    // 6-7MB
			    if (file.size > 6 * 1024 * 1024 && file.size <= 7 * 1024 * 1024) {
			      options.quality = 0.15; // 压缩质量
			      options.convertSize = false;//不进行图像尺寸的调整
			      options.checkOrientation = false; // 图片翻转，默认为false
			    }
			    // 7-9MB
			    if (file.size > 7 * 1024 * 1024 && file.size <= 9 * 1024 * 1024) {
			      options.quality = 0.1; // 压缩质量
			      options.convertSize = false;//不进行图像尺寸的调整
			      options.checkOrientation = false; // 图片翻转，默认为false
			    }
			    new ImageCompressor(file, options);
			  });
			}, 
			//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
				}
			},
			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"> 
	.top-view{
	 	width: 100%;
	 	height: 14vh;
	 	background: linear-gradient( 180deg, #3888FF 0%, rgba(56,136,255,0) 100%);
		position: relative;
	 }
	
	.header {
	  padding: 40rpx;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  margin-bottom: 10rpx;
	
	  .header-text {
	    font-size: 38rpx;
	    font-weight: 600;
	    color: #fff;
	  }
	}  
	.center-box{
		// margin-top: 30rpx;
		width: 100%; 
		height: 85vh;
		background: rgba(255,255,255,0.3);
		opacity: 0.8;
		border-radius: 48rpx 48rpx 0rpx 0rpx;
		border: 1px solid #fff;
		margin-top: -10vh;
		padding: 20rpx 20rpx;  
		z-index: 999999;   
	}

	.user-info {
		height: 15vh;
		display: flex;
		align-items: center;
		padding: 16px; 
		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>