<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useWxStore } from '@/pinia/stores/wx'
import { useProductStore } from '@/pinia/stores/product'
import { useCartStore } from '@/pinia/stores/cart'
import { getShopListApi } from '@/api/shop'
import type { ShopEntity } from '@/api/shop/types'
import ProductContainer from './components/product-container.vue';
import { generateDynamicCode, mpCodeToOpenId } from '@/api/users'
import { toHttpsUrl } from '@/utils'
import { useAb98UserStore } from '@/pinia/stores/ab98-user'
import { storeToRefs } from 'pinia'

definePage({
  style: {
    navigationBarTitleText: '首页',
  },
})

// 状态管理
const wxStore = useWxStore()
const productStore = useProductStore()
const cartStore = useCartStore()
const ab98UserStore = useAb98UserStore()

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

// 页面加载
onMounted(async () => {
  await wxStore.fakeQyLogin();
  uni.login({
    provider: 'weixin', //使用微信登录
    success: function (loginRes) {
        mpCodeToOpenId(loginRes.code).then((wxUser) => {
          console.log('wxUser:', wxUser);
          wxStore.setOpenid(wxUser.data.openid);
          wxStore.setWxUserDTO(wxUser.data);
          if (wxUser.data.ab98UserId) {
            ab98UserStore.setAb98UserName(wxUser.data.ab98Name || wxUser.data.nickName || '')
            ab98UserStore.setAb98UserFaceImg(wxUser.data.ab98FaceImg || '')
          }
        }).catch((e) => {
          console.error('mpCodeToOpenId error:', e)
        })
    },
  });
  
  if (showShopList.value) {
    try {
      // 等待 handleWxCallback 完成
      await wxStore.waitForHandleWxCallbackComplete();
      const res = await getShopListApi(wxStore.corpid || '');
      console.log('获取店铺列表:', res)
      if (res?.code === 0 && res?.data?.length > 0) {
        shopList.value = res.data;
        
        // shopList.value = [...shopList.value, ...res.data, ...res.data, ...res.data];
      }
    } catch (error) {
      console.error('获取店铺列表失败:', error)
    }
  }
})

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

// 返回店铺列表
function backToShopList() {
  showShopList.value = true
  shopId.value = 0
  productStore.categories = []
  cartStore.clearCart()
}

// 结算方法
function handleCheckout() {
  uni.navigateTo({
    url: '/pages/index/checkout'
  })
}
</script>

<template>
  <!-- 直接使用 shop-list 类，合并 shop-container 的样式 -->
  <view class="shop-list">
    <view class="shop-header">
      <wd-img
        :src="`/static/cover.jpg`"
        width="100%"
        height="150"
        mode="aspectFill"
      ></wd-img>
    </view>

    <!-- 店铺选择列表内容 -->
    <view v-if="showShopList" class="shop-list-content">
      <view class="shop-prompt">
        <view class="prompt-text">请选择机柜地址：</view>
      </view>

      <view class="shop-row">
        <view v-for="shop in shopList" :key="shop.shopId" class="shop-col" @click="handleShopSelect(shop.shopId)">
          <view class="shop-item">
            <wd-img
              :src="toHttpsUrl(shop.coverImg) || '/static/product-image.png'"
              width="100%"
              height="80"
              mode="aspectFill"
            ></wd-img>
            <view class="shop-info">
              <view class="shop-name">
                <wd-icon name="shop" size="16px" color="#666"></wd-icon>
                <text>{{ shop.shopName }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品列表 -->
    <ProductContainer
      v-if="!showShopList"
      @backToShopList="backToShopList"
      @checkout="handleCheckout"
    />
  </view>
</template>

<style scoped lang="scss">
.shop-list {
  display: flex;
  flex-direction: column;
  // height: calc(100vh - 94px - env(safe-area-inset-top) - env(safe-area-inset-bottom));
  height: 100vh;
  background: #f7f8fa;
  overflow: hidden;
  
  .shop-header {
    width: 100%;
    height: 150px;
    overflow: hidden;
    flex-shrink: 0;
  }

  .shop-list-content {
    flex: 1;
    height: calc(100vh - 150px);
  }

  .shop-prompt {
    margin: 8px;
    padding: 12px 16px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .prompt-text {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }

  .shop-row {
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    flex: 1;
    height: calc(100vh - 150px - 60px);
  }

  .shop-col {
    width: calc(50% - 4px);
    margin-bottom: 8px;
  }

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

    &:active {
      transform: scale(0.98);
    }

    .shop-info {
      padding: 12px;
    }

    .shop-name {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #333;
      font-weight: 500;

      text {
        margin-left: 4px;
      }
    }
  }
}
</style>