<template>
  <div class="checkout-page">
    <h1 class="page-title">订单结算</h1>
    
    <div v-if="loading" class="loading">
      <el-loading-spinner></el-loading-spinner>
      加载中...
    </div>

    <div v-else-if="cartItems.length === 0" class="empty-cart">
      <div class="empty-icon">🛒</div>
      <h2>购物车是空的</h2>
      <p>请先添加商品到购物车</p>
      <router-link to="/productList" class="shop-now-btn">
        去购物
      </router-link>
    </div>

    <div v-else class="checkout-content">
      <!-- 订单摘要 -->
      <div class="order-summary">
        <h2 class="section-title">订单摘要</h2>
        
        <div class="order-items">
          <div 
            v-for="item in cartItems" 
            :key="item.id" 
            class="order-item"
          >
            <div class="item-image">
              <img :src="item.image" :alt="item.title" />
            </div>
            
            <div class="item-info">
              <h3 class="item-title">{{ item.title }}</h3>
              <div class="item-price">¥{{ item.price }}</div>
            </div>
            
            <div class="item-quantity">
              <span class="quantity-label">数量：</span>
              <span class="quantity-value">{{ item.quantity }}</span>
            </div>
            
            <div class="item-total">
              <span class="total-label">小计：</span>
              <span class="total-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
            </div>
          </div>
        </div>
        
        <div class="order-total">
          <div class="total-row">
            <span>商品总数：</span>
            <span>{{ summary.totalQuantity }} 件</span>
          </div>
          <div class="total-row">
            <span>商品种类：</span>
            <span>{{ cartItems.length }} 种</span>
          </div>
          <div class="total-row final-total">
            <span>订单总计：</span>
            <span class="final-amount">¥{{ summary.totalPrice.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 结算表单 -->
      <div class="checkout-form">
        <h2 class="section-title">收货信息</h2>
        
        <form @submit.prevent="handleSubmit" class="form">
          <div class="form-row">
            <div class="form-group">
              <label for="name" class="form-label">收货人姓名 *</label>
              <input 
                id="name"
                v-model="form.name" 
                type="text" 
                class="form-input"
                required
                placeholder="请输入收货人姓名"
                aria-describedby="name-error"
              />
              <div v-if="errors.name" id="name-error" class="error-message">
                {{ errors.name }}
              </div>
            </div>
            
            <div class="form-group">
              <label for="phone" class="form-label">联系电话 *</label>
              <input 
                id="phone"
                v-model="form.phone" 
                type="tel" 
                class="form-input"
                required
                placeholder="请输入联系电话"
                aria-describedby="phone-error"
              />
              <div v-if="errors.phone" id="phone-error" class="error-message">
                {{ errors.phone }}
              </div>
            </div>
          </div>

          <div class="form-group">
            <label for="address" class="form-label">收货地址 *</label>
            <textarea 
              id="address"
              v-model="form.address" 
              class="form-textarea"
              rows="3"
              required
              placeholder="请输入详细收货地址"
              aria-describedby="address-error"
            ></textarea>
            <div v-if="errors.address" id="address-error" class="error-message">
              {{ errors.address }}
            </div>
          </div>

          <div class="form-group">
            <label for="note" class="form-label">备注</label>
            <textarea 
              id="note"
              v-model="form.note" 
              class="form-textarea"
              rows="2"
              placeholder="可选：订单备注信息"
            ></textarea>
          </div>

          <div class="form-actions">
            <router-link to="/cart" class="back-btn">
              返回购物车
            </router-link>
            
            <button 
              type="submit" 
              class="submit-btn"
              :disabled="submitting"
              aria-label="提交订单"
            >
              <span v-if="submitting">提交中...</span>
              <span v-else>提交订单</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { readCart, clearCart, computeSummary } from '../../utils/cartManager'

export default {
  name: 'Checkout',
  data() {
    return {
      cartItems: [],
      loading: false,
      submitting: false,
      form: {
        name: '',
        phone: '',
        address: '',
        note: ''
      },
      errors: {}
    }
  },
  computed: {
    summary() {
      return computeSummary()
    }
  },
  mounted() {
    this.loadCart()
  },
  methods: {
    /**
     * 加载购物车数据
     */
    loadCart() {
      try {
        this.loading = true
        this.cartItems = readCart()
        
        if (this.cartItems.length === 0) {
          this.$message.warning('购物车为空，请先添加商品')
        }
      } catch (error) {
        console.error('加载购物车失败:', error)
        console.log('加载购物车失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    /**
     * 验证表单
     */
    validateForm() {
      this.errors = {}
      
      if (!this.form.name.trim()) {
        this.errors.name = '请输入收货人姓名'
      }
      
      if (!this.form.phone.trim()) {
        this.errors.phone = '请输入联系电话'
      } else if (!/^1[3-9]\d{9}$/.test(this.form.phone.trim())) {
        this.errors.phone = '请输入正确的手机号码'
      }
      
      if (!this.form.address.trim()) {
        this.errors.address = '请输入收货地址'
      }
      
      return Object.keys(this.errors).length === 0
    },

    /**
     * 处理表单提交
     */
    async handleSubmit() {
      if (!this.validateForm()) {
        this.$message.error('请完善收货信息')
        return
      }
      
      try {
        this.submitting = true
        
        // 模拟订单提交
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        // 构建订单数据
        const order = {
          id: `ORDER_${Date.now()}`,
          items: this.cartItems,
          total: this.summary.totalPrice,
          customer: {
            name: this.form.name,
            phone: this.form.phone,
            address: this.form.address,
            note: this.form.note
          },
          createTime: new Date().toISOString()
        }
        
        console.log('订单提交成功:', order)
        
        // 清空购物车
        clearCart()
        
        // 显示成功消息
        this.$message.success('订单提交成功！')
        
        // 跳转到成功页面或商品列表
        setTimeout(() => {
          this.$router.push('/productList')
        }, 1500)
        
      } catch (error) {
        console.error('提交订单失败:', error)
        console.log('提交订单失败，请稍后重试')
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style scoped>
.checkout-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 600;
}

.loading {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-cart {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-cart h2 {
  color: #2c3e50;
  margin-bottom: 12px;
  font-size: 24px;
}

.empty-cart p {
  color: #666;
  margin-bottom: 24px;
  font-size: 16px;
}

.shop-now-btn {
  display: inline-block;
  background: #42b983;
  color: white;
  text-decoration: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  transition: background 0.3s ease;
}

.shop-now-btn:hover {
  background: #3aa876;
}

.checkout-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 20px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid #eee;
}

/* 订单摘要样式 */
.order-summary {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
  height: fit-content;
}

.order-items {
  margin-bottom: 24px;
}

.order-item {
  display: grid;
  grid-template-columns: auto 1fr auto auto;
  gap: 16px;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #eee;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
}

.item-title {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 4px 0;
}

.item-price {
  font-size: 16px;
  font-weight: 700;
  color: #e74c3c;
}

.item-quantity {
  text-align: center;
}

.quantity-label {
  font-size: 12px;
  color: #666;
}

.quantity-value {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
}

.item-total {
  text-align: right;
}

.total-label {
  font-size: 12px;
  color: #666;
}

.total-price {
  font-size: 16px;
  font-weight: 700;
  color: #e74c3c;
}

.order-total {
  border-top: 2px solid #eee;
  padding-top: 20px;
}

.total-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
  color: #666;
}

.final-total {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  border-top: 1px solid #eee;
  padding-top: 16px;
  margin-top: 16px;
}

.final-amount {
  color: #e74c3c;
  font-size: 24px;
}

/* 结算表单样式 */
.checkout-form {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
}

.form-input,
.form-textarea {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.error-message {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 4px;
}

.form-actions {
  display: flex;
  gap: 16px;
  margin-top: 20px;
}

.back-btn {
  background: #6c757d;
  color: white;
  text-decoration: none;
  padding: 14px 24px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  transition: background 0.3s ease;
  text-align: center;
  flex: 1;
}

.back-btn:hover {
  background: #5a6268;
}

.submit-btn {
  background: #42b983;
  color: white;
  border: none;
  padding: 14px 24px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  flex: 2;
}

.submit-btn:hover:not(:disabled) {
  background: #3aa876;
  transform: translateY(-2px);
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .checkout-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .checkout-page {
    padding: 16px;
  }
  
  .page-title {
    font-size: 24px;
    margin-bottom: 24px;
  }
  
  .order-item {
    grid-template-columns: 1fr;
    gap: 12px;
    text-align: center;
  }
  
  .item-image img {
    width: 80px;
    height: 80px;
  }
}
</style> 