<template>
  <div class='grid'>
    <el-card>
      <template #header><div class='font-700'>基本信息</div></template>
      <el-form :model='profileForm' label-width='100px'>
        <el-form-item label='昵称'><el-input v-model='profileForm.nickname' /></el-form-item>
        <el-form-item label='邮箱'><el-input v-model='profileForm.email' /></el-form-item>
        <el-form-item label='手机号'><el-input v-model='profileForm.phone' /></el-form-item>
        <el-button type='primary' :loading='savingProfile' @click='saveProfile'>保存信息</el-button>
      </el-form>
    </el-card>

    <el-card>
      <template #header><div class='font-700'>修改密码</div></template>
      <el-form :model='passwordForm' label-width='110px'>
        <el-form-item label='当前密码'><el-input v-model='passwordForm.current_password' type='password' show-password /></el-form-item>
        <el-form-item label='新密码'><el-input v-model='passwordForm.password' type='password' show-password /></el-form-item>
        <el-form-item label='确认新密码'><el-input v-model='passwordForm.password_confirmation' type='password' show-password /></el-form-item>
        <el-button type='warning' :loading='savingPassword' @click='savePassword'>更新密码</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang='ts'>
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { authApi } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const profileForm = reactive({ nickname: authStore.user?.nickname || '', email: authStore.user?.email || '', phone: (authStore.user as any)?.phone || '' })
const passwordForm = reactive({ current_password: '', password: '', password_confirmation: '' })
const savingProfile = ref(false)
const savingPassword = ref(false)

async function saveProfile(): Promise<void> {
  savingProfile.value = true
  try {
    await authApi.updateProfile(profileForm)
    const me = await authApi.me()
    authStore.setAuth(me.data.user, me.data.permissions)
    ElMessage.success('个人信息已更新')
  } catch (error: any) {
    const first = error?.errors ? (Object.values(error.errors)[0] as string[])?.[0] : null
    ElMessage.error(first || error?.message || '更新失败')
  } finally {
    savingProfile.value = false
  }
}

async function savePassword(): Promise<void> {
  savingPassword.value = true
  try {
    await authApi.updatePassword(passwordForm)
    ElMessage.success('密码已更新')
    passwordForm.current_password = ''
    passwordForm.password = ''
    passwordForm.password_confirmation = ''
  } catch (error: any) {
    const first = error?.errors ? (Object.values(error.errors)[0] as string[])?.[0] : null
    ElMessage.error(first || error?.message || '修改失败')
  } finally {
    savingPassword.value = false
  }
}
</script>

<style scoped>
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
</style>
