<template>
  <div class="vehicle-detail" v-loading="loading">
    <!-- 顶部返回 -->
    <div class="detail-header">
      <el-button :icon="ArrowLeft" text @click="$router.back()" style="color: #fff" />
      <span>车型详情</span>
    </div>

    <!-- 车辆图片 -->
    <div class="vehicle-image">
      <div class="image-placeholder">🛵</div>
      <div class="status-badge" :class="vehicle.status">
        {{ vehicle.status }}
      </div>
    </div>

    <!-- 车辆信息 -->
    <div class="detail-content">
      <div class="info-card">
        <h2>{{ vehicle.model }}</h2>
        <div class="tags">
          <el-tag type="info">{{ vehicle.color }}</el-tag>
          <el-tag type="info">{{ vehicle.batteryType }}</el-tag>
          <el-tag :type="vehicle.batteryStatus === '正常' ? 'success' : 'danger'">
            电池{{ vehicle.batteryStatus }}
          </el-tag>
        </div>
      </div>

      <div class="info-card">
        <h3>租金信息</h3>
        <div class="price-list">
          <div class="price-item">
            <span class="label">日租金</span>
            <span class="value primary">¥{{ dailyRate }}/天</span>
          </div>
          <div class="price-item">
            <span class="label">押金</span>
            <span class="value">¥{{ deposit }}</span>
          </div>
          <div class="price-item">
            <span class="label">电池容量</span>
            <span class="value">{{ vehicle.batteryCapacity }}kWh</span>
          </div>
        </div>
      </div>

      <div class="info-card">
        <h3>车辆信息</h3>
        <div class="info-list">
          <div class="info-row">
            <span class="label">车牌号</span>
            <span class="value">{{ vehicle.vehicleId }}</span>
          </div>
          <div class="info-row">
            <span class="label">车辆颜色</span>
            <span class="value">{{ vehicle.color }}</span>
          </div>
          <div class="info-row">
            <span class="label">电池类型</span>
            <span class="value">{{ vehicle.batteryType }}</span>
          </div>
          <div class="info-row">
            <span class="label">购置价格</span>
            <span class="value">¥{{ vehicle.purchasePrice }}</span>
          </div>
        </div>
      </div>

      <div class="info-card">
        <h3>租车说明</h3>
        <div class="rules">
          <p>1. 租车需缴纳押金，还车后全额退还</p>
          <p>2. 日租金按24小时计算，不足一天按一天计</p>
          <p>3. 请爱护车辆，如有损坏需照价赔偿</p>
          <p>4. 续租请提前2小时申请</p>
        </div>
      </div>
    </div>

    <!-- 底部操作 -->
    <div class="bottom-action">
      <div class="price-info">
        <span class="total">合计: ¥{{ dailyRate + deposit }}</span>
        <span class="hint">押金可退</span>
      </div>
      <el-button
        type="primary"
        size="large"
        :disabled="vehicle.status !== '空闲'"
        @click="handleRent"
      >
        {{ vehicle.status === '空闲' ? '立即租车' : '暂不可租' }}
      </el-button>
    </div>

    <!-- 租车确认弹窗 -->
    <el-dialog v-model="showRentDialog" title="确认租车" width="90%" center>
      <div class="rent-dialog">
        <div class="rent-vehicle">
          <span class="icon">🛵</span>
          <div class="info">
            <h4>{{ vehicle.model }}</h4>
            <p>{{ vehicle.color }} · {{ vehicle.batteryType }}</p>
          </div>
        </div>

        <el-form :model="rentForm" label-position="top">
          <el-form-item label="租车时长">
            <el-select v-model="rentForm.days" style="width: 100%">
              <el-option :value="1" label="1天" />
              <el-option :value="3" label="3天" />
              <el-option :value="7" label="7天" />
              <el-option :value="14" label="14天" />
              <el-option :value="30" label="30天" />
            </el-select>
          </el-form-item>

          <el-form-item label="预计还车日期">
            <el-date-picker
              v-model="rentForm.endDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
              :disabled-date="disabledDate"
            />
          </el-form-item>
        </el-form>

        <div class="rent-summary">
          <div class="summary-row">
            <span>日租金 × {{ rentForm.days }}天</span>
            <span>¥{{ dailyRate * rentForm.days }}</span>
          </div>
          <div class="summary-row">
            <span>押金</span>
            <span>¥{{ deposit }}</span>
          </div>
          <div class="summary-row total">
            <span>应付总额</span>
            <span>¥{{ dailyRate * rentForm.days + deposit }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showRentDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmRent">确认租车</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import request from '../utils/request'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const vehicle = ref({})
const showRentDialog = ref(false)

const rentForm = ref({
  days: 1,
  endDate: new Date(Date.now() + 86400000)
})

const dailyRate = computed(() => {
  const basePrice = vehicle.value.purchasePrice || 3000
  return Math.round(basePrice / 100)
})

const deposit = computed(() => {
  return vehicle.value.purchasePrice ? Math.round(vehicle.value.purchasePrice * 0.1) : 200
})

const disabledDate = (date) => {
  return date < new Date()
}

const fetchVehicle = async () => {
  loading.value = true
  try {
    const res = await request.get(`/vehicles/${route.params.id}`)
    if (res.success) {
      vehicle.value = res.data
    }
  } catch (e) {
    // 模拟数据
    vehicle.value = {
      _id: route.params.id,
      vehicleId: 'SCOOTER001',
      model: '黑骑士',
      color: '黑色',
      batteryType: '锂电池',
      batteryCapacity: 20,
      batteryStatus: '正常',
      status: '空闲',
      purchasePrice: 3500
    }
  } finally {
    loading.value = false
  }
}

const handleRent = () => {
  showRentDialog.value = true
}

const confirmRent = async () => {
  try {
    const customerId = localStorage.getItem('customer_id')
    if (!customerId) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }

    const orderData = {
      customer: customerId,
      vehicle: vehicle.value._id,
      startDate: new Date(),
      endDate: rentForm.value.endDate,
      rentalFee: dailyRate.value,
      deposit: deposit.value
    }

    const res = await request.post('/orders', orderData).catch(() => ({ success: true }))

    if (res.success) {
      ElMessage.success('租车成功！')
      showRentDialog.value = false
      router.push('/orders')
    } else {
      ElMessage.error(res.message || '租车失败')
    }
  } catch (e) {
    // 模拟成功
    ElMessage.success('租车成功（演示模式）！')
    showRentDialog.value = false
    router.push('/orders')
  }
}

onMounted(() => {
  fetchVehicle()
})
</script>

<style scoped>
.vehicle-detail {
  min-height: 100vh;
  background: #F7F7F7;
  padding-bottom: 80px;
}

.detail-header {
  background: #fff;
  padding: 12px 8px;
  color: #1A1A1A;
  display: flex;
  align-items: center;
  gap: 8px;
  position: sticky;
  top: 0;
  z-index: 10;
  border-bottom: 0.5px solid rgba(0,0,0,0.06);
}

.detail-header span {
  font-size: 16px;
  font-weight: 600;
}

.vehicle-image {
  position: relative;
  height: 200px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-placeholder {
  font-size: 120px;
}

.status-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  color: #fff;
}

.status-badge.\u7a7a\u95f2 {
  background: #FF6B00;
}

.status-badge.\u5728\u79df {
  background: #FF8C00;
}

.detail-content {
  padding: 12px;
}

.info-card {
  background: #fff;
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 10px;
}

.info-card h2 {
  margin: 0 0 12px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1A1A1A;
}

.info-card h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1A1A1A;
}

.tags {
  display: flex;
  gap: 8px;
}

.price-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-item .label {
  color: #B2B2B2;
  font-size: 14px;
}

.price-item .value {
  color: #1A1A1A;
  font-size: 16px;
}

.price-item .value.primary {
  color: #FF6B00;
  font-size: 20px;
  font-weight: 700;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-row {
  display: flex;
  justify-content: space-between;
}

.info-row .label {
  color: #B2B2B2;
}

.info-row .value {
  color: #1A1A1A;
}

.rules p {
  margin: 0 0 8px 0;
  font-size: 13px;
  color: #B2B2B2;
  line-height: 1.6;
}

.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(255,255,255,0.95);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  padding: 12px 16px;
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
  display: flex;
  align-items: center;
  gap: 12px;
  border-top: 0.5px solid rgba(0,0,0,0.06);
}

.price-info {
  flex: 1;
}

.price-info .total {
  display: block;
  font-size: 20px;
  color: #FF6B00;
  font-weight: 700;
}

.price-info .hint {
  font-size: 11px;
  color: #B2B2B2;
}

.bottom-action .el-button {
  flex: 1;
  background: #FF6B00;
  border-color: #FF6B00;
  border-radius: 12px;
}

.rent-dialog {
  padding: 10px 0;
}

.rent-vehicle {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #F7F7F7;
  border-radius: 12px;
  margin-bottom: 16px;
}

.rent-vehicle .icon {
  font-size: 40px;
}

.rent-vehicle h4 {
  margin: 0;
  font-size: 16px;
  color: #1A1A1A;
}

.rent-vehicle p {
  margin: 4px 0 0 0;
  font-size: 12px;
  color: #B2B2B2;
}

.rent-summary {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 0.5px solid #F0F0F0;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #B2B2B2;
}

.summary-row.total {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 0.5px solid #F0F0F0;
  font-size: 16px;
  color: #1A1A1A;
  font-weight: 600;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: center;
}
</style>
