<template>
  <Theme>
    <view class="wrap">
      <Navbar fixed leftShow leftIconColor="var(--bg)">
        <template #center>
          <view class="nav_title">
            <trans _t="购物车" />
          </view>
          <view class="nav_title" v-if="cartNum">({{ cartNum }})</view>
        </template>
        <template #right>
          <view
            class="nav_right"
            @click.stop="delCart"
            v-if="selectedIds.length"
          >
            <trans _t="删除" />
          </view>
        </template>
      </Navbar>

      <view class="tab" id="tabs">
        <Tab :active="activeTab" :tabList="tabList" @confirm="tabClick" />
      </view>

      <view
        class="content"
        :style="{ '--height': footerHeight + tabbarHeight + tabHeight + 'px' }"
      >
        <view class="cont_wrap">
          <!-- 购物车为空 -->
          <view class="empty-cart" v-if="!cartList.length">
            <image src="/static/shop/empty_cart.png" class="empty-image" />
            <text class="empty-text">购物车空空如也</text>
            <view class="empty-btn" @click="goShopping">
              <trans _t="去逛逛" />
            </view>
          </view>

          <!-- 购物车列表 -->
          <view class="cart-list" v-else>
            <view class="cart-item" v-for="item in cartList" :key="item.id">
              <view class="item-checkbox">
                <up-checkbox
                  :checked="item.checked"
                  @change="toggleItem(item, $event)"
                  activeColor="var(--black)"
                  shape="circle"
                />
              </view>

              <view class="item-content" @click="toProductDetail(item)">
                <image :src="item.image" class="item-image" />
                <view class="item-info">
                  <text class="item-name">{{ item.name }}</text>
                  <text class="item-spec">{{ item.spec }}</text>
                  <view class="item-price-row">
                    <text class="item-price"
                      >{{ symbol.symbol }}{{ item.price }}</text
                    >
                    <view class="quantity-control">
                      <view
                        class="quantity-btn minus"
                        @click.stop="decreaseQuantity(item)"
                        :class="{ disabled: item.quantity <= 1 }"
                      >
                        -
                      </view>
                      <input
                        class="quantity-input"
                        type="number"
                        :value="item.quantity"
                        @input="updateQuantity(item, $event)"
                        @blur="validateQuantity(item)"
                      />
                      <view
                        class="quantity-btn plus"
                        @click.stop="increaseQuantity(item)"
                      >
                        +
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view
          class="footer"
          id="footer"
          :style="{ '--tabbarHeight': tabbarHeight + 'px' }"
          v-if="cartList.length"
        >
          <view class="footer_left">
            <up-checkbox
              :label="t('全选')"
              :disabled="!cartList.length"
              activeColor="var(--black)"
              shape="circle"
              labelSize="14"
              labelColor="#676969"
              iconSize="16"
              name="selectAll"
              usedAlone
              v-model:checked="selectAllChecked"
              @change="selectAllChange"
            />
          </view>
          <view class="footer_right">
            <view class="total_info">
              <view class="total_price">
                <text>合计：{{ symbol.symbol }}{{ totalPrice }}</text>
              </view>
              <view class="total_desc">
                <trans _t="已选{{ selectedCount }}件商品" />
              </view>
            </view>
            <view
              class="total_btn"
              @click.stop="checkout"
              :style="{
                opacity: canCheckout ? 1 : 0.5,
                'pointer-events': canCheckout ? 'auto' : 'none',
              }"
            >
              <trans _t="去结算" />
            </view>
          </view>
        </view>
      </view>
    </view>
    <Tabbar page="cart" @getTabbarHeight="getTabbarHeight" />
  </Theme>
</template>

<script setup>
import { computed, ref, onMounted, nextTick, watch } from "vue";
import Tabbar from "@/components/tabbar";
import Navbar from "@/components/navbar";
import Tab from "@/components/tabs";
import { useUserStore, useShopStore, useSystemStore } from "@/store";
import { t } from "@/locale";
import { onShow } from "@dcloudio/uni-app";
import { query } from "@/utils";

const useUser = useUserStore();
const useShop = useShopStore();
const useSystem = useSystemStore();
const symbol = computed(() => useSystem.getSymbol);

// 购物车数据
const cartList = ref([
  {
    id: 1,
    name: "时尚连衣裙",
    spec: "颜色：黑色 尺码：M",
    image: "/static/shop/product1.png",
    price: "299.00",
    quantity: 1,
    checked: true,
    stock: 99,
  },
  {
    id: 2,
    name: "护肤精华",
    spec: "容量：30ml",
    image: "/static/shop/product2.png",
    price: "199.00",
    quantity: 2,
    checked: true,
    stock: 50,
  },
  {
    id: 3,
    name: "无线耳机",
    spec: "颜色：白色",
    image: "/static/shop/product3.png",
    price: "599.00",
    quantity: 1,
    checked: false,
    stock: 20,
  },
]);

const cartNum = computed(() => cartList.value.length);
const selectAllChecked = ref(false);
const footerHeight = ref(0);
const tabbarHeight = ref(0);
const activeTab = ref(0);
const tabHeight = ref(0);
const tabList = ["全部", "降价商品", "库存紧张"];

const userInfo = computed(() => useUser.getuserInfo);
const token = computed(() => useUser.getToken);

// 选中的商品ID列表
const selectedIds = computed(() => {
  return cartList.value.filter((item) => item.checked).map((item) => item.id);
});

// 选中商品数量
const selectedCount = computed(() => {
  return cartList.value
    .filter((item) => item.checked)
    .reduce((sum, item) => sum + item.quantity, 0);
});

// 总价
const totalPrice = computed(() => {
  return cartList.value
    .filter((item) => item.checked)
    .reduce((sum, item) => sum + parseFloat(item.price) * item.quantity, 0)
    .toFixed(2);
});

// 是否可以结算
const canCheckout = computed(() => {
  return selectedIds.value.length > 0;
});

// 监听购物车变化，更新全选状态
watch(
  () => cartList.value,
  (list) => {
    if (!list.length) {
      selectAllChecked.value = false;
      return;
    }
    const allChecked = list.every((item) => item.checked);
    selectAllChecked.value = allChecked;
  },
  { immediate: true, deep: true }
);

// 全选/取消全选
const selectAllChange = (checked) => {
  cartList.value.forEach((item) => {
    item.checked = checked;
  });
};

// 切换单个商品选中状态
const toggleItem = (item, checked) => {
  item.checked = checked;
};

// 增加数量
const increaseQuantity = (item) => {
  if (item.quantity < item.stock) {
    item.quantity++;
  } else {
    uni.showToast({
      title: "库存不足",
      icon: "none",
    });
  }
};

// 减少数量
const decreaseQuantity = (item) => {
  if (item.quantity > 1) {
    item.quantity--;
  }
};

// 更新数量
const updateQuantity = (item, event) => {
  const value = parseInt(event.detail.value) || 1;
  if (value > item.stock) {
    item.quantity = item.stock;
    uni.showToast({
      title: "库存不足",
      icon: "none",
    });
  } else if (value < 1) {
    item.quantity = 1;
  } else {
    item.quantity = value;
  }
};

// 验证数量
const validateQuantity = (item) => {
  if (item.quantity < 1) {
    item.quantity = 1;
  }
};

// 删除购物车
const delCart = () => {
  if (selectedIds.value.length === 0) {
    uni.showToast({
      title: "请选择要删除的商品",
      icon: "none",
    });
    return;
  }

  uni.showModal({
    title: "确认删除",
    content: `确定要删除选中的${selectedIds.value.length}件商品吗？`,
    success: (res) => {
      if (res.confirm) {
        cartList.value = cartList.value.filter((item) => !item.checked);
        selectAllChecked.value = false;
      }
    },
  });
};

// 去结算
const checkout = () => {
  if (!canCheckout.value) {
    uni.showToast({
      title: "请选择要结算的商品",
      icon: "none",
    });
    return;
  }

  const selectedItems = cartList.value.filter((item) => item.checked);
  uni.navigateTo({
    url: `/pagesBuyer/cart/checkout?items=${JSON.stringify(selectedItems)}`,
  });
};

// 去购物
const goShopping = () => {
  uni.switchTab({
    url: "/pagesBuyer/home/index",
  });
};

// 查看商品详情
const toProductDetail = (item) => {
  uni.navigateTo({
    url: `/pagesBuyer/home/product?id=${item.id}`,
  });
};

// 切换标签
const tabClick = (item, index) => {
  if (activeTab.value === index) return;
  activeTab.value = index;
  // 根据标签筛选商品
  filterCartItems(index);
};

// 筛选购物车商品
const filterCartItems = (tabIndex) => {
  // 这里可以根据不同标签筛选商品
  // 0: 全部, 1: 降价商品, 2: 库存紧张
  switch (tabIndex) {
    case 0:
      // 显示全部商品
      break;
    case 1:
      // 显示降价商品（这里简化处理）
      break;
    case 2:
      // 显示库存紧张商品（库存小于10）
      break;
  }
};

const getHeight = async () => {
  try {
    const res = await query("#footer");
    const resTab = await query("#tabs");
    nextTick(() => {
      tabHeight.value = resTab.height;
      footerHeight.value = res.height;
    });
  } catch (error) {}
};

const getTabbarHeight = (height) => {
  tabbarHeight.value = height;
};

onMounted(() => {
  getHeight();
});

onShow(() => {
  setTimeout(() => {
    getHeight();
  }, 0);
});
</script>

<style lang="less" scoped>
@import url("@/style.less");

.wrap {
  min-height: 100vh;
  background: var(--bg);
  overflow: hidden;
  .flex();
  flex-direction: column;

  :deep(.u-navbar__content) {
    background-color: var(--black) !important;
  }

  .nav_title {
    color: var(--light);
  }

  .nav_right {
    color: var(--primary);
    .size(24rpx);
    font-weight: 500;
  }

  .content {
    flex-grow: 1;
    height: calc(100vh - 44px - var(--height));
    overflow-y: scroll;
    .flex();
    flex-direction: column;

    .cont_wrap {
      flex-grow: 1;
      overflow: hidden scroll;
      padding: 0 30rpx;
    }

    .empty-cart {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 60vh;

      .empty-image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 32rpx;
      }

      .empty-text {
        font-size: 32rpx;
        color: var(--text-01);
        margin-bottom: 48rpx;
      }

      .empty-btn {
        background: var(--black);
        color: var(--light);
        padding: 24rpx 48rpx;
        border-radius: 40rpx;
        font-size: 28rpx;
      }
    }

    .cart-list {
      .cart-item {
        display: flex;
        align-items: flex-start;
        background: var(--light);
        border-radius: 20rpx;
        padding: 24rpx;
        margin-bottom: 16rpx;

        .item-checkbox {
          margin-right: 20rpx;
          margin-top: 8rpx;
        }

        .item-content {
          flex: 1;
          display: flex;

          .item-image {
            width: 160rpx;
            height: 160rpx;
            border-radius: 16rpx;
            margin-right: 20rpx;
          }

          .item-info {
            flex: 1;
            display: flex;
            flex-direction: column;

            .item-name {
              font-size: 28rpx;
              color: var(--black);
              margin-bottom: 8rpx;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
            }

            .item-spec {
              font-size: 24rpx;
              color: var(--text-01);
              margin-bottom: 16rpx;
            }

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

              .item-price {
                font-size: 32rpx;
                font-weight: bold;
                color: var(--red);
              }

              .quantity-control {
                display: flex;
                align-items: center;
                border: 1rpx solid var(--border-color);
                border-radius: 8rpx;

                .quantity-btn {
                  width: 60rpx;
                  height: 60rpx;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  font-size: 32rpx;
                  color: var(--text);
                  background: var(--bg);

                  &.disabled {
                    color: var(--text-01);
                    background: var(--inputBg);
                  }

                  &.minus {
                    border-right: 1rpx solid var(--border-color);
                  }

                  &.plus {
                    border-left: 1rpx solid var(--border-color);
                  }
                }

                .quantity-input {
                  width: 80rpx;
                  height: 60rpx;
                  text-align: center;
                  font-size: 28rpx;
                  border: none;
                  background: transparent;
                }
              }
            }
          }
        }
      }
    }

    .footer {
      .flex_position(space-between);
      flex-wrap: wrap;
      padding: 8px 12px;
      background-color: var(--light);
      box-shadow: 0 -4px 6px #0000000d;
      position: fixed;
      bottom: var(--tabbarHeight);
      left: 0;
      right: 0;
      box-sizing: border-box;

      &_left {
        display: flex;
        align-items: center;
      }

      &_right {
        .ver();

        .total_info {
          .total_price {
            text-align: right;
            color: var(--red);
            .size();
            font-weight: 700;
            line-height: 48rpx;
          }

          .total_desc {
            color: var(--text-01);
            .size(24rpx);
            line-height: 40rpx;
            text-align: right;
          }
        }

        .total_btn {
          .size(28rpx);
          font-weight: 700;
          height: 38px;
          margin-left: 16rpx;
          min-width: 180rpx;
          background-color: var(--black);
          color: var(--light);
          border-radius: 16rpx;
          padding: 16rpx 30rpx;
          text-align: center;
        }
      }
    }
  }
}
</style>
