<template>
  <div>
    <div class="section-title">我的收藏</div>
    <div class="card-grid">
      <a-card v-for="item in favorites" :key="item.id" :title="item.car.brand + ' ' + item.car.model">
        <p>车牌：{{ item.car.plateNo }}</p>
        <p>日租金：¥{{ item.car.pricePerDay }}</p>
        <a-button type="primary" @click="goDetail(item.car.id)">查看详情</a-button>
        <a-button type="text" status="danger" @click="remove(item.car.id)">移除</a-button>
      </a-card>
    </div>
  </div>
</template>

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

const router = useRouter()
const favorites = ref([])

const load = async () => {
  const list = await http.get('/api/user/favorite')
  const cars = await http.get('/api/cars')
  const map = new Map(cars.map((car) => [car.id, car]))
  favorites.value = list.map((fav) => ({
    ...fav,
    car: map.get(fav.carId) || {}
  }))
}

const remove = async (carId) => {
  await http.delete(`/api/user/favorite/${carId}`)
  Message.success('已移除')
  load()
}

const goDetail = (id) => {
  router.push(`/cars/${id}`)
}

onMounted(load)
</script>
