<template>
	<view class="login">
		<view class="u-font-xl bold-600 u-padding-top-56">获取你的昵称、头像</view>
		
		<view>
			<form @submit="doLogin">
				<view class="u-flex u-row-between avatar u-m-t-80">
					<text>头像</text>
					<view class="u-flex u-row-between flex1 u-m-l-30">
						<button
							style="border: none;"
							class="u-flex u-row-between w-full"
							hover-class="none"
							open-type="chooseAvatar"
							@chooseavatar="onChooseAvatar"
						>
							<!-- <u-image :src="cloudPath + 'img/avatar.jpeg'" width="100rpx" height="100rpx" shape="circle"></u-image> -->
							<u-image v-if="form.avatar" :src="form.avatar" width="100rpx" height="100rpx" shape="circle"></u-image>
							<view v-else="!form.avatar">点击授权头像</view>
							<u-icon name="arrow-right" color="#9F9EA4" size="32"></u-icon>
							
						</button>
					</view>
				</view>
				
				<view class="u-flex u-row-between avatar u-m-t-80">
					<text>昵称</text>
					<view class="u-flex u-row-between flex1 u-m-l-30">
						<input
							:value="form.nickname"
							name="nickname"
							type="nickname"
							placeholder="请输入昵称"
							placeholder-style="color: #000;"
						/>
						<u-icon name="arrow-right" color="#9F9EA4" size="32"></u-icon>
					</view>
				</view>
				
				<view class="menu">
					<view class="u-m-b-32" >
						<button form-type="submit" class="submit-btn" hover-class="none" :customStyle="{backgroundColor: themeColor, color: '#fff', border: 'none', padding: '16rpx 0'}" :hair-line="false" shape="circle">允许</button>
					</view>
					<u-button hover-class="none" :customStyle="{color: '#000', border: 'none', padding: '16rpx 0'}" :plain="true" :hair-line="false" shape="circle">拒绝</u-button>
				</view>
			</form>
			
			<view class="u-m-t-32 u-flex u-row-center">
				<u-checkbox v-model="form.isAgree" shape="circle" :active-color="themeColor">
				    <view class="sm row-start">
				        已阅读并同意
				        <navigator :style="{color: themeColor}" hover-class="none" url="/pages/server_explan/server_explan?type=0">
				            《服务协议》
				        </navigator>
				        和
				        <navigator :style="{color: themeColor}" hover-class="none" url="/pages/server_explan/server_explan?type=1">
				            《隐私政策》
				        </navigator>
				    </view>
				</u-checkbox>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapMutations, mapActions, mapGetters } from 'vuex'
	import { uploadFile } from "@/utils/tools";
	import {
	    authLogin,
	    updateUser
	} from '@/api/app'
	import { getWxCode, getUserInfo } from '@/utils/login'
	import { isWeixinClient, currentPage, client } from '@/utils/tools'
	import Cache from '@/utils/cache'
	import { BACK_URL } from '@/config/cachekey'
	
	export default {
		data() {
			return {
				form: {
					avatar: '',
					nickname: '',
					isAgree: false
				},
			}
		},

		methods: {
			...mapMutations(['LOGIN', 'LOGOUT']),
			...mapActions(['getUser']),
			
			// 选择头像
			onChooseAvatar(e) {
				const avatarUrl = e.detail.avatarUrl;
				if (!avatarUrl) {
					return;
				}
				uni.showLoading({
					title: "正在上传中...",
					mask: true,
				});
				uploadFile(avatarUrl).then((res) => {
					uni.hideLoading();
					this.form.avatar = res.url;
				}).catch(() => {
					uni.hideLoading();
					this.$toast({
						title: "上传失败",
					});
				});
			},
			

			// 登录
			async doLogin(e) {
				this.form.nickname = e.detail.value.nickname

				if (!this.form.isAgree) {
					this.$toast({title: '请先阅读并同意服务协议和隐私政策'})
				    return false
				}
				const {
				    userInfo: { avatarUrl, nickName, gender }
				} = await getUserInfo()

				uni.showLoading({
				    title: '登录中',
				    mask: true
				})
				
				const wxCode = await getWxCode()
				const {code, data, msg} = await authLogin({
				    code: wxCode,
				    nickname: nickName || '', //支付宝小程序没有直接获取昵称
				    headimgurl: avatarUrl,
					client
				})
				if (code == 1) {
				    if (data.is_new_user) {
						// 新用户注册，这边可以预留个邀请码
				        uni.hideLoading()
				        this.loginData = data
				
						this.handleSubmitInfo()
				    } else {
				        this.loginHandle(data)
				    }
				} else {
				    this.$toast({title: msg})
				}
			},
			
			// 更新新注册的用户信息
			async handleSubmitInfo() {
			    const loginData = this.loginData || {}
			    const res = await updateUser({
					avatar: this.form.avatar,
					nickname: this.form.nickname
				}, loginData.token)
				
			    if (res.code == 1) {
			        this.loginHandle(loginData)
			    }
			},
			
			// 登录结果处理
			async loginHandle(data) {
			    this.LOGIN(data)
			    uni.hideLoading()
			    const inviteCode = Cache.get('INVITE_CODE')
			    if (inviteCode) {
			        inputInviteCode({
			            code: inviteCode
			        })
			    }
			    // #ifdef H5
			    location.replace('/mobile' + (Cache.get(BACK_URL) || '/'))
			    Cache.remove(BACK_URL)
			    //#endif
			    // #ifndef H5
			    uni.navigateBack({
			        success() {
			            // 刷新上一页
			            const { onLoad, options } = currentPage()
			            onLoad && onLoad(options)
			        }
			    })
			    //#endif
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}
	
	.login {
		margin: 0 32rpx;
		
		.avatar text {
			font-size: 48rpx;
		}
		
		.menu {
			margin-top: 200rpx;
		}
		
		.submit-btn {
			background-color: #254062;
			border-radius: 200rpx;
			color: #fff;
			height: 81rpx;
			line-height: 81rpx;
		}
	}
</style>