<template>
	<view style="padding: 30rpx;">
		<uni-forms ref="formRef" :modelValue="formData" :rules="formRules" validateTrigger="bind" label-width="80px" label-align="right" label-position="left">
			<uni-forms-item name="password" label="新密码" required>
				<uni-easyinput v-model="formData.password" type="password" placeholder="请输入新密码"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="passwordConfirm" label="二次确认" required>
				<uni-easyinput v-model="formData.passwordConfirm" type="password" placeholder="请再次输入新密码"></uni-easyinput>
			</uni-forms-item>
		</uni-forms>

		<button class="send-button" @tap="handleSubmit">提 交</button>
	</view>
</template>

<script setup>
import { ref, unref } from 'vue'
import { password } from '@/utils/validate'
import { userStore } from '@/store/user'
import { entUpdatePassword } from '@/api/enterprise'

const user = userStore()
const formRef = ref(null)
const formData = ref({
	id: user?.userInfo?.id,
	password: null,
	passwordConfirm: null
})
const formRules = {
	password,
	passwordConfirm: {
		rules: [
			{ required: true, errorMessage: '请再次输入密码' },
			{ 
				validateFunction: function(rule, value, data, callback) {
					if (value !== data.password) callback('两次输入的密码不一致')
					return true
				}
			}
		]
	}
}

// 提交
const handleSubmit = async () => {
	const valid = await unref(formRef).validate()
	if (!valid) return

	uni.showLoading({ title: '提交中' })
	try {
		await entUpdatePassword(formData.value)
		uni.hideLoading()
		uni.showToast({
			title: '修改成功',
			icon: 'success'
		})
		setTimeout(() => {
			uni.navigateBack({ delta: 1 })
		}, 1000)
	} catch {
		uni.hideLoading()
	}
}
</script>

<style scoped lang="scss">

</style>
