<script setup lang="ts">
import { useCartStore } from "@/pinia/stores/cart";
import { Product } from "@/pinia/stores/product";
import { storeToRefs } from "pinia";
import { showConfirmDialog } from "vant";
import { useRouter } from "vue-router";
import { useProductStore } from "@/pinia/stores/product"; // 引入 product store
import { useRentingCabinetStore } from "@/pinia/stores/rentingCabinet"; // 引入 rentingCabinet store
import type { CabinetCellEntity } from "@/common/apis/cabinet/type"; // 引入租用柜子单元类型
import { publicPath } from "@/common/utils/path";

// 定义组件事件：关闭详情
const emit = defineEmits(["cartClose"]);
const router = useRouter();

// 状态管理
const cartStore = useCartStore();
const { cartItems, totalPrice, totalQuantity } = storeToRefs(cartStore);

// 引入 productStore 获取 selectedShop
const productStore = useProductStore();
const { selectedShop } = storeToRefs(productStore);

// 引入 rentingCabinetStore 获取租用购物车数据
const rentingCabinetStore = useRentingCabinetStore();
const { rentingCartItems, rentingCartTotalQuantity } = storeToRefs(rentingCabinetStore);

// 判断当前是否为租用模式 (mode 为 3)
const isRentingMode = computed(() => selectedShop.value?.mode === 3);

// 根据模式选择渲染的列表
const currentItems = computed(() => {
  return isRentingMode.value ? rentingCartItems.value : cartItems.value;
});

// 根据模式选择渲染的总数量
const currentTotalQuantity = computed(() => {
  return isRentingMode.value ? rentingCartTotalQuantity.value : totalQuantity.value;
});

// 处理关闭按钮点击事件
function handleClose() {
  emit("cartClose");
}

// 通用处理添加到购物车或租用购物车（递增数量）
function handleAddItem(item: Product | { cabinetCell: CabinetCellEntity }) {
  if (isRentingMode.value) {
    if ('cabinetCell' in item) {
      rentingCabinetStore.addToRentingCart(item.cabinetCell);
    }
  } else {
    if ('id' in item) { // 确保是 Product 类型
      cartStore.addToCart(item);
    }
  }
}

// 通用处理从购物车或租用购物车移除（递减数量）
function handleRemoveItem(item: Product | { cabinetCell: CabinetCellEntity }) {
  if (isRentingMode.value) {
    if ('cabinetCell' in item) {
      rentingCabinetStore.removeFromRentingCart(item.cabinetCell.cellId);
    }
  } else {
    if ('id' in item) { // 确保是 Product 类型
      cartStore.removeFromCart(item.cellId);
    }
  }
}

// 通用清空购物车或租用购物车
function handleClearCartOrRentingCart() {
  showConfirmDialog({
    title: `确认清空${isRentingMode.value ? '租用' : ''}购物车吗？`
  })
    .then(() => {
      if (isRentingMode.value) {
        rentingCabinetStore.clearRentingCart();
      } else {
        cartStore.clearCart();
      }
    })
    .catch(() => {
      // on cancel
    });
}

// 结算方法
function handleCheckout() {
  handleClose();
  router.push("/product/checkout");
}
</script>

<template>
  <div class="cart-container">
    <!-- 修改后的header结构 -->
    <div class="flex-header">
      <div class="clear-header">
        <van-button
          size="small" type="primary" class="clear-btn" plain
          @click="handleClearCartOrRentingCart"
        >
          清空购物车
        </van-button>
      </div>
    </div>
    <div class="product-list">
      <!-- 根据 isRentingMode 动态渲染列表 -->
      <template v-if="isRentingMode">
        <van-cell v-for="item in rentingCartItems" :key="item.cabinetCell.cellId" class="product-item">
          <template #icon>
            <!-- 租用柜子通常没有图片，或者默认图片 -->
            <van-image :src="`${publicPath}` + 'img/product-image.svg'" width="80" height="80" class="product-image">
              <template #error>
                <div class="custom-error">
                  图片加载失败
                </div>
              </template>
            </van-image>
          </template>
          <div class="product-info">
            <div class="product-name van-ellipsis">
              <!-- 租用柜子的名称可以根据 cellNo 或其他属性生成 -->
              {{ `格口号 ${item.cabinetCell.cellNo}` }}
            </div>
            <div class="product-price">
              ¥{{ item.cabinetCell.cellPrice?.toFixed(2) }}
            </div>
            <div class="action-row">
              <span class="stock-count">
                <!-- 租用柜子可能没有库存概念，或者显示可用数量 -->
                <!-- 如果需要展示库存，item.cabinetCell 需包含 stock 字段 -->
              </span>
              <div class="cart-actions">
                <van-button size="mini" icon="minus" @click.stop="handleRemoveItem(item)" />
                <span class="cart-count">{{ item.quantity }}</span>
              </div>
            </div>
          </div>
        </van-cell>
      </template>
      <template v-else>
        <van-cell v-for="item in cartItems" :key="item.product.id" class="product-item">
          <template #icon>
            <van-image :src="item.product.image" width="80" height="80" class="product-image">
              <template #error>
                <div class="custom-error">
                  图片加载失败
                </div>
              </template>
            </van-image>
          </template>
          <div class="product-info">
            <div class="product-name van-ellipsis">
              {{ item.product.name }}
            </div>
            <div class="product-price">
              ¥{{ item.product.price.toFixed(2) }}
            </div>
            <div class="action-row">
              <span v-if="item.product.stock > 0" class="stock-count">
                还剩{{ item.product.stock }}份
              </span>
              <div class="cart-actions">
                <van-button size="mini" icon="minus" @click.stop="handleRemoveItem(item.product)" />
                <span class="cart-count">{{ item.quantity }}</span>
                <van-button
                  size="mini" type="primary" class="add-cart-btn" icon="plus"
                  @click.stop="handleAddItem(item.product)"
                />
              </div>
            </div>
          </div>
        </van-cell>
      </template>

      <!-- 底部购物车栏，根据 currentItems 的长度判断是否显示 (通用逻辑) -->
      <div v-if="currentItems.length" class="shopping-cart-bar">
        <div class="cart-info">
          <van-badge :content="currentTotalQuantity" @click.stop="handleClose()">
            <van-icon name="shopping-cart-o" size="24" />
          </van-badge>
          <div class="total-price">
            <!-- 总价可能在租用模式下不适用或显示其他信息, 这里简化处理 -->
            合计：¥{{ isRentingMode ? rentingCabinetStore.rentingCartTotalPrice : totalPrice.toFixed(2) }}
          </div>
        </div>
        <van-button type="primary" size="small" @click="handleCheckout" class="checkout-btn">
          去结算
        </van-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 保持所有样式不变，因为DOM结构尽量保持一致 */
.product-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px 16px 60px;
  background: #ffffff;
}

.product-item {
  margin-bottom: 10px;
  padding: min(2.667vw, 20px) 0;
  /* border-radius: 4px; */
  /* box-shadow: 0 2px 4px rgba(0,0,0,0.05); */
}

.product-image {
  margin-right: 12px;
  border-radius: 4px;
  overflow: hidden;
}

.product-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 80px;
  position: relative;
}

.product-name {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
  text-align: left;
}

.product-price {
  font-size: 16px;
  color: #e95d5d;
  font-weight: bold;
  text-align: left;
}

.add-cart-btn {
  align-self: flex-end;
  margin-top: 0;
  background-color: #e95d5d;
  border-color: #e95d5d;
}

.action-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  /* 底部对齐 */
  margin-top: auto;
  /* 推到容器底部 */
}

.stock-count {
  font-size: 11px;
  color: #bbbbbb;
  margin-right: 8px;
  display: flex;
  align-items: flex-end;
  height: 100%;
  line-height: 1;
}

/* 修改购物车栏样式 */
.shopping-cart-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.cart-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.total-price {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.checkout-btn {
  background-color: #e95d5d;
  border: none;
  border-radius: 16px;
  padding: 0 24px;
}

.cart-actions {
  margin-left: auto;
  align-self: flex-end;
  display: flex;
  align-items: center;
  gap: 4px;
  /* margin-left: 8px; */

  .cart-count {
    font-size: 12px;
    min-width: 20px;
    text-align: center;
  }
}

.cart-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

/* 保持其他样式不变 */
.flex-header {
  display: flex;
  justify-content: flex-end;
  background: white;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.clear-header {
  padding: 10px 16px;
  /* 添加左右边距 */
  margin-bottom: 0;
}

.clear-btn {
  color: #e95d5d;
  border-color: #e95d5d;
}
</style>
