<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="content">
			<!-- 上传区域 -->
			<view class="upload-area" @click="handleChooseImage">
				<view class="upload-box" :class="{ 'has-image': facePhotoUrl }">
					<image v-if="facePhotoUrl" :src="facePhotoUrl" mode="aspectFill" class="preview-image" />
					<view v-else class="upload-placeholder">
						<image class="camera-icon" :src="require('@/static/images/my/camera.png')" mode="aspectFill"></image>
						<text class="upload-text">点击上传照片</text>
					</view>
				</view>
			</view>

			<!-- 提示信息 -->
			<view class="tips">
				<text class="tip-item">·五官端正，面部无遮挡（请使用人脸照片）</text>
				<text class="tip-item">·不要带饰品（如墨镜等）</text>
				<text class="tip-item">·请在光线明亮的纯色背景下拍照（建议背景颜色为白色）</text>
				<text class="tip-item">·上传照片后需保存，保存失败照片将被清除</text>
			</view> 

			<!-- 按钮组 -->
			<view class="button-group">
				<button class="submit-btn" :disabled="!agreed || !imageUrl" @click="handleUpload">确定上传</button>
				<button class="cancel-btn" @click="goBack">取消</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { queryFacePhotoApi,uploadPhotoGenCodeForAppApi } from '@/api/mine/index'
	import { getInfo,getInfoByUserId } from "@/api/login.js"
	import { uploadBase64 } from "@/api/upload" 
	import { pathToBase64, base64ToPath } from 'image-tools';
	import config from '@/config'
	import { getToken } from '@/utils/auth'
	import { showConfirm } from '@/utils/common'
	
	export default {
		data() {
			return {
				fontValue:uni.getStorageSync('fontSize') || 8,
				facePhotoUrl:"",
				imageUrl: '',
				agreed: true,
				userInfo: {},
				faceData:{}
			}
		},
		onLoad() {
			// this.getFacePhoto()
			this.getUserInfo()
		},
		methods: { 
			getFacePhoto(){
				queryFacePhotoApi({"userId":uni.getStorageSync('userId')}).then(res => {
					console.log(res)
					this.facePhotoUrl = res.facePhotoUrl
				})
			},
			getUserInfo() {
				getInfoByUserId().then(res => {
					this.userInfo = res.data;
					this.userInfo.postIds = res.postIds||[]
					this.userInfo.roleIds = res.roleIds||[]
					this.facePhotoUrl = this.userInfo.photoUrl 
				})
			}, 
			goBack() {
				uni.navigateBack()
			}, 
			handleChooseImage() {
				uni.chooseImage({ 
					count: 1,
					success: resImage => {
						console.log(resImage)
						console.log(config.baseUrl)
						this.facePhotoUrl = resImage.tempFilePaths[0]
						this.imageUrl = resImage.tempFilePaths[0]
						uni.uploadFile({
							url: config.baseUrl+`/file/upload`, //服务器地址 
							filePath: this.imageUrl,
							formData: {
								"fileType":'face', 
							},
							header: {
								'Authorization': 'Bearer ' + getToken(), 
							},
							success: (uploadFileRes) => {
								let res = JSON.parse(uploadFileRes.data)
								console.log(uploadFileRes)
								if(res.code==200){
									this.faceData.fileNameUrl = res.data.url 
								}else{
									uni.$u.toast('上传失败');
								}
							},
							fail: err => {
								uni.$u.toast('上传失败');
								console.log(err)
							}
						}); 
						 
						// this.imgToBase64(resImage.tempFilePaths[0]).then(base64 => {
						// 	console.log(base64) 
						// 	this.base64=base64; 
						// 	this.uploadFaceImg()
						// }) 
					}
				});
			},
			//确认按钮
			handleUpload() {
				console.log(this.imageUrl)
				if (!this.agreed || !this.imageUrl) return 
				uni.showLoading({
					title: '上传中...'
				})
				this.userInfo.photoUrl = this.faceData.fileNameUrl
				console.log(this.userInfo) 
				// let param = {
				// 	"userId": uni.getStorageSync('userId'),
				// 	"photoUrl": this.faceData.fileNameUrl
				// }
				uploadPhotoGenCodeForAppApi(this.userInfo).then(res => {
					console.log(res)
					if(res.code==200){
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'success'
						});
					} 
				})
			},
			//base64上传
			imgToBase64(data) {
			  return new Promise((resolve, reject) => {
				pathToBase64(data)
				  .then(base64 => {
					resolve(base64)
				  })
				  .catch(error => {
					console.error(error)
					reject(error)
				  })
			  })
			},
			//base64上传
			uploadFaceImg(){
				let param = {
					"MERCHANT-ID":"378915229716713472",
					"uploadKey":'face',
					"base64File":this.base64
				}
				uploadImg(param).then(res => {
					console.log(res)
					if(res.code==200){
						this.faceData = res.data
					}else{
						this.faceData = {}
					}
				}) 
			}
		}
	}
</script>

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

	.header {
		padding: 44px 32rpx 0;
		height: 88rpx;
		display: flex;
		align-items: center;

		.back-icon {
			padding: 20rpx;
			margin-left: -20rpx;

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

		.title {
			flex: 1;
			text-align: center;
			font-size: 34rpx;
			font-weight: 500;
			color: #333;
			margin-right: 60rpx;
		}
	}

	.content {
		padding: 32rpx;
	}

	.upload-area {
		margin-bottom: 48rpx;

		.upload-box {
			width: 75%;
			height: 400rpx;
			border: 2rpx dashed #CCCCCC;
			border-radius: 16rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			overflow: hidden;
			margin: 0 auto;
		}

		&.has-image {
			border-style: solid;
		}

		.preview-image {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		.upload-placeholder {
			display: flex;
			flex-direction: column;
			align-items: center;

			.camera-icon {
				width: 80rpx;
				height: 80rpx;
				margin-bottom: 16rpx;
			}

			.upload-text {
				font-size: 28rpx;
				color: #999;
			}
		}
	}


	.tips {
		margin-bottom: 48rpx;
		width: 75%;
		margin-left: auto;
		margin-right: auto;

		.tip-item {
			display: block;
			font-size: 24rpx;
			color: #999;
			line-height: 1.6;
			text-align: left;
		}
	}

	.privacy-agreement {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 48rpx;

		/deep/ .uni-checkbox-input {
			border-radius: 50% !important;
		}
	}

	.button-group {
		margin-top: 32rpx;

		.submit-btn {
			width: 100%;
			height: 88rpx;
			background: #FF8126;
			color: #fff;
			font-size: 32rpx;
			font-weight: 500;
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: none;
			margin-bottom: 24rpx;

			&:disabled {
				opacity: 0.5;
			}

			&:active {
				opacity: 0.9;
			}
		}

		.cancel-btn {
			width: 100%;
			height: 88rpx;
			background: #fff;
			color: #333;
			font-size: 32rpx;
			font-weight: 500;
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: 2rpx solid #CCCCCC;

			&:active {
				background: #f5f5f5;
			}
		}
	}
</style>