<template>
	<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="userInfo.headPortraitUrl ? userInfo.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.custName}}</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.mobile}}</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="sexShow=true">
						<text class="value" :class="userInfo.sex? '' :'placeholder'">{{columns[0][userInfo.sex] || '填选择性别'}}</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"  border="none" maxlength="24"></u--input>
						<!-- <text class="value">{{userInfo.idCard}}</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.email"  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>
						<!-- <image class="arrow-icon" :src="require('@/static/images/my/enter.png')" mode="aspectFit"></image> -->
					</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;">
		  <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 {
		getUserProfile,
		uploadAvatar,
		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 {
				dateShow: false,
				sexShow: false,
				columns: [['男', '女', '未知']],
				
				defaultFace: '/static/images/my/face.png',
				userInfo: {},
				defaultDate: Number(new Date()),
				minDate: 7200000,
				maxDate: Number(new Date())
			}
		},
		onLoad() {
			this.getUserInfo()
		},
		methods: {
			getUserInfo() {
				getUserProfile({'custId':uni.getStorageSync('custId'),"sourceType":7}).then(res => {
					this.userInfo = res.data
					console.log('this.userInfo',this.userInfo)
				})
			},
			
			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 = {
					"custId":uni.getStorageSync('custId'),
					"mobile":this.userInfo.mobile,
					"sex":this.userInfo.sex,
					"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
				}
				console.log(param)
				updateUserProfile(param).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)
						// this.headPortraitUrl = resImage.tempFilePaths[0]
						//转base64
						this.imgToBase64(resImage.tempFilePaths[0]).then(base64 => {
							console.log(base64)
							//base64上传
							this.uploadHeadImg(base64)
						}) 
					}
				});
			},
			//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,
					"custId": uni.getStorageSync('custId')
				}
				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;
	}

	.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;
				}
			}
		}
	}
</style>