<template>
	<view class="content">
		<view class="one">
			<uni-forms ref="valiForm" :rules="rules" :modelValue="form" labelWidth="80px">
				<uni-forms-item label="新密码" required name="newpassword">
					<uni-easyinput type="password" v-model="form.newpassword" placeholder="请输入新密码" />
				</uni-forms-item>
				<uni-forms-item label="确认密码" required name="password">
					<uni-easyinput type="password" v-model="form.password" placeholder="请输入确认密码" />
				</uni-forms-item>
			</uni-forms>
			<button class="button" type="primary" @click="submit('valiForm')">确认</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {},
				// 校验规则
				rules: {
					newpassword: [{
						required: true,
						errorMessage: '新密码不能为空'
					}]
				},
				password: [{
					required: true,
					errorMessage: '确认密码不能为空'
				}]
			}
		},
		async onLoad() {
			const that = this;
			await that.searchToken();
		},
		methods: {
			async searchToken() {
				const that = this;
				uni.getStorage({
					key: 'token',
					success: function(res) {
						that.$set(that, `form`, res.data);
					},
					fail: function(err) {
						uni.showToast({
							title: err.errmsg,
							icon: 'error',
							duration: 2000
						});
					}
				})
			},
			// 确认修改
			submit(ref) {
				const that = this;
				that.$refs[ref].validate().then(async params => {
					if (that.form.newpassword == that.form.password) {
						let form = {
							_id: that.form._id,
							password: that.form.password
						}
						const res = await that.$api(`/User/rp`, 'POST', form);
						if (res.errcode == '0') {
							uni.showToast({
								title: '修改信息成功',
								icon: 'none'
							})
							that.toExit()
						} else {
							uni.showToast({
								title: res.errmsg,
								icon: 'none'
							})
						}
					} else {
						uni.showToast({
							title: '输入密码不一致 请重新输入',
							icon: 'none'
						})
					}
				}).catch(err => {
					console.log('err', err);
				})
			},
			// 退出登录
			toExit() {
				uni.removeStorage({
					key: 'token',
					success: function(res) {
						let url = `/pages/index/index`;
						uni.reLaunch({
							url
						})
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		flex-direction: column;

		.one {
			padding: 3vw;

			.button {
				margin: 2vw 0 0 0;
				background-color: var(--f3CColor);
				color: var(--mainColor);
				font-size: var(--font14Size);
			}
		}
	}
</style>
