<template>
  <div>
    <a-card v-if="car" :title="car.brand + ' ' + car.model">
      <p>车牌：{{ car.plateNo }}</p>
      <p>日租金：¥{{ car.pricePerDay }}</p>
      <p>押金：¥{{ car.deposit }}</p>
      <p>座位：{{ car.seats }} | 变速箱：{{ car.transmission }} | 油耗类型：{{ car.fuelType }}</p>
      <p>里程：{{ car.mileage }} km</p>
      <p>{{ car.description }}</p>
      <a-tag v-if="car.isSpecial" color="red">特价</a-tag>
      <a-tag v-if="car.status !== 'AVAILABLE'" color="orange">{{ mapText(carStatusMap, car.status) }}</a-tag>
      <div style="margin-top: 12px; display: flex; gap: 12px;">
        <a-button type="primary" @click="toggleFavorite">
          {{ isFavorite ? '取消收藏' : '加入收藏' }}
        </a-button>
      </div>
    </a-card>

    <div style="height: 16px"></div>
    <a-card>
      <div class="section-title">租车下单</div>
      <a-form :model="orderForm" layout="inline">
        <a-form-item label="租期">
          <a-range-picker v-model="orderForm.range" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="createOrder">提交订单</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import http from '../api/http'
import { useAuthStore } from '../store/auth'
import { carStatusMap, mapText } from '../utils/format'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const car = ref(null)
const isFavorite = ref(false)
const orderForm = ref({ range: [] })

const loadCar = async () => {
  car.value = await http.get(`/api/cars/${route.params.id}`)
}

const loadFavorite = async () => {
  if (!auth.token) return
  const favorites = await http.get('/api/user/favorite')
  isFavorite.value = favorites.some((item) => item.carId === Number(route.params.id))
}

const toggleFavorite = async () => {
  if (!auth.token) {
    router.push('/login')
    return
  }
  if (isFavorite.value) {
    await http.delete(`/api/user/favorite/${route.params.id}`)
    isFavorite.value = false
    Message.success('已取消收藏')
  } else {
    await http.post(`/api/user/favorite/${route.params.id}`)
    isFavorite.value = true
    Message.success('已收藏')
  }
}

const createOrder = async () => {
  if (!auth.token) {
    router.push('/login')
    return
  }
  if (!orderForm.value.range || orderForm.value.range.length !== 2) {
    Message.warning('请选择租期')
    return
  }
  const [startDate, endDate] = orderForm.value.range
  await http.post('/api/user/order', {
    carId: car.value.id,
    startDate,
    endDate
  })
  Message.success('订单创建成功，请前往我的订单支付')
  router.push('/orders')
}

onMounted(() => {
  loadCar()
  loadFavorite()
})
</script>
