<template>
  <view>
    <AppNavbar title="用户信息" show-back fallback-url="/pages/profile/index" />

    <view class="page profile-info-page">
      <view class="profile-info-form">
        <view class="field">
          <AtInput v-model:value="form.nickname" name="nickname" title="昵称" placeholder="请输入昵称" />
        </view>
        <view class="field">
          <AtInput v-model:value="form.phoneNumber" name="phoneNumber" title="手机号" type="tel" placeholder="请输入手机号" />
        </view>
        <view class="field">
          <AtInput v-model:value="form.email" name="email" title="邮箱" type="email" placeholder="请输入邮箱" />
        </view>
      </view>

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

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

const userStore = useUserStore()
const form = reactive({ nickname: '', phoneNumber: '', email: '' })

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

async function loadProfile() {
  const { data } = await getProfileApi()
  Object.assign(form, data.user || {})
  userStore.setUser(data.user || {})
}

async function saveProfile() {
  await updateProfileApi({
    nickName: form.nickname,
    phoneNumber: form.phoneNumber,
    email: form.email
  })
  Taro.showToast({ title: '保存成功', icon: 'success' })
  await loadProfile()
}
</script>

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

.profile-info-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>



