<template>
  <a-modal
    v-model:visible="visible"
    :title="'个人资料'"
    :width="400"
    @cancel="handleClose"
    @ok="handleSaveProfile"
    :ok-text="'保存'"
    :cancel-text="'取消'"
    :confirm-loading="loading"
  >
    <a-form :model="form" layout="vertical">
      <a-form-item :label="'账号'" field="account">
        <a-input v-model="form.account" :placeholder="'账号'" disabled />
      </a-form-item>

      <a-form-item :label="'姓名'" field="name">
        <a-input v-model="form.name" :placeholder="'请输入姓名'" allow-clear />
      </a-form-item>

      <a-form-item :label="'邮箱'" field="email">
        <a-input v-model="form.email" :placeholder="'请输入邮箱'" allow-clear />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { modifyUser } from '@/api/module/user'
import type { UserItem } from '@/api/types'
import SafeStorage, { AppStorageKey } from '@/utils/safeStorage'

interface Props {
  open: boolean
}

const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
}>()

const loading = ref(false)
const visible = ref(props.open)

const form = ref({
  account: '',
  name: '',
  email: '',
})

// 监听 props.open 变化
watch(
  () => props.open,
  (val) => {
    visible.value = val
    if (val) {
      // 打开时从存储中获取用户信息
      const userInfo = SafeStorage.get<UserItem>(AppStorageKey.USER_INFO)
      form.value = {
        account: userInfo?.account || '',
        name: userInfo?.name || '',
        email: userInfo?.email || '',
      }
    }
  }
)

// 监听 visible 变化，同步到父组件
watch(visible, (val) => {
  emit('update:open', val)
})

// 保存个人资料
const handleSaveProfile = async () => {
  loading.value = true

  try {
    const userInfo = SafeStorage.get<UserItem>(AppStorageKey.USER_INFO)
    const updatedUserInfo = {
      ...userInfo,
      ...form.value,
      id: userInfo?.user_id ?? userInfo?.id,
    }

    const res = await modifyUser(updatedUserInfo)

    if (res.code === 0) {
      Message.success('个人资料修改成功')
      SafeStorage.set(AppStorageKey.USER_INFO, updatedUserInfo)
      handleClose()
    } else {
      Message.error(res.message || '个人资料修改失败')
    }
  } catch (error) {
    console.error('个人资料修改失败:', error)
    Message.error('个人资料修改失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  form.value = {
    account: '',
    name: '',
    email: '',
  }
  visible.value = false
}
</script>
