<template>
	<view>
		<view class="u-m-t-34" @tap="chooseAvatar">
			<view class="row-center">
				<u-avatar v-if="userInfo.avatar" :src="userInfo.avatar" size="142"></u-avatar>
				<u-icon v-if="!userInfo.avatar" name="account-fill" size="142"></u-icon>
			</view>
			<view class="nr text-default u-text-center u-m-t-16">
				点击更换头像
			</view>
		</view>
		
		<view class="u-m-l-62 u-m-r-62">
			<view class="nr row-between u-col-center u-m-t-48" @tap="changeName">
				<view style="width: 100rpx;">昵称</view>
				<view class="flex1 u-m-l-80 row u-row-between u-col-center">
					<view>{{userInfo.nickname || ''}}</view>
					<view>
						<u-image :src="cloudPath + 'img/icon_arrow_right.png'" width="44" height="44"></u-image>
					</view>
				</view>
			</view>
			
			<!-- <view class="nr row-between u-col-center u-m-t-48" @tap="changeMobile">
				<view style="width: 100rpx;">手机号</view>
				<view class="flex1 u-m-l-80 row u-row-between u-col-center">
					<view>{{formatPhone(userInfo.mobile)}}</view>
					<view>
						<u-image :src="cloudPath + 'img/icon_arrow_right.png'" width="44" height="44"></u-image>
					</view>
				</view>
			</view> -->
		</view>
		
		<view class="fixed left-0 right-0 save">
			<u-button @click="save" hover-class="none" :customStyle="{backgroundColor: themeColor, color: '#fff', border: 'none', padding: '16rpx 0'}" :hair-line="false" shape="circle">保存</u-button>
		</view>
		
		<!-- 昵称修改组件 -->
		<u-popup
		    v-model="nickname.showPopup"
		    mode="center"
		    border-radius="16"
		>
			<view class="bg-white br16 w-full" style="width: 70vw;">
				<view class="u-p-32">
					<view class="title xl u-text-center bold-500">修改用户名</view>
					<view>
						<u-form :model="nickname" ref="nicknameForm">
							<u-form-item label="昵称" :border-bottom="false">
								<u-input v-model="nickname.value" value="请输入新的昵称"/>
							</u-form-item>
							<u-button @click="confirmChangeNickeName" hover-class="none" :customStyle="{backgroundColor: themeColor, color: '#fff', border: 'none', padding: '16rpx 0'}" :hair-line="false" shape="circle">确定</u-button>
						</u-form>
					</view>
				</view>
			</view>
		</u-popup>
		
		<mplogin v-model="mp.showPopup" :info-type="mp.type" @close="mp.showPopup = false" @update="handleSubmitInfo"/>
		<mobile-login v-model="mobile.showPopup" @close="mobile.showPopup = false" :hideCancleBtn="false" @update="updateMobile"/>
	</view>
</template>

<script>
	import { changeUserMobile, getUserInfo, setUserInfo, setWechatInfo } from '@/api/user'
	import { uploadFile, isWeixinClient, trottle } from '@/utils/tools'
	import { mapState, mapGetters } from 'vuex'
	const FieldType = {
		NONE: '',
	    NICKNAME: 'nickname',
	    AVATAR: 'avatar',
	    MOBILE: 'mobile'
	}
	
	export default {
		data() {
			return {
				fieldType: FieldType.NONE,
				userInfo: {},
				nickname: {
					value: '',
					showPopup: false
				},
				mobile: {
					showPopup: false,
				},
				mp: {
					showPopup: false,
					type: ''
				}
			}
		},
		onUnload() {
		    uni.$off('uAvatarCropper')
		},
		
		onLoad(){
			this.getUserInfo()
			uni.$on('uAvatarCropper', (path) => {
			    this.uploadImage(path)
			})

			console.log("🚀 ~ onLoad ~ userInfo:", this.userInfo)
		},
		
		methods: {
			// 修改头像
			chooseAvatar() {
				this.fieldType = FieldType.AVATAR
				// uni.$u.route({
				//     // 关于此路径，请见下方"注意事项"
				//     url: '/components/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
				//     // 内部已设置以下默认参数值，可不传这些参数
				//     params: {
				//         // 输出图片宽度，高等于宽，单位px
				//         destWidth: 300,
				//         // 裁剪框宽度，高等于宽，单位px
				//         rectWidth: 300,
				//         // 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
				//         fileType: 'jpg'
				//     }
				// })

				// 选择头像
				this.mp.showPopup = true
				this.mp.type = 'avatar'
			},
			
			// 修改昵称
			changeName() {
			    this.fieldType = FieldType.NICKNAME
			    // this.nickname.value = ''
				// this.nickname.showPopup = true
				
				// 选择昵称
				this.mp.showPopup = true
				this.mp.type = 'nickname'
			},
			
			// 确认修改昵称
			async confirmChangeNickeName() {
				if (!this.nickname.value) {
					return this.$toast({
					    title: '请输入新的昵称'
					})
				}
				
				await this.setUserInfo(this.nickname.value)
				this.nickname.showPopup = false
			},
			
			// 修改手机号
			changeMobile() {
				this.fieldType = FieldType.MOBILE
				this.mobile.showPopup = true
			},
			
			// 更新手机号码
			async updateMobile(e) {
				if (!e.mobile) {
					return this.$toast({
					    title: '请授权获取您的手机号'
					})
				}
				
				await this.setUserInfo(e.mobile)
				this.nickname.showPopup = false
			},
			
			// 上传头像
			uploadImage(path) {
			    uni.showLoading({
			        title: '正在上传中...',
			        mask: true
			    })
			    uploadFile(path).then((res) => {
					uni.hideLoading()
					this.setUserInfo(res.url)
				}).catch(() => {
					uni.hideLoading()
					this.$toast({title: '上传失败'})
				})
			},
			
			// 修改个人信息
			async setUserInfo(value) {
				const res = await setUserInfo({
					field: this.fieldType,
					value: value
				})
				if (res.code == 1) {
					this.$toast({
						title: res.msg
					})
					
					this.getUserInfo()
				}
			},
			
			// 获取个人信息
			getUserInfo() {
			    getUserInfo().then((res) => {
			        if (res.code == 1) {
			            this.userInfo = res.data
			        }
			    })
			},
			
			// 格式化手机号
			formatPhone(p) {
				if (p) {
					return p.substring(0, 3) + '****' + p.substring(7)
				}
				return ''
			},
			
			handleSubmitInfo(e) {
				if (this.mp.type === 'avatar') {
					this.setUserInfo(e.avatar)
				} else if (this.mp.type === 'nickname') {
					this.setUserInfo(e.nickname)
				}
			},

			save() {
				uni.switchTab({
					url: '/pages/my/my'
				})
			},
		},
		computed: {
			...mapState(['token']),
			...mapGetters(['appConfig'])
		}
	}
</script>

<style lang="scss">
	page{
		background-color: #fff;
	}
	
	.save {
		bottom: calc(52rpx + env(safe-area-inset-bottom));
		height: 76rpx;
		background-color: #212526;
		color: #fff;
		border-radius: 100rpx;
		margin: 0 64rpx;
	}
</style>