<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
	<view class="container">
		<!-- 顶部导航栏 -->
		<!--    <view class="header">-->
		<!--      <view class="back-icon" @click="goBack">-->
		<!--        <image class="icon" :src="require('@/static/images/icons/back.png')" mode="aspectFit"></image>-->
		<!--      </view>-->
		<!--      <text class="title">基本信息</text>-->
		<!--    </view>-->

		<!-- 个人信息表单 -->
		<view class="form-container">
			<!-- 头像区域 -->
			<view class="avatar-section" @click="handleUpdateAvatar">
				<image class="avatar" :src="headPortraitUrl ? headPortraitUrl : defaultFace" mode="aspectFill"></image>
				<view class="camera-icon">
					<image class="icon" :src="require('@/static/images/my/camera.png')" mode="aspectFit"></image>
				</view>
			</view>

			<!-- 信息列表 -->
			<view class="info-list">
				<!-- 姓名 -->
				<view class="info-item">
					<text class="label">姓名</text>
					<view class="value-wrapper">
						<text class="value">{{userInfo.nickName}}</text>
						<image class="arrow-icon" :src="require('@/static/images/my/enter.png')" mode="aspectFit"></image>
					</view>
				</view>

				<!-- 手机号 -->
				<view class="info-item">
					<text class="label">手机号</text>
					<view class="value-wrapper">
						<uni-easyinput v-model="userInfo.phonenumber" :inputBorder="false" :clearable="false"  placeholder="请输入手机号" maxlength="11" color="#333" class="fs32" style="text-align: right;" />
						<image class="arrow-icon" :src="require('@/static/images/my/enter.png')" mode="aspectFit"></image>
					</view>
				</view>
				
				<!-- 性别 -->
				<!-- <view class="info-item">
					<text class="label">性别</text>
					<view class="value-wrapper" @click="sexShow=true">
						<text class="value" :class="userInfo.sex? '' :'placeholder'">{{userInfo.sexStr || '填选择性别'}}</text>
						<image class="arrow-icon" :src="require('@/static/images/my/enter.png')" mode="aspectFit"></image>
					</view>
				</view> -->

				<!-- 生日 -->
				<view class="info-item">
					<text class="label">出生年月</text>
					<view class="value-wrapper" @click="selectBirthDay()">
						<text class="value" :class="userInfo.birthday? '' :'placeholder'">{{userInfo.birthday || '填写出生年月完善信息'}}</text>
						<image class="arrow-icon" :src="require('@/static/images/my/enter.png')" mode="aspectFit"></image>
					</view>
				</view>
				
				<!-- 年龄 -->
				<!-- <view class="info-item">
					<text class="label">年龄</text>
					<view class="value-wrapper">
						<text class="value">{{userInfo.age}}</text>
						<image class="arrow-icon" :src="require('@/static/images/my/enter.png')" mode="aspectFit"></image>
					</view>
				</view> -->
				
				<!-- 身份证号码 -->
				<!-- <view class="info-item">
					<text class="label">身份证号码</text>
					<view class="value-wrapper">
						  <u--input v-model="userInfo.idCard" style="font-size: 32rpx;color: #333;"  border="none" maxlength="24"></u--input>
					</view>
				</view> -->
				<!-- 邮箱 -->
				<!-- <view class="info-item">
					<text class="label">邮箱</text>
					<view class="value-wrapper"> 
						 <u--input v-model="userInfo.email" style="font-size: 32rpx;color: #333;" border="none" maxlength="30"></u--input>
					</view>
				</view> -->
				<!-- 地址 -->
				<!-- <view class="info-item">
					<text class="label">地址</text>
					<view class="value-wrapper"> 
						<u--input v-model="userInfo.homeAddr"  border="none" maxlength="30"></u--input>
					</view>
				</view> -->
				
				
			</view>
			<!-- 性别 -->
			<u-picker :show="sexShow" :columns="columns" @confirm="confirm"></u-picker>
			<u-datetime-picker :minDate="minDate" :maxDate="maxDate" :show="dateShow" v-model="defaultDate" mode="date"
				:closeOnClickOverlay="true" :formatter="formatter" @cancel="dateShow = false" @confirm="birthDayConfirm">
			</u-datetime-picker>
		</view>
	
		<!-- 提交按钮 -->
		<view style="padding: 20rpx 30rpx;margin-top: 20px;position:absolute;bottom: 5vh;width: 100%;">
		  <u-button
		    text="保存"
		    shape="squrd"
			@click="saveUserInfo"
		    :customStyle="{
		      width: '100%',
		      height: '88rpx',
		      background: '#ffa361',
		      color: '#ffffff',
		      border: 'none'
		    }"
		  ></u-button>
		</view>
	
	</view>
</template>

<script>
	
	import { 
		uploadAvatar,
		getUserProfile,
		getUserInfo,
		updateUserProfile,
		saveUserHeaderPhoto
	} from "@/api/system/user"
	import config from '@/config'
	import { uploadBase64 } from "@/api/upload"
	import { pathToBase64, base64ToPath } from 'image-tools';
	import {
		getToken
	} from '@/utils/auth'
	import {
		showConfirm
	} from '@/utils/common'
	export default {
		data() {
			return {
				fontValue:uni.getStorageSync('fontSize') || 8,
				headPortraitUrl:"",
				dateShow: false,
				sexShow: false,
				columns: [['男', '女', '未知']], 
				defaultFace: '/static/images/my/face.png',
				userInfo: {},
				defaultDate: Number(new Date()),
				minDate: 7200000,
				maxDate: Number(new Date())
			}
		},
		onLoad() {
			this.getUserInfoData()
			this.getUserHead()
		},
		methods: {
			getUserInfoData() { 
				getUserProfile().then(res => {
					this.userInfo = res.data;
					this.userInfo.postIds = res.postIds||[]
					this.userInfo.roleIds = res.roleIds||[]
					console.log('this.userInfo',this.userInfo) 
				}) 
			},
			getUserHead() {
				getUserInfo().then(res => {
					this.headPortraitUrl= res.user.avatar
				})
			},
			goBack() {
				uni.navigateBack()
			},
			navigateTo(url) {
				uni.navigateTo({
					url
				})
			},
			//性别选中
			confirm(e) {
				console.log('confirm', e)
				this.userInfo.sex=e.indexs[0];
				this.userInfo.sexStr = e.value[0]
				this.sexShow = false
			},
			//出生年月选中
			selectBirthDay() {
				this.dateShow = true
			},
			saveUserInfo(){
				console.log(this.userInfo)
				// let param = {
				// 	"userId":uni.getStorageSync('userId'),
				// 	"phonenumber":this.userInfo.phonenumber,
				// 	"sex":this.userInfo.sex+1,
				// 	"birthday":this.userInfo.birthday,
				// 	"age":this.userInfo.age,
				// 	"idCard":this.userInfo.idCard, 
				// 	"email":this.userInfo.email,
				// 	"homeAddr":this.userInfo.homeAddr,
				// 	"pwd":uni.getStorageSync('pwd'),
				// 	"sourceType":7
				// } 
				if (!/^1[3456789]\d{9}$/.test(this.userInfo.phonenumber)) { 
				   uni.showToast({
					  title: '请输入正确的手机号',
					  icon: 'none'
						});
					 return false;
				} 
				updateUserProfile(this.userInfo).then(res => {
					if(res.code==200){
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
						setTimeout(()=>{
							uni.navigateBack()
						},800)
					}
				})
			},
			birthDayConfirm(e) {
				this.userInfo.birthday = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				// this.getAge(this.userInfo.birthday)
				this.dateShow = false;
			},
			getAge(vl) {
			  if (vl) {
				let birthdays = new Date(vl.replace(/-/g, "/"));
				let d = new Date();
				let age =
				  d.getFullYear() -
				  birthdays.getFullYear() -
				  (d.getMonth() < birthdays.getMonth() ||
				  (d.getMonth() == birthdays.getMonth() &&
					d.getDate() < birthdays.getDate())
					? 1
					: 0); 
				this.userInfo.age = age;
			  }
			},
			
			handleUpdateAvatar() {
				//上传头像
				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.getUserHead()
								} 
							})   	
						}
					}
				});
			},
			//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.getUserInfo()
				}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)
						})
			  })
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
		}
	}
</script>

<style lang="scss">
	.container {
		min-height: 100vh;
		background-color: #FBFCFF;
		position: relative;
	}

	.form-container {
		padding: 32rpx;
		background-color: #FBFCFF;
	}

	.avatar-section {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		margin: 50rpx auto 48rpx;

		.avatar {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}

		.camera-icon {
			position: absolute;
			right: 0;
			bottom: 0;
			width: 48rpx;
			height: 48rpx;
			background: #fff;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

			.icon {
				width: 32rpx;
				height: 32rpx;
			}
		}
	}

	.info-list {
		background: #fff;
		border-radius: 16rpx;

		.info-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 32rpx;
			border-bottom: 1rpx solid #FFFFFF;

			&:last-child {
				border-bottom: none;
			}

			.label {
				font-size: 32rpx;
				color: #333;
			}

			.value-wrapper {
				display: flex;
				align-items: center;

				.value {
					font-size: 32rpx;
					color: #333;
					margin-right: 16rpx;

					&.placeholder {
						color: #999;
					}
				}

				.arrow-icon {
					width: 32rpx;
					height: 32rpx;
				}
			}
		}
	}
	
	.fs32{
		& :nth-child(1){
			font-size: 32rpx;
		}
		& :nth-child(2){
			font-size: 32rpx;
		}
	}
</style>