<template>
	<view class="container">
		<uni-section title="基础信息" type="line">
			<uni-forms ref="infoForm" :rules="rules" :modelValue="formData" :label-width="90">
				<uni-forms-item required label="姓名" name="name">
					<uni-easyinput type="text" v-model="formData.name" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item required label="性别" name="sex">
					<uni-data-checkbox v-model="formData.sex" :localdata="sexs" />
				</uni-forms-item>
				<uni-forms-item required label="手机号" name="phone">
					<view class="phoneBox">
						<uni-easyinput disabled type="text" v-model="formData.phone" placeholder="手机号" />
						<button type="primary" :plain="true" style="border: none;"  size="mini" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">获取手机号</button>
					</view>
				</uni-forms-item>
				<uni-forms-item name="birthday" label="出生日期">
					<uni-datetime-picker type="date" v-model="formData.birthday" />
				</uni-forms-item>
			</uni-forms>
		</uni-section>
		<button class="btn" type="primary" @click="submit('infoForm')">提交</button>
	</view>
</template>

<script>
	import request from '../../api/user.js';
	import requestLogin from '../../api/login.js';
	const appid = uni.getAccountInfoSync().miniProgram.appId;
	export default {
		data() {
			return {
				role: '',
				path: null,
				formData: {},
				sexs: [
					{ text: '男', value: 1 },
					{ text: '女', value: 0 },
				],
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					sex: {
						rules: [{
							required: true,
							errorMessage: '性别不能为空'
						}]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '电话不能为空'
						}]
					},
				},
			}
		},
		async mounted() {
			this.role = uni.getStorageSync('role');
			if (this.role !== 'guest') this.queryInfo();
		},
		methods: {
			async queryInfo() {
				const userinfo = await request.getUser();
				// const userinfo = uni.getStorageSync('userinfo');
				this.formData = userinfo.data;
			},
			// 获取手机号
			async decryptPhoneNumber(e) {
				const res = await requestLogin.getPhone({ code: e.detail.code, appid: appid });
				this.$set(this.formData, 'phone', res.phone_info.phoneNumber);
			},
			// 提交
			async submit(ref) {
				this.$refs[ref].validate(async (err, formdata) => {
					if (!err) {
						// 修改用户
						const res = await request.updateUser(this.formData);
						uni.showToast({
							title: '修改成功',
							duration: 2000,
						});
						uni.navigateBack()
					}
				})
			},
		},
		onLoad(option) {
			this.path == option.path;
		}
	}
</script>

<style>
	.uni-section {
		padding-bottom: 10px;
		margin-bottom: 10px;
	}
	.uni-forms, .btn {
		width: 90%;
		margin: 10px auto;
	}
	.phoneBox {
		display: flex;
	}
</style>
