<template>
	<view class="form-page">
		<view class="form-card">
			<view class="form-row">
				<text class="form-row__label form-row__label--req">旧密码</text>
				<input
					v-model="form.oldPassword"
					class="form-row__input"
					type="password"
					placeholder="请输入当前密码"
				/>
			</view>
			<view class="form-row">
				<text class="form-row__label form-row__label--req">新密码</text>
				<input
					v-model="form.newPassword"
					class="form-row__input"
					type="password"
					placeholder="至少 6 位"
				/>
			</view>
			<view class="form-row">
				<text class="form-row__label form-row__label--req">确认密码</text>
				<input
					v-model="form.confirmPassword"
					class="form-row__input"
					type="password"
					placeholder="再次输入新密码"
				/>
			</view>
		</view>
		<view class="form-footer">
			<button class="form-footer__btn" :disabled="saving" @click="handleSave">
				{{ saving ? '提交中…' : '确认修改' }}
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { changeMemberPassword } from '@/api/member'
import { ensureApiToken } from '@/utils/apiAuth'
import { validatePassword } from '@/utils/memberValidate'
import { useActionGuard } from '@/utils/actionGuard'

const saveGuard = useActionGuard()
const saving = saveGuard.locked

const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

onLoad(() => {
  ensureApiToken()
})

function validate() {
  if (!form.oldPassword) {
    uni.showToast({ title: '请输入旧密码', icon: 'none' })
    return false
  }
  const p1 = validatePassword(form.newPassword, '新密码')
  if (p1) {
    uni.showToast({ title: p1, icon: 'none' })
    return false
  }
  if (form.newPassword !== form.confirmPassword) {
    uni.showToast({ title: '两次输入的密码不一致', icon: 'none' })
    return false
  }
  if (form.oldPassword === form.newPassword) {
    uni.showToast({ title: '新密码不能与旧密码相同', icon: 'none' })
    return false
  }
  return true
}

function handleSave() {
  saveGuard.run(async () => {
    if (!validate()) return
    await changeMemberPassword({
      oldPassword: form.oldPassword,
      newPassword: form.newPassword,
      confirmPassword: form.confirmPassword
    })
    uni.showToast({ title: '修改成功', icon: 'none' })
    setTimeout(() => uni.navigateBack(), 800)
  })
}
</script>

<style lang="scss" scoped>
@import '@/styles/mine.scss';
</style>
