<template>
  <div class="cart-page">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="nav-left">
        <el-button 
          type="text" 
          @click="$router.go(-1)"
          class="back-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
      </div>
      <div class="nav-center">
        <h1 class="nav-title">购物车</h1>
      </div>
      <div class="nav-right">
        <el-button 
          type="text" 
          @click="clearCart"
          class="clear-btn"
          v-if="cartItems.length > 0"
        >
          清空
        </el-button>
      </div>
    </nav>

    <div v-loading="loading" class="page-content">
      <!-- 空购物车状态 -->
      <div v-if="cartItems.length === 0" class="empty-cart">
        <div class="empty-icon">
          <el-icon size="80"><ShoppingCart /></el-icon>
        </div>
        <div class="empty-text">购物车是空的</div>
        <div class="empty-desc">快去挑选心仪的商品吧</div>
        <el-button type="primary" @click="$router.push('/shop')" class="go-shop-btn">
          去购物
        </el-button>
      </div>

      <!-- 购物车商品列表 -->
      <div v-else class="cart-content">
        <div class="cart-header">
          <el-checkbox 
            v-model="selectAll" 
            @change="handleSelectAll"
            class="select-all-checkbox"
          >
            全选
          </el-checkbox>
          <span class="item-count">共{{ cartItems.length }}件商品</span>
        </div>

        <div class="cart-items">
          <div 
            v-for="item in cartItems" 
            :key="item.id"
            class="cart-item"
          >
            <div class="item-checkbox">
              <el-checkbox 
                v-model="item.selected"
                @change="updateSelection"
              />
            </div>
            <div class="item-image">
              <img :src="getImageUrl(item.product.image_url) || '/imgs/productdetail/商品主图.png'" :alt="item.name" />
            </div>
            <div class="item-info">
              <div class="item-name">{{ item.name }}</div>
              <div class="item-details">
                <span v-if="item.category" class="item-category">{{ item.category }}</span>
                <span v-if="item.size" class="item-size">{{ item.size }}</span>
              </div>
              <div class="item-price">
                <div class="price-container">
                  <div class="main-price">
                    <img src='/imgs/profile/rongdou.png' alt="融豆" class="rongdou-icon" />
                    <span class="rongdou-price">{{ Math.ceil((item.product.points_price || 0) / 10000) }}</span>
                  </div>
                  <div class="sub-price">
                    <el-icon class="points-icon"><Coin /></el-icon>
                    <span class="points-price">{{ item.product.points_price || 0 }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="item-actions">
              <div class="quantity-controls">
                <div 
                  @click="decreaseQuantity(item)"
                  :class="['quantity-btn', { 'disabled': item.quantity <= 1 }]"
                >
                  -
                </div>
                <span class="quantity">{{ item.quantity }}</span>
                <div 
                  @click="increaseQuantity(item)"
                  :class="['quantity-btn', { 'disabled': item.quantity >= item.stock }]"
                >
                  +
                </div>
              </div>
              <el-button 
                type="text" 
                @click="removeItem(item)"
                class="remove-btn"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div v-if="cartItems.length > 0" class="bottom-bar">
      <div class="total-info">
        <div class="selected-count">已选{{ selectedCount }}件</div>
        <div class="total-price">
          <span class="total-label">合计：</span>
          <div class="total-price-container">
            <div class="total-main-price">
              <img src='/imgs/profile/rongdou.png' alt="融豆" class="total-rongdou-icon" />
              <span class="total-rongdou-price">{{ Math.ceil(totalPrice / 10000) }}</span>
            </div>
            <div class="total-sub-price">
              <el-icon class="total-points-icon"><Coin /></el-icon>
              <span class="total-points-price">{{ totalPrice }}</span>
            </div>
          </div>
        </div>
      </div>
      <el-button 
        type="primary" 
        size="large"
        @click="checkout"
        :disabled="selectedCount === 0"
        class="checkout-btn"
      >
        结算({{ selectedCount }})
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft,
  ShoppingCart,
  Coin
} from '@element-plus/icons-vue'
import api from '@/utils/api'
import { getImageUrl } from '@/config'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const cartItems = ref([])
const selectAll = ref(false)

// 计算属性
const selectedItems = computed(() => {
  return cartItems.value.filter(item => item.selected)
})

const selectedCount = computed(() => {
  return selectedItems.value.length
})

const totalPrice = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    const points = parseFloat(item.product?.points_price) || 0
    const quantity = parseInt(item.quantity) || 0
    return total + (points * quantity)
  }, 0)
})

// 方法
const loadCartData = async () => {
  loading.value = true
  try {
    const response = await api.get('/cart')
    console.log(response.data);
    
    if (response.data.success) {
      cartItems.value = response.data.data.items.map(item => ({
        ...item,
        quantity: parseInt(item.quantity) || 1,
        selected: false
      }))
      console.log(cartItems)
    }
  } catch (error) {
    console.log(error);
    
    ElMessage.error('加载购物车失败')
  } finally {
    loading.value = false
  }
}

const handleSelectAll = () => {
  cartItems.value.forEach(item => {
    item.selected = selectAll.value
  })
}

const updateSelection = () => {
  const selectedCount = cartItems.value.filter(item => item.selected).length
  selectAll.value = selectedCount === cartItems.value.length && cartItems.value.length > 0
}

const increaseQuantity = async (item) => {
  if (item.quantity >= item.stock) {
    ElMessage.warning('库存不足')
    return
  }
  
  try {
    await api.put(`/cart/${item.id}`, {
      quantity: item.quantity + 1
    })
    item.quantity++
  } catch (error) {
    ElMessage.error('更新数量失败')
  }
}

const decreaseQuantity = async (item) => {
  if (item.quantity <= 1) return
  
  try {
    await api.put(`/cart/${item.id}`, {
      quantity: item.quantity - 1
    })
    item.quantity--
  } catch (error) {
    ElMessage.error('更新数量失败')
  }
}

const removeItem = async (item) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这件商品吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/cart/${item.id}`)
    const index = cartItems.value.findIndex(i => i.id === item.id)
    if (index > -1) {
      cartItems.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
    updateSelection()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const clearCart = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空购物车吗？',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete('/cart/clear')
    cartItems.value = []
    ElMessage.success('购物车已清空')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空失败')
    }
  }
}

const checkout = async () => {
  if (selectedCount.value === 0) {
    ElMessage.error('请选择要结算的商品')
    return
  }
  
  try {
    // 只发送选中商品的id数组
    const selectedIds = selectedItems.value.map(item => item.id)
    
    // 向后端发送选中商品的id数组创建订单
    const response = await api.post('/orders/create-from-cart', {
      cart_item_ids: selectedIds
    })
    
    if (response.data.success) {
      // 直接跳转到支付页面，不传递任何参数
      console.log('跳转支付页面的response',response.data.data.preOrderId)
      router.push(`/pay/${response.data.data.preOrderId}`)
    } else {
      throw new Error(response.data.message || '创建订单失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '结算失败，请重试')
  }
}

// 生命周期
onMounted(() => {
  loadCartData()
})
</script>

<style scoped>
.cart-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.navbar {
  background: #72c9ff;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: white;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-left, .nav-right {
  flex: 1;
}

.nav-right {
  display: flex;
  justify-content: center;
  align-items: center;
}

.nav-center {
  flex: 2;
  text-align: center;
}

.nav-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: white;
}

.back-btn, .clear-btn {
  color: white !important;
  font-size: 16px;
}

.back-btn:hover, .clear-btn:hover {
  background: rgba(255, 255, 255, 0.1) !important;
}

.page-content {
  flex: 1;
  padding: 0;
  background: white;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  text-align: center;
}

.empty-icon {
  color: #ddd;
  margin-bottom: 20px;
}

.empty-text {
  font-size: 18px;
  color: #666;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  color: #999;
  margin-bottom: 30px;
}

.go-shop-btn {
  background: linear-gradient(135deg, #ff6b35 0%, #ff4757 100%);
  border: none;
  padding: 12px 30px;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
}

.cart-content {
  background: white;
}

.cart-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.select-all-checkbox {
  font-size: 16px;
}

.item-count {
  font-size: 14px;
  color: #666;
}

.cart-items {
  padding: 0;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background: white;
}

.item-checkbox {
  margin-right: 12px;
}

.item-image {
  width: 80px;
  height: 80px;
  margin-right: 12px;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  margin-right: 12px;
}

.item-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.item-details {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.item-category, .item-size {
  font-size: 12px;
  color: #666;
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.item-price {
  display: flex;
  align-items: center;
}

.price-container {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.main-price {
  display: flex;
  align-items: center;
  gap: 4px;
}

.rongdou-icon {
  width: 16px;
  height: 16px;
}

.rongdou-price {
  color: #ff6b35;
  font-weight: 600;
  font-size: 16px;
}

.sub-price {
  display: flex;
  align-items: center;
  gap: 2px;
}

.points-icon {
  font-size: 12px;
  color: #ff6b35;
}

.points-price {
  color: #ff6b35;
  font-weight: 500;
  font-size: 12px;
}

.item-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.quantity-controls {
  display: flex;
  align-items: center;
  overflow: hidden;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  border: none;
  background: transparent;
  color: #666;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  user-select: none;
}

.quantity-btn:hover {
  background: transparent;
  color: #333;
}

.quantity-btn.disabled {
  background: transparent;
  color: #ccc;
  cursor: not-allowed;
  pointer-events: none;
}

.quantity {
  min-width: 36px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  color: #333;
  font-weight: 500;
}

.remove-btn {
  color: #999;
  font-size: 14px;
  padding: 0;
  height: auto;
}

.remove-btn:hover {
  color: #ff4757;
}

.bottom-bar {
  background: white;
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: sticky;
  bottom: 0;
  z-index: 100;
}

.total-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.selected-count {
  font-size: 14px;
  color: #666;
}

.total-price {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.total-label {
  color: #333;
  margin-right: 8px;
}

.total-price-container {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.total-main-price {
  display: flex;
  align-items: center;
  gap: 4px;
}

.total-rongdou-icon {
  width: 20px;
  height: 20px;
}

.total-rongdou-price {
  color: #ff6b35;
  font-weight: 600;
  font-size: 20px;
}

.total-sub-price {
  display: flex;
  align-items: center;
  gap: 2px;
}

.total-points-icon {
  font-size: 14px;
  color: #ff6b35;
}

.total-points-price {
  color: #ff6b35;
  font-weight: 500;
  font-size: 14px;
}

.checkout-btn {
  background: linear-gradient(135deg, #ff6b35 0%, #ff4757 100%);
  border: none;
  padding: 12px 24px;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  min-width: 120px;
}

.checkout-btn:disabled {
  background: #ddd;
  color: #999;
}
</style>