<template>
  <view>
    <AppNavbar title="修改密码" show-back fallback-url="/pages/profile/index" />

    <view class="page profile-password-page">
      <view class="profile-password-form">
        <view class="field">
          <AtInput
            v-model:value="form.newPassword"
            name="newPassword"
            title="新密码"
            type="password"
            placeholder="请输入新密码"
          />
        </view>
        <view class="field">
          <AtInput
            v-model:value="form.confirmPassword"
            name="confirmPassword"
            title="确认密码"
            type="password"
            placeholder="请再次输入新密码"
          />
        </view>
      </view>

      <view class="submit-bar">
        <AtButton class="btn btn-primary submit-btn" @click="savePassword">提交</AtButton>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import Taro, { useDidShow } from '@tarojs/taro'
import { reactive } from 'vue'
import { updatePasswordApi } from '@/api/profile'
import { isLoggedIn, redirectToLogin } from '@/utils/auth'
import AppNavbar from '@/components/AppNavbar.vue'

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

useDidShow(() => {
  if (isLoggedIn()) return
  redirectToLogin()
})

async function savePassword() {
  if (!form.newPassword || !form.confirmPassword) {
    Taro.showToast({ title: '请输入新密码和确认密码', icon: 'none' })
    return
  }
  if (form.newPassword !== form.confirmPassword) {
    Taro.showToast({ title: '两次输入的密码不一致', icon: 'none' })
    return
  }
  await updatePasswordApi({
    newPassword: form.newPassword,
    confirmPassword: form.confirmPassword
  })
  clearForm()
  Taro.showToast({ title: '修改成功', icon: 'success' })
}

function clearForm() {
  form.newPassword = ''
  form.confirmPassword = ''
}
</script>

<style lang="scss">
.profile-password-page {
  padding-bottom: calc($page-bottom-space + env(safe-area-inset-bottom));
  background: $bg-page;
}

.profile-password-form {
  background: $bg-page;
}

.submit-bar {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1000;
  padding: $space-md $space-xl calc(#{$space-md} + env(safe-area-inset-bottom));
  background: $bg-page;
  border-top: 1px solid $border-color;
}

.submit-btn.at-button {
  margin: 0;
}
</style>



