<script setup lang="ts">
import { publicPath } from "@/common/utils/path"
import { useCartStore } from "@/pinia/stores/cart"
import { Product, useProductStore } from "@/pinia/stores/product"
import { throttle } from "lodash-es"
import { storeToRefs } from "pinia"
import VanPopup from "vant/es/popup"
import { computed, onBeforeUnmount, onMounted, ref } from "vue"
import Cart from "./components/cart.vue"
import Detail from "./components/detail.vue"
import { useRoute } from 'vue-router'
import { useWxStore } from "@/pinia/stores/wx"
import { bindQyUserApi } from "@/common/apis/ab98"
import { getShopListApi } from "@/common/apis/shop"
import { ShopEntity } from "@/common/apis/shop/type"
import ProductContainer from "./components/ProductContainer.vue"
import RentingCabinetContainer from "./components/RentingCabinetContainer.vue"
import { useRentingCabinetStoreOutside } from "@/pinia/stores/rentingCabinet"

const router = useRouter()
const route = useRoute()
// 状态管理
const productStore = useProductStore();
const cartStore = useCartStore();
const wxStore = useWxStore();
const rentingCabinetStore = useRentingCabinetStoreOutside();

const { openid, corpidLogin, ab98User, qyUserId } = storeToRefs(wxStore);


// 滚动容器引用
const scrollContainer = ref<HTMLElement>()
// 顶部头图高度（随滚动变化）
const headerHeight = ref(150)

// 滚动事件监听器存储数组
let scrollListener: any[] = []

// 显示选择商店列表
const showShopList = ref(true);
const shopList = ref<ShopEntity[]>([]);
const shopId = ref<number>(0);

const name = ref('');
const idNum = ref('');
const showAb98BindPopup = ref(false);

// 点击分类导航
function handleShopSelect(selectedShopId: number) {
  shopId.value = selectedShopId;
  showShopList.value = false;
  productStore.setSelectedShop(shopList.value.find(shop => shop.shopId === selectedShopId)!);
  if(productStore.selectedShop?.mode == 3) {
    rentingCabinetStore.fetchRentingCabinetDetail(selectedShopId);
  } else {
    productStore.getGoods(selectedShopId);
  }
  cartStore.clearCart();
  rentingCabinetStore.clearRentingCart();
}


// 组件挂载时添加滚动监听
onMounted(async () => {
  const urlParams = new URLSearchParams(window.location.search);
  const shopIdParam = urlParams.get('shopId') || undefined;

  if (showShopList.value) {
    // 等待 handleWxCallback 完成
    await wxStore.waitForHandleWxCallbackComplete();
    getShopListApi({ corpid: wxStore.corpid }).then((res) => {
      if (res?.code === 0 && res?.data?.length > 0) {
        shopList.value = res.data;
        if (shopIdParam && shopList.value.some(shop => shop.shopId.toString() == shopIdParam)) {
          handleShopSelect(parseInt(shopIdParam));
        }
      }
    });
  } else {
    productStore.getGoods(shopId.value);
  }
  // scrollListener.push(scrollContainer.value?.addEventListener("scroll", throttledScroll))
  // scrollListener.push(scrollContainer.value?.addEventListener("scroll", throttledUpdate))
  // wxStore.fakeQyLogin();
})

// 组件卸载前清理事件监听
onBeforeUnmount(() => {
  scrollListener.forEach(listener => scrollContainer.value?.removeEventListener("scroll", listener))
  scrollListener = []
})

// 结算方法

function handleCheckout() {
  router.push("/product/checkout")
}

// 路由更新时刷新数据
watch(() => route.path, async (newPath) => {
  if (newPath === '/') {
    if (showShopList.value) {
    // 等待 handleWxCallback 完成
    await wxStore.waitForHandleWxCallbackComplete();
      getShopListApi({ corpid: wxStore.corpid }).then((res) => {
        if (res?.code === 0 && res?.data?.length > 0) {
          shopList.value = res.data;
        }
      });
    } else {
      productStore.getGoods(shopId.value);
    }
  }
}, { immediate: true });

let showAb98BindPopupOnce = false;
watch(openid, async () => {
  if (openid.value && corpidLogin.value && !ab98User.value
    && !showAb98BindPopup.value && !showAb98BindPopupOnce) {
    // 显示绑定弹窗
    showAb98BindPopup.value = true;
    showAb98BindPopupOnce = true;
  }
}, { immediate: true });

async function handleAb98Bind() {
  try {
    const ab98UserData = await bindQyUserApi({
      qyUserId: qyUserId.value,
      name: name.value,
      idNum: idNum.value
    });

    if (ab98UserData?.code === 0) {
      wxStore.setAb98User(ab98UserData.data);
      showAb98BindPopup.value = false;
      name.value = '';
      idNum.value = '';
    } else {
      console.error('绑定失败:', ab98UserData?.msg);
    }
  } catch (error) {
    console.error('绑定失败:', error);
  }
}
</script>

<template>
  <div v-if="showShopList" class="shop-list">
    <div class="shop-header" :style="{ height: `${headerHeight}px` }">
      <van-image :src="`${publicPath}cover.png`" class="shop-cover" fit="cover" />
    </div>
    <div class="shop-prompt">
      <van-cell title="请选择机柜地址：" center />
    </div>
    <van-row :gutter="[10, 10]" class="shop-row" justify="start">
      <van-col v-for="shop in shopList" :key="shop.shopId" span="12" class="shop-col">
        <div class="shop-item" @click="handleShopSelect(shop.shopId)">
          <van-image :src="shop.coverImg || `${publicPath}product-image.png`" class="shop-cover-img" fit="cover" />
          <div class="shop-info">
            <van-icon name="shop-o" size="20" class="shop-icon" />
            <div class="shop-name van-ellipsis">{{ shop.shopName }}</div>
          </div>
        </div>
      </van-col>
      <van-col v-if="shopList.length % 2 === 0" span="12" class="shop-col"></van-col>
    </van-row>
  </div>
  <div v-if="!showShopList" class="shop">
    <div class="shop-header" :style="{ height: `${headerHeight}px` }">
      <van-image :src="`${publicPath}cover.png`" class="shop-cover" fit="cover" />
    </div>
    <template v-if="productStore.selectedShop?.mode === 3">
      <RentingCabinetContainer :shop-id="productStore.selectedShop.shopId" 
      @backToShopList="showShopList = true" 
      @checkoutRenting="handleCheckout"
      />
    </template>
    <template v-else>
      <ProductContainer @backToShopList="showShopList = true" @checkout="handleCheckout" />
    </template>
  </div>
  <VanPopup v-model:show="showAb98BindPopup" position="center" :style="{ padding: '12px' }" round>
    <div style="text-align: center; font-size: 16px; font-weight: bold; margin-bottom: 16px;">请绑定汇邦云账号</div>
    <van-form @submit="handleAb98Bind">
      <van-cell-group inset>
        <van-field v-model="name" label="姓名" placeholder="请输入真实姓名" :rules="[{ required: true, message: '请填写姓名' }]" />
        <van-field v-model="idNum" label="身份证号" placeholder="请输入身份证号码"
          :rules="[{ required: true, message: '请填写身份证号' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button block type="primary" native-type="submit">
          立即绑定
        </van-button>
      </div>
    </van-form>
  </VanPopup>
</template>

<style scoped lang="scss">
.product-container {
  display: flex;
  height: 100vh;
  background: #f7f8fa;
  flex: 1;
  min-height: 0;
  position: relative;
  border-top: 1px solid #e0e0e0;
  /* 顶部边框 */
  border-top-left-radius: 8px;
  /* 左上圆角 */
  border-top-right-radius: 8px;
  /* 右上圆角 */
  overflow: hidden;
  /* 确保圆角生效 */
}

.category-nav {
  width: 100px;
  flex-shrink: 0;
}

.showShopListBtn {
  width: 100%;
  padding: 0;
  border: 0;
}

.product-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px 16px 60px;
  background: #ffffff;
}

.category-section {
  margin-bottom: 20px;
}

.category-title {
  margin: 5px;
  padding: 0;
  font-size: 16px;
  color: #333;
  font-weight: bold;
  /* background: linear-gradient(to right, #f7f8fa, transparent); */
  /* position: sticky; */
  top: 0;
  z-index: 1;
}

.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;
}

.van-sidebar-item--select:before {
  background-color: #e95d5d;
}

.van-button--primary {
  background-color: #e95d5d;
  border: 0;
  border-color: #e95d5d;
}

.sold-out-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.sold-out-text {
  color: #999;
  font-size: 14px;
  transform: rotate(-15deg);
  border: 1px solid #eee;
  padding: 2px 8px;
  border-radius: 4px;
}

.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;
}

/* 禁用状态样式 */
.van-button--disabled {
  background-color: #ccc !important;
  border-color: #ccc !important;
}

/* 商品项置灰 */
.product-item:has(.sold-out-overlay) {
  opacity: 0.6;
}

.shop {
  display: flex;
  flex-direction: column;
  height: 100%;
  /* 外层容器设置视口高度 */
}

.shop-header {
  overflow: hidden;
  transition: height 0.3s ease;
  /* 添加高度过渡动画 */
}

.shop-cover {
  /* height: 150px; */
  width: 100%;
  transform: translateY(calc((150px - var(--header-height)) / 2)
      /* 垂直居中 */
    );
  scale: calc(1 + (150 - var(--header-height)) / 150);
  /* 保持图片缩放比例 */
}

.detail-container {
  height: 100%;
}

/* 修改购物车栏样式 */
.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;
  }
}

.shop-list {
  .shop-prompt {
    margin: 8px;
    height: 44px !important;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s;

  }

  .shop-row {
    margin: 8px 0;
    padding: 0 8px;
  }

  .shop-col {
    margin-bottom: 8px;
  }

  .shop-item {
    height: auto !important;
    padding: 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s;

    .shop-info {
      display: flex;
      align-items: center;
      justify-content: start;
      padding: 12px;
    }

    .shop-cover-img {
      width: 100%;
      height: 80px;
      object-fit: cover;
    }

    .shop-name {
      white-space: normal;
      word-break: break-word;
      font-size: 14px;
      color: #333;
      font-weight: 500;
      margin: 2px 0 4px 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
    }
  }
}
</style>
