<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="email" label="企业邮箱" required>
				<uni-easyinput v-model="formData.email" placeholder="请输入企业邮箱"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="code" label="验证码" required>
				<uni-easyinput v-model="formData.code" :inputBorder="false" placeholder="请输入邮箱验证码">
					<template v-slot:right>
            <button class="login-code" @tap.stop="handleCode">
              {{ getSmsTimer('resetPassword') }}
            </button>
          </template>
				</uni-easyinput>
			</uni-forms-item>
			<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, emailRequired } from '@/utils/validate'
import { resetPassword } from '@/api/enterprise'
import { getEmailCode, getSmsTimer } from '@/utils/code'

const formRef = ref(null)
const formData = ref({
	email: null,
	code: null,
	password: null,
	passwordConfirm: null
})
const formRules = {
	email: emailRequired,
	code: {
		rules: [
			{ required: true, errorMessage: '请输入邮箱验证码' },
		]
	},
	password,
	passwordConfirm: {
		rules: [
			{ required: true, errorMessage: '请再次输入密码' },
			{ 
				validateFunction: function(rule, value, data, callback) {
					if (value !== data.password) callback('两次输入的密码不一致')
					return true
				}
			}
		]
	}
}

// 获取邮箱验证码
const handleCode = async () => {
  if (!formData.value.email) {
    uni.showToast({
      title: '请输入您的企业邮箱',
      icon: 'none',
      duration: 2000
    })
    return
  }
	getEmailCode('resetPassword', formData.value.email)
}

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

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

<style scoped lang="scss">
.login-code {
  width: 73px;
  min-width: 73px;
  color: #00B760;
  text-align: center; 
  font-size: 12px; 
  cursor: pointer;
  padding: 0;
}
</style>
