<template>
  <div class="container">
    <a-space style="width: 100%; justify-content: space-between; margin-bottom: 12px">
      <h2>萌贝母婴商城 - 个人信息</h2>
      <a-space>
        <a-button @click="goProducts">继续购物</a-button>
        <a-button @click="goOrders">我的订单</a-button>
      </a-space>
    </a-space>

    <a-card title="个人资料">
      <a-form :model="form" layout="vertical" style="max-width: 480px">
        <a-form-item label="账号"><a-input v-model="form.username" disabled /></a-form-item>
        <a-form-item label="角色"><a-input v-model="form.role" disabled /></a-form-item>
        <a-form-item label="昵称"><a-input v-model="form.nickname" /></a-form-item>
        <a-form-item label="手机号"><a-input v-model="form.phone" /></a-form-item>
        <a-form-item label="收货地址"><a-input v-model="form.address" /></a-form-item>
        <a-button type="primary" @click="save">保存修改</a-button>
      </a-form>
    </a-card>

    <a-card title="商家入驻申请" style="margin-top: 12px">
      <a-space direction="vertical" style="width: 100%">
        <a-textarea v-model="qualification" :rows="3" placeholder="请填写商家资质、经营能力说明" />
        <a-button type="primary" @click="submitMerchantApplication">提交入驻申请</a-button>
      </a-space>
    </a-card>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { api } from '../api'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()
const form = reactive({ username: '', role: '', nickname: '', phone: '', address: '' })
const qualification = ref('')

const goProducts = () => router.push('/products')
const goOrders = () => router.push('/orders')

const load = async () => {
  const me = await api.me()
  form.username = me.username
  form.role = me.role
  form.nickname = me.nickname || ''
  form.phone = me.phone || ''
  form.address = me.address || ''
}

const save = async () => {
  await api.updateMe({ nickname: form.nickname, phone: form.phone, address: form.address })
  Message.success('已保存')
}

const submitMerchantApplication = async () => {
  await api.applyMerchant({ qualification: qualification.value })
  qualification.value = ''
  Message.success('入驻申请已提交，等待管理员审核')
}

onMounted(async () => {
  try {
    await userStore.fetchMe()
    if (userStore.role !== 'CUSTOMER') return router.replace('/login')
    await load()
  } catch {
    router.replace('/login')
  }
})
</script>
