<template>
<view class="p-t-30">
	<u-cell-group :customStyle="{backgroundColor:'white'}">
		<u-cell title="头像">
			<button slot="value" open-type="chooseAvatar" @chooseavatar="chooseAvatar">
				<view class="flex-dir-row flex-y-center">
					<u-avatar :src="face" size="60"/>
					<view class="m-l-10">
						<u-icon name="arrow-right" color="#c8c9cc"/>
					</view>
				</view>
			</button>
		</u-cell>
		<u-cell title="昵称">
			<view slot="value">
				<u--input v-model="nickName" type="nickname" color="#c8c9cc" inputAlign="right" border="none"/>
			</view>
		</u-cell>
		<!-- <u-cell>
			<view slot="title">
				<u-icon name="reload" :color="$u.color['primary']"
					label="随机头像" :labelColor="$u.color['primary']" @click="randomFace"/>
			</view>
			<view slot="value">
				<u-icon name="reload" :color="$u.color['primary']"
					label="随机昵称" :labelColor="$u.color['primary']" @click="randomName"/>
			</view>
		</u-cell> -->
	</u-cell-group>
	<view class="width-100 k-btn">
		<view class="p-30">
			<u-button text="保存" :color="edited?'black':'#c8c9cc'" :disabled="!edited" shape="circle" @click="save"/>
		</view>
	</view>
	<bt-timer ref="timer"/><!-- 一定要加ref=timer，mixins里会用到 -->
</view>
</template>

<script>

export default {
	mixins: [],
	data() {
		return {
			face: '',
			nickName: '',
			edited: false, //是否更改
		}
	},
	watch: {//监听头像或昵称任何一个发生变动
		face(newValue, oldValue) {
			if (oldValue && newValue != oldValue) {
				this.edited = true
			}
		},
		nickName(newValue, oldValue) {
			if (oldValue && newValue != oldValue) {
				this.edited = true
			}
		},
	},
	methods: {
		chooseAvatar(e) {
			this.$u.api.putFile(e.detail.avatarUrl).then(res => {
				this.face = res.data.link
			})
		},
		randomName() {
			this.$u.api.getRandomName().then(res => {
				this.nickName = res.data
			})
		},
		randomFace() {
			this.$u.api.getRandomAvatar().then(res => {
				this.face = res.data
			})
		}, 
		save() {
			if (!this.edited) {
				return
			}
			this.$u.api.saveNicknameAndAvatar(this.nickName, this.face).then(res => {
				this.$u.vuex('userInfo.avatar', this.face) //写入缓存
				this.$u.vuex('userInfo.nick_name', this.nickName) //写入缓存
				uni.$u.toast('保存成功')
				this.edited = false
				uni.$emit('refreshUser', this.face, this.nickName)//要特别调用父页面的方法，不然父页面不同步
			})
		},
	},
	onLoad() {
		this.face = this.userInfo.avatar || '/static/images/face.png'
		this.nickName = this.userInfo.nick_name || ''
	},
}
</script>

<style>
.k-btn {
	position: absolute;
	bottom: 30%;
}
button[open-type=chooseAvatar] {
	background-color: white;
	padding: 0;
}
</style>
