<template>
	<view>
		<u-navbar title="编辑个人资料">
			<view class="slot-wrap" @click="submit">
				保存
			</view>	
		</u-navbar>
		<view class="data">
			<view class="data-img">
				<view class="data-icon">
					<u-icon name="camera-fill"  color="#fff" size="32"></u-icon>
				</view>
				<img v-if="form.headImg" :src="form.headImg" style="width: 160rpx;" alt="">
				
				<u-avatar v-else  size="160" ></u-avatar>
			</view>
			<view class="change"  @click="uploadPhoto" >
				点击更换头像
			</view>
			
			<view class="nickname">
				<view class="title">
					昵称
				</view>
				<view class="input">
					<input type="text" placeholder="修改昵称"  v-model="form.name" >
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import * as API from '@/apis/pagejs/user.js'
	import * as API_common from '@/apis/common.js'
	
	export default {
		data() {
			return {
				plusInfo:{},
				userInfo:{},
				form:{},
			}
		},
		onLoad() {
			this.plusInfo=this.carhelp.getPersonInfoPlus();
			this.userInfo=this.carhelp.getPersonInfo();
			this.form={
				name:this.userInfo.name,
				headImg:this.userInfo.headImg
			}
			
		},
		methods: {
			submit() {
				uni.showLoading({
					title: "加载中",
					mask: true,
				})		
				API.changeData(this.form).then((res) => {
					uni.hideLoading();
					this.userInfo.name=this.form.name
					this.userInfo.headImg=this.form.headImg
					this.carhelp.setPersonInfo(this.userInfo);
					uni.showToast({
						title: "提交成功",
						icon: "none"
					})
				}).catch(error => {
					uni.showToast({
						title: error,
						icon: "none"
					})
				})
			},
			uploadPhoto() {
				let _self = this;
				
				const crop = {
					quality: 100,
					width: 600,
					height: 600,
					resize: true
				};
				
				// 上传图片
				uni.chooseImage({
					count: 1,
					crop,
					success: async (res) => {
						//(res);
						let tempFile = res.tempFiles[0],
							avatar_file = {
								// #ifdef H5
								extname: tempFile.name.split('.')[tempFile.name.split('.').length - 1],
								// #endif
								// #ifndef H5
								extname: tempFile.path.split('.')[tempFile.path.split('.').length - 1]
								// #endif
							},
							filePath = res.tempFilePaths[0]
							
						// #ifndef APP-PLUS
						//(`filePath=${filePath}`)
						
						//非app端用前端组件剪裁头像，app端用内置的原生裁剪
						let fileData = await new Promise((callback) => {
							uni.navigateTo({
								url: '/pages/mine/cropImage?path=' + filePath +
									`&options=${JSON.stringify(crop)}`,
								animationType: "fade-in",
								events: {
									success: url => {
										callback(url)
									}
								}
							});
						})
						// #endif
						
						
						function dataURLtoBlob(dataurl){
						    var arr = dataurl.split(','),
						      mime = arr[0].match(/:(.*?);/)[1],
						      bstr = atob(arr[1]),
						      n = bstr.length,
						      u8arr = new Uint8Array(n);
						    while (n--) {
						      u8arr[n] = bstr.charCodeAt(n);
						    }
						    return new Blob([u8arr], { type: mime });
						  }
						  //2,再将blob转换为file
						function  blobToFile(theBlob, fileName){
						     theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
						     theBlob.name = fileName;                // 文件名
						     return new File([theBlob], fileName, {type: theBlob.type, lastModified: Date.now()});
						  }
						  
						  
						  var blob= dataURLtoBlob(fileData)
						  var file= blobToFile(blob,parseInt(Math.random()*100000000)+'.jpg')
						  console.log(file)
						  
						//返回 base64 图片
						//(fileData);
					var formData = new FormData();
					
					formData.append('subFolder', "headimg");
					
					formData.append('photoFile', file);
					var token=this.carhelp.getToken()
						
						uni.uploadFile({
								 url: process.car.BASE_URL + "uploadPicture",//仅为示例，非真实的接口地址
									files: [{
										name:"photoFile",
										file:file
									}],
									header: {
									    'Authorization': token,
										//'Content-Type': 'multipart/form-data',
										'X-Requested-With': 'XMLHttpRequest',
									//	'content-type': 'multipart/form-data'
									},
									name: 'file',
									formData: {
										subFolder:"headimg"
									},
									success: (uploadFileRes) => {
										
										
										var obj=JSON.parse(uploadFileRes.data)
										console.log(obj);
										 _self.form.headImg = obj.data.fileUrl;
												
										// uni.hideLoading();
									}
								});
					
					 
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	page{
		background-color: #fff;
		font-family: 'Regular';
	}
	/deep/.u-slot-content {
		display: block;
		text-align: right !important;
		margin-right: 16px;
		color: rgba(31, 74, 153, 1);
		font-size: 16px;
	}
	.data-icon{
		height: 56rpx;
		width: 56rpx;
		background-color: #4E8DF6;
		border-radius: 14px;
		border: 2px solid #fff;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		z-index: 999;
		right: 0;
		bottom:0;
		
		
	}
	.data-img{
		margin: 40rpx auto 16rpx;
		height: 160rpx;
		width: 160rpx;
		position: relative;
	}
	
	.change{
		color: rgba(31, 74, 153, 1);
		text-align: center;
	}
	
	.nickname{
		margin-top: 40rpx;
		display: flex;
		justify-content: space-between;
		padding: 0 30rpx;
		height: 88rpx;
		line-height: 88rpx;
		border-bottom: 1px solid rgba(244, 244, 244, 1);
		uni-input{
			line-height: 88rpx;
			height: 88rpx;
		     text-align: right;
			 color: #888888;
			 font-family: Microsoft Yahei;
		}
	}
</style>
