<template>
  <view class="cart-page">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-title">购物车</view>
      <view class="navbar-action" @click="toggleEdit">
        {{ isEditing ? '完成' : '编辑' }}
      </view>
    </view>

    <!-- 购物车列表 -->
    <scroll-view class="cart-list" scroll-y>
      <view v-if="cartItems.length === 0" class="empty-cart">
        <image src="/static/images/empty-cart.png" class="empty-image" />
        <text class="empty-text">购物车空空如也</text>
        <button class="go-shopping-btn" @click="goShopping">去逛逛</button>
      </view>

      <view v-else class="cart-content">
        <!-- 店铺分组 -->
        <view 
          v-for="shop in groupedCartItems" 
          :key="shop.shopId"
          class="shop-group"
        >
          <!-- 店铺头部 -->
          <view class="shop-header">
            <view class="shop-select" @click="toggleShopSelect(shop.shopId)">
              <uni-icons 
                :type="shop.selected ? 'checkbox-filled' : 'circle'" 
                :color="shop.selected ? '#2E8B57' : '#ccc'"
                size="20"
              />
            </view>
            <view class="shop-info">
              <uni-icons type="shop" size="16" color="#666" />
              <text class="shop-name">{{ shop.shopName }}</text>
            </view>
          </view>

          <!-- 商品列表 -->
          <view class="product-list">
            <view 
              v-for="item in shop.items" 
              :key="item.id"
              class="cart-item"
            >
              <view class="item-select" @click="toggleItemSelect(item.id)">
                <uni-icons 
                  :type="item.selected ? 'checkbox-filled' : 'circle'" 
                  :color="item.selected ? '#2E8B57' : '#ccc'"
                  size="20"
                />
              </view>
              
              <view class="item-image">
                <image :src="item.image" mode="aspectFill" />
              </view>
              
              <view class="item-info">
                <view class="item-title">{{ item.title }}</view>
                <view class="item-spec">{{ item.specification }}</view>
                <view class="item-footer">
                  <view class="item-price">
                    <text class="currency">¥</text>
                    <text class="amount">{{ item.price }}</text>
                  </view>
                  
                  <view v-if="!isEditing" class="quantity-control">
                    <view 
                      class="quantity-btn decrease"
                      :class="{ disabled: item.quantity <= 1 }"
                      @click="decreaseQuantity(item.id)"
                    >
                      <uni-icons type="minus" size="14" />
                    </view>
                    <input 
                      v-model="item.quantity" 
                      type="number"
                      class="quantity-input"
                      @blur="updateQuantity(item.id, $event)"
                    />
                    <view 
                      class="quantity-btn increase"
                      @click="increaseQuantity(item.id)"
                    >
                      <uni-icons type="plus" size="14" />
                    </view>
                  </view>
                  
                  <view v-else class="edit-actions">
                    <button class="collect-btn" @click="collectItem(item.id)">
                      收藏
                    </button>
                    <button class="delete-btn" @click="deleteItem(item.id)">
                      删除
                    </button>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 推荐商品 -->
        <view class="recommend-section">
          <view class="section-title">
            <text>为你推荐</text>
          </view>
          <scroll-view class="recommend-list" scroll-x>
            <view 
              v-for="product in recommendProducts" 
              :key="product.id"
              class="recommend-item"
              @click="goToProduct(product.id)"
            >
              <image :src="product.image" mode="aspectFill" />
              <view class="recommend-info">
                <text class="recommend-title">{{ product.title }}</text>
                <text class="recommend-price">¥{{ product.price }}</text>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view v-if="cartItems.length > 0" class="bottom-bar">
      <view class="select-all" @click="toggleSelectAll">
        <uni-icons 
          :type="isAllSelected ? 'checkbox-filled' : 'circle'" 
          :color="isAllSelected ? '#2E8B57' : '#ccc'"
          size="20"
        />
        <text>全选</text>
      </view>
      
      <view class="price-info">
        <view class="total-price">
          <text class="label">合计：</text>
          <text class="currency">¥</text>
          <text class="amount">{{ totalPrice }}</text>
        </view>
        <view v-if="totalDiscount > 0" class="discount">
          已优惠 ¥{{ totalDiscount }}
        </view>
      </view>
      
      <button 
        class="checkout-btn"
        :class="{ disabled: selectedItems.length === 0 }"
        @click="goToCheckout"
      >
        {{ isEditing ? `删除(${selectedItems.length})` : `结算(${selectedItems.length})` }}
      </button>
    </view>

    <!-- 删除确认弹窗 -->
    <uni-popup ref="deletePopup" type="dialog">
      <uni-popup-dialog 
        type="warn"
        title="确认删除"
        content="确定要删除选中的商品吗？"
        @confirm="confirmDelete"
        @close="cancelDelete"
      />
    </uni-popup>
  </view>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRequest } from '@/common/utils/request'
import { showToast, showModal } from '@/common/utils/uni-helper'

export default {
  name: 'CartPage',
  setup() {
    const request = useRequest()
    
    // 响应式数据
    const cartItems = ref([])
    const recommendProducts = ref([])
    const isEditing = ref(false)
    const loading = ref(false)
    
    // 计算属性
    const groupedCartItems = computed(() => {
      const groups = {}
      cartItems.value.forEach(item => {
        if (!groups[item.shopId]) {
          groups[item.shopId] = {
            shopId: item.shopId,
            shopName: item.shopName,
            selected: false,
            items: []
          }
        }
        groups[item.shopId].items.push(item)
      })
      
      // 计算店铺选中状态
      Object.values(groups).forEach(shop => {
        shop.selected = shop.items.every(item => item.selected)
      })
      
      return Object.values(groups)
    })
    
    const selectedItems = computed(() => {
      return cartItems.value.filter(item => item.selected)
    })
    
    const isAllSelected = computed(() => {
      return cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
    })
    
    const totalPrice = computed(() => {
      return selectedItems.value.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0).toFixed(2)
    })
    
    const totalDiscount = computed(() => {
      return selectedItems.value.reduce((total, item) => {
        return total + (item.originalPrice - item.price) * item.quantity
      }, 0).toFixed(2)
    })
    
    // 获取购物车数据
    const getCartData = async () => {
      try {
        loading.value = true
        const response = await request.get('/api/cart/list')
        cartItems.value = response.data.map(item => ({
          ...item,
          selected: false
        }))
      } catch (error) {
        showToast('获取购物车数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取推荐商品
    const getRecommendProducts = async () => {
      try {
        const response = await request.get('/api/products/recommend')
        recommendProducts.value = response.data
      } catch (error) {
        console.error('获取推荐商品失败', error)
      }
    }
    
    // 切换编辑模式
    const toggleEdit = () => {
      isEditing.value = !isEditing.value
      if (!isEditing.value) {
        // 退出编辑模式时清除选中状态
        cartItems.value.forEach(item => {
          item.selected = false
        })
      }
    }
    
    // 切换商品选中状态
    const toggleItemSelect = (itemId) => {
      const item = cartItems.value.find(item => item.id === itemId)
      if (item) {
        item.selected = !item.selected
      }
    }
    
    // 切换店铺选中状态
    const toggleShopSelect = (shopId) => {
      const shopItems = cartItems.value.filter(item => item.shopId === shopId)
      const allSelected = shopItems.every(item => item.selected)
      
      shopItems.forEach(item => {
        item.selected = !allSelected
      })
    }
    
    // 切换全选状态
    const toggleSelectAll = () => {
      const newSelectState = !isAllSelected.value
      cartItems.value.forEach(item => {
        item.selected = newSelectState
      })
    }
    
    // 增加数量
    const increaseQuantity = async (itemId) => {
      const item = cartItems.value.find(item => item.id === itemId)
      if (item) {
        item.quantity++
        await updateCartItem(itemId, item.quantity)
      }
    }
    
    // 减少数量
    const decreaseQuantity = async (itemId) => {
      const item = cartItems.value.find(item => item.id === itemId)
      if (item && item.quantity > 1) {
        item.quantity--
        await updateCartItem(itemId, item.quantity)
      }
    }
    
    // 更新数量
    const updateQuantity = async (itemId, event) => {
      const quantity = parseInt(event.detail.value) || 1
      const item = cartItems.value.find(item => item.id === itemId)
      if (item) {
        item.quantity = Math.max(1, quantity)
        await updateCartItem(itemId, item.quantity)
      }
    }
    
    // 更新购物车商品
    const updateCartItem = async (itemId, quantity) => {
      try {
        await request.put(`/api/cart/update/${itemId}`, { quantity })
      } catch (error) {
        showToast('更新失败')
      }
    }
    
    // 删除商品
    const deleteItem = (itemId) => {
      showModal({
        title: '确认删除',
        content: '确定要删除这个商品吗？',
        success: (res) => {
          if (res.confirm) {
            removeCartItem(itemId)
          }
        }
      })
    }
    
    // 收藏商品
    const collectItem = async (itemId) => {
      try {
        await request.post('/api/favorites/add', { productId: itemId })
        showToast('已添加到收藏')
      } catch (error) {
        showToast('收藏失败')
      }
    }
    
    // 移除购物车商品
    const removeCartItem = async (itemId) => {
      try {
        await request.delete(`/api/cart/remove/${itemId}`)
        const index = cartItems.value.findIndex(item => item.id === itemId)
        if (index > -1) {
          cartItems.value.splice(index, 1)
        }
        showToast('删除成功')
      } catch (error) {
        showToast('删除失败')
      }
    }
    
    // 批量删除
    const confirmDelete = async () => {
      try {
        const itemIds = selectedItems.value.map(item => item.id)
        await request.post('/api/cart/batch-remove', { itemIds })
        
        // 从本地数据中移除
        cartItems.value = cartItems.value.filter(item => !item.selected)
        showToast('删除成功')
      } catch (error) {
        showToast('删除失败')
      }
    }
    
    const cancelDelete = () => {
      // 取消删除
    }
    
    // 去购物
    const goShopping = () => {
      uni.switchTab({
        url: '/pages/index/index'
      })
    }
    
    // 跳转到商品详情
    const goToProduct = (productId) => {
      uni.navigateTo({
        url: `/pages/product/product?id=${productId}`
      })
    }
    
    // 去结算
    const goToCheckout = () => {
      if (isEditing.value) {
        // 编辑模式下执行删除
        if (selectedItems.value.length > 0) {
          confirmDelete()
        }
      } else {
        // 正常模式下去结算
        if (selectedItems.value.length === 0) {
          showToast('请选择要结算的商品')
          return
        }
        
        const itemIds = selectedItems.value.map(item => item.id)
        uni.navigateTo({
          url: `/pages/checkout/checkout?items=${JSON.stringify(itemIds)}`
        })
      }
    }
    
    // 页面加载
    onMounted(() => {
      getCartData()
      getRecommendProducts()
    })
    
    return {
      cartItems,
      recommendProducts,
      isEditing,
      loading,
      groupedCartItems,
      selectedItems,
      isAllSelected,
      totalPrice,
      totalDiscount,
      toggleEdit,
      toggleItemSelect,
      toggleShopSelect,
      toggleSelectAll,
      increaseQuantity,
      decreaseQuantity,
      updateQuantity,
      deleteItem,
      collectItem,
      confirmDelete,
      cancelDelete,
      goShopping,
      goToProduct,
      goToCheckout
    }
  }
}
</script>

<style lang="scss" scoped>
.cart-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $bg-secondary;
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-md;
  background-color: $white;
  border-bottom: 1px solid $border-color;
  
  .navbar-title {
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
    color: $text-primary;
  }
  
  .navbar-action {
    color: $primary-color;
    font-size: $font-size-base;
  }
}

.cart-list {
  flex: 1;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: $spacing-5xl;
  
  .empty-image {
    width: 120px;
    height: 120px;
    margin-bottom: $spacing-lg;
  }
  
  .empty-text {
    font-size: $font-size-base;
    color: $text-muted;
    margin-bottom: $spacing-xl;
  }
  
  .go-shopping-btn {
    background-color: $primary-color;
    color: $white;
    border-radius: $border-radius-full;
    padding: $spacing-sm $spacing-xl;
    font-size: $font-size-base;
  }
}

.cart-content {
  padding: $spacing-md;
}

.shop-group {
  background-color: $white;
  border-radius: $border-radius-lg;
  margin-bottom: $spacing-md;
  overflow: hidden;
  
  .shop-header {
    display: flex;
    align-items: center;
    padding: $spacing-md;
    border-bottom: 1px solid $border-light;
    gap: $spacing-sm;
    
    .shop-info {
      display: flex;
      align-items: center;
      gap: $spacing-xs;
      
      .shop-name {
        font-size: $font-size-base;
        font-weight: $font-weight-medium;
        color: $text-primary;
      }
    }
  }
}

.cart-item {
  display: flex;
  align-items: center;
  padding: $spacing-md;
  gap: $spacing-sm;
  border-bottom: 1px solid $border-light;
  
  &:last-child {
    border-bottom: none;
  }
  
  .item-image {
    width: 80px;
    height: 80px;
    border-radius: $border-radius-md;
    overflow: hidden;
    
    image {
      width: 100%;
      height: 100%;
    }
  }
  
  .item-info {
    flex: 1;
    
    .item-title {
      font-size: $font-size-base;
      color: $text-primary;
      @include text-ellipsis(2);
      margin-bottom: $spacing-xs;
    }
    
    .item-spec {
      font-size: $font-size-sm;
      color: $text-muted;
      margin-bottom: $spacing-sm;
    }
    
    .item-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .item-price {
        .currency {
          font-size: $font-size-sm;
          color: $error-color;
        }
        
        .amount {
          font-size: $font-size-lg;
          font-weight: $font-weight-bold;
          color: $error-color;
        }
      }
      
      .quantity-control {
        display: flex;
        align-items: center;
        border: 1px solid $border-color;
        border-radius: $border-radius-md;
        
        .quantity-btn {
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: $bg-light;
          
          &.disabled {
            opacity: 0.5;
          }
          
          &.decrease {
            border-right: 1px solid $border-color;
          }
          
          &.increase {
            border-left: 1px solid $border-color;
          }
        }
        
        .quantity-input {
          width: 50px;
          height: 32px;
          text-align: center;
          font-size: $font-size-sm;
        }
      }
      
      .edit-actions {
        display: flex;
        gap: $spacing-sm;
        
        button {
          padding: $spacing-xs $spacing-sm;
          border-radius: $border-radius-sm;
          font-size: $font-size-sm;
          
          &.collect-btn {
            background-color: $bg-light;
            color: $text-secondary;
          }
          
          &.delete-btn {
            background-color: $error-color;
            color: $white;
          }
        }
      }
    }
  }
}

.recommend-section {
  margin-top: $spacing-lg;
  
  .section-title {
    font-size: $font-size-base;
    font-weight: $font-weight-medium;
    color: $text-primary;
    margin-bottom: $spacing-md;
  }
  
  .recommend-list {
    white-space: nowrap;
    
    .recommend-item {
      display: inline-block;
      width: 120px;
      margin-right: $spacing-md;
      background-color: $white;
      border-radius: $border-radius-md;
      overflow: hidden;
      
      image {
        width: 100%;
        height: 120px;
      }
      
      .recommend-info {
        padding: $spacing-sm;
        
        .recommend-title {
          font-size: $font-size-sm;
          color: $text-primary;
          @include text-ellipsis(2);
          margin-bottom: $spacing-xs;
        }
        
        .recommend-price {
          font-size: $font-size-sm;
          color: $error-color;
          font-weight: $font-weight-medium;
        }
      }
    }
  }
}

.bottom-bar {
  display: flex;
  align-items: center;
  padding: $spacing-md;
  background-color: $white;
  border-top: 1px solid $border-color;
  @include safe-area-inset(padding-bottom, bottom);
  
  .select-all {
    display: flex;
    align-items: center;
    gap: $spacing-xs;
    margin-right: $spacing-lg;
    
    text {
      font-size: $font-size-base;
      color: $text-primary;
    }
  }
  
  .price-info {
    flex: 1;
    text-align: right;
    
    .total-price {
      .label {
        font-size: $font-size-base;
        color: $text-primary;
      }
      
      .currency {
        font-size: $font-size-sm;
        color: $error-color;
      }
      
      .amount {
        font-size: $font-size-xl;
        font-weight: $font-weight-bold;
        color: $error-color;
      }
    }
    
    .discount {
      font-size: $font-size-xs;
      color: $text-muted;
    }
  }
  
  .checkout-btn {
    background-color: $primary-color;
    color: $white;
    border-radius: $border-radius-full;
    padding: $spacing-sm $spacing-lg;
    font-size: $font-size-base;
    margin-left: $spacing-md;
    
    &.disabled {
      background-color: $gray-300;
      color: $gray-500;
    }
  }
}
</style>