<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="goCart">购物车</a-button>
        <a-button @click="goOrders">我的订单</a-button>
      </a-space>
    </a-space>

    <a-card title="收藏列表">
      <a-space style="margin-bottom: 10px">
        <a-input v-model="address" style="width: 320px" placeholder="收货地址" />
        <a-button @click="loadFavorites">刷新</a-button>
      </a-space>
      <a-table :columns="columns" :data="favorites" :pagination="{ pageSize: 8 }">
        <template #actions="{ record }">
          <a-space>
            <a-button size="mini" @click="addCart(record.productId)">加入购物车</a-button>
            <a-button size="mini" type="primary" @click="buyNow(record.productId)">立即购买</a-button>
            <a-button size="mini" status="danger" @click="removeFavorite(record.productId)">取消收藏</a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { onMounted, 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 favorites = ref([])
const address = ref(localStorage.getItem('customer_address') || '辽宁省大连市高新区')

const columns = [
  { title: '商品名称', dataIndex: 'productName' },
  { title: '分类', dataIndex: 'category' },
  { title: '单价', dataIndex: 'unitPrice' },
  { title: '库存', dataIndex: 'stock' },
  { title: '操作', slotName: 'actions' }
]

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

const loadFavorites = async () => {
  favorites.value = await api.customerFavoriteViews()
}

const removeFavorite = async (productId) => {
  await api.deleteFavorite(productId)
  Message.success('已取消收藏')
  await loadFavorites()
}

const addCart = async (productId) => {
  await api.addCart({ productId, quantity: 1 })
  Message.success('已加入购物车')
}

const buyNow = async (productId) => {
  if (!address.value) return Message.warning('请先填写收货地址')
  localStorage.setItem('customer_address', address.value)
  await api.customerBuyNow({ productId, quantity: 1, address: address.value })
  Message.success('购买成功')
  router.push('/orders')
}

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