<template>
  <a-card title="个人中心">
    <a-form layout="vertical">
      <a-form-item label="手机号"><a-input v-model:value="profile.phone" /></a-form-item>
      <a-form-item label="邮箱"><a-input v-model:value="profile.email" /></a-form-item>
      <a-form-item label="头像URL"><a-input v-model:value="profile.avatar" /></a-form-item>
      <a-button type="primary" @click="save">保存</a-button>
    </a-form>
  </a-card>

  <a-card title="收货地址" style="margin-top: 16px">
    <a-form layout="inline">
      <a-form-item label="姓名"><a-input v-model:value="addr.receiverName" /></a-form-item>
      <a-form-item label="电话"><a-input v-model:value="addr.receiverPhone" /></a-form-item>
      <a-form-item label="地址"><a-input v-model:value="addr.detail" /></a-form-item>
      <a-button type="primary" @click="addAddress">新增</a-button>
    </a-form>
    <a-list :data-source="addresses" style="margin-top: 16px">
      <template #renderItem="{ item }">
        <a-list-item>
          {{ item.receiverName }} {{ item.receiverPhone }} {{ item.detail }}
          <a-button type="link" danger @click="remove(item)">删除</a-button>
        </a-list-item>
      </template>
    </a-list>
  </a-card>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import api from '../../api'

const profile = reactive({ phone: '', email: '', avatar: '' })
const addresses = ref([])
const addr = reactive({ receiverName: '', receiverPhone: '', detail: '' })

const load = async () => {
  const res = await api.get('/api/user/profile')
  if (res.success) {
    profile.phone = res.data.phone || ''
    profile.email = res.data.email || ''
    profile.avatar = res.data.avatar || ''
  }
  const res2 = await api.get('/api/user/addresses')
  if (res2.success) addresses.value = res2.data
}

const save = async () => {
  await api.put('/api/user/profile', profile)
  message.success('保存成功')
}

const addAddress = async () => {
  await api.post('/api/user/addresses', addr)
  addr.receiverName = ''
  addr.receiverPhone = ''
  addr.detail = ''
  load()
}

const remove = async (item) => {
  await api.delete(`/api/user/addresses/${item.id}`)
  load()
}

onMounted(load)
</script>
