<template>
  <Theme>
    <view class="wrap" :style="{ '--tabbarHeight': tabbarHeight + 'px' }">
      <view class="cont">
        <view class="cont_bg" id="tob">
          <Navbar bgColor="transparent" fixed>
            <template #left>
              <view class="nav_left">
                <image
                  src="@/static/logo.png"
                  class="nav_logo"
                  mode="widthFix"
                ></image>
              </view>
            </template>
            <template #right>
              <view class="nav_right">
                <view class="icon-badge-wrap">
                  <image
                    src="/static/home/kefu.png"
                    class="mobile_system"
                    @click="toGo('/pages/setting/system')"
                  >
                  </image>
                  <up-badge
                    type="error"
                    max="99"
                    :value="unreadCount"
                    class="tips"
                    v-if="unreadCount > 0"
                  ></up-badge>
                </view>

                <image
                  src="/static/language.png"
                  class="mobile_language"
                  @click="toGo('/pages/setting/language_currency')"
                ></image>
                <navMenu />
              </view>
            </template>
          </Navbar>
          <view class="bg_top">
            <view class="search">
              <Search
                v-model="searchValue"
                border="none"
                @click="searchClick"
                :placeholder="t('搜索商品')"
              >
                <template #prefix>
                  <i class="icon-font icon-search"></i>
                </template>
                <template #suffix>
                  <i class="icon-font icon-camera"></i>
                </template>
              </Search>
            </view>
          </view>
        </view>
        <scroll-view
          class="content-scroll"
          scroll-y
          refresher-enabled
          :refresher-triggered="refreshering"
          @refresherrefresh="onRefresherRefresh"
          @refresherrestore="onRefresherRestore"
          refresher-default-style="none"
          :style="{ height: contentHeight + 'px' }"
        >
          <view class="refresher" v-if="refreshering">
            <up-loadmore :status="'loading'" :loadingText="''" />
          </view>
          <view class="content">
            <!-- 轮播图区域 -->
            <view class="banner-section">
              <Swiper @click="swiperClick" class="swiper-box" />
            </view>

            <!-- 分类导航 -->
            <view class="category-section">
              <view class="category-title">
                <trans _t="商品分类" />
              </view>
              <view class="category-grid">
                <view
                  class="category-item"
                  v-for="(item, index) in categoryList"
                  :key="index"
                  @click="toCategory(item)"
                >
                  <image :src="item.icon" class="category-icon" />
                  <text class="category-name">{{ t(item.name) }}</text>
                </view>

                <!-- 录音功能入口 -->
                <view class="category-item record-item" @click="toRecord">
                  <view class="record-icon">
                    <i class="icon-font icon-microphone"></i>
                  </view>
                  <text class="category-name">录音功能</text>
                </view>
              </view>
            </view>

            <!-- 热门商品 -->
            <view class="hot-products-section">
              <view class="section-title">
                <trans _t="热门商品" />
                <view class="more-btn" @click="toMoreProducts">
                  <trans _t="更多" />
                  <i class="icon-font icon-arrow-right"></i>
                </view>
              </view>
              <view class="products-grid">
                <view
                  class="product-item"
                  v-for="(item, index) in hotProducts"
                  :key="index"
                  @click="toProductDetail(item)"
                >
                  <image :src="item.image" class="product-image" />
                  <view class="product-info">
                    <text class="product-name">{{ item.name }}</text>
                    <view class="product-price">
                      <text class="current-price"
                        >{{ symbol.symbol }}{{ item.price }}</text
                      >
                      <text class="original-price" v-if="item.originalPrice"
                        >{{ symbol.symbol }}{{ item.originalPrice }}</text
                      >
                    </view>
                    <view class="product-tags">
                      <text class="tag" v-for="tag in item.tags" :key="tag">{{
                        tag
                      }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <IosUpdateModal />
    <blindModel />
    <Tabbar page="index" @getTabbarHeight="getTabbarHeight" />
  </Theme>
</template>

<script setup>
import Tabbar from "@/components/tabbar";
import Navbar from "@/components/navbar";
import Swiper from "@/components/swiper";
import blindModel from "@/components/blindModel";
import Search from "@/components/input";
import navMenu from "@/components/nav_menu";
import IosUpdateModal from "@/components/IosUpdateModal";
import { computed, ref, watch, nextTick, onMounted } from "vue";
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onPageScroll,
} from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import {
  useShopStore,
  useSystemStore,
  useMessageStore,
  useTabbarStore,
  useUserStore,
} from "@/store";
import { t } from "@/locale";
import { query, systemInfo } from "@/utils";

const useShop = useShopStore();
const useSystem = useSystemStore();
const useTabbar = useTabbarStore();
const useUser = useUserStore();

const langList = computed(() => useSystem.getLangeuage);
const lang = computed(() => useSystem.getLang);
const token = computed(() => useUser.getToken);
const symbol = computed(() => useSystem.getSymbol);
const userType = computed(() => useUser.getUserType);

const useMessage = useMessageStore();
const { globalMap } = storeToRefs(useMessage);
const unreadCount = ref(0);
watch(
  () => globalMap.value.noticeChannel,
  (newVal, oldVal) => {
    if (newVal) {
      unreadCount.value = newVal.unreadCount;
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

const searchValue = ref("");
const refreshering = ref(false);
const contentHeight = ref(0);
const tabbarHeight = ref(0);

// 轮播图数据
const bannerList = ref([
  {
    id: 1,
    image: "/static/home/banner1.png",
    title: "新品上市",
    action: "goto_product",
  },
  {
    id: 2,
    image: "/static/home/banner2.png",
    title: "限时优惠",
    action: "goto_activity",
  },
]);

// 分类数据
const categoryList = ref([
  { id: 1, name: "服装", icon: "/static/shop/category_clothes.png" },
  { id: 2, name: "美妆", icon: "/static/shop/category_beauty.png" },
  { id: 3, name: "数码", icon: "/static/shop/category_digital.png" },
  { id: 4, name: "家居", icon: "/static/shop/category_home.png" },
  { id: 5, name: "食品", icon: "/static/shop/category_food.png" },
  { id: 6, name: "母婴", icon: "/static/shop/category_baby.png" },
  { id: 7, name: "运动", icon: "/static/shop/category_sports.png" },
  { id: 8, name: "更多", icon: "/static/shop/category_more.png" },
]);

// 热门商品数据
const hotProducts = ref([
  {
    id: 1,
    name: "时尚连衣裙",
    image: "/static/shop/product1.png",
    price: "299.00",
    originalPrice: "399.00",
    tags: ["热销", "包邮"],
  },
  {
    id: 2,
    name: "护肤精华",
    image: "/static/shop/product2.png",
    price: "199.00",
    originalPrice: "299.00",
    tags: ["新品", "限时"],
  },
  {
    id: 3,
    name: "无线耳机",
    image: "/static/shop/product3.png",
    price: "599.00",
    originalPrice: "799.00",
    tags: ["爆款", "包邮"],
  },
  {
    id: 4,
    name: "智能手表",
    image: "/static/shop/product4.png",
    price: "1299.00",
    originalPrice: "1599.00",
    tags: ["科技", "热销"],
  },
]);

// 推荐商品数据
const recommendProducts = ref([
  {
    id: 5,
    name: "经典牛仔裤",
    image: "/static/shop/product5.png",
    price: "199.00",
    sales: 1234,
  },
  {
    id: 6,
    name: "口红套装",
    image: "/static/shop/product6.png",
    price: "299.00",
    sales: 567,
  },
  {
    id: 7,
    name: "运动鞋",
    image: "/static/shop/product7.png",
    price: "399.00",
    sales: 890,
  },
  {
    id: 8,
    name: "保温杯",
    image: "/static/shop/product8.png",
    price: "89.00",
    sales: 2345,
  },
]);

const searchClick = () => {
  toGo("/pagesBuyer/home/search");
};

const toGo = (url) => {
  if (!url) return;
  uni.navigateTo({ url });
};

const toCategory = (category) => {
  toGo(`/pagesBuyer/home/category?id=${category.id}&name=${category.name}`);
};

const toProductDetail = (product) => {
  toGo(`/pagesBuyer/home/product?id=${product.id}`);
};

const toMoreProducts = () => {
  toGo("/pagesBuyer/home/products");
};

const toRecord = () => {
  toGo("/pagesBuyer/home/record");
};

const swiperClick = (item) => {
  if (item.action == "goto_product") {
    toGo("/pagesBuyer/home/products");
  } else if (item.action == "goto_activity") {
    toGo("/pagesBuyer/home/activity");
  }
};

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

const loadPageData = async () => {
  // 加载页面数据
  await useSystem.setBoxes({}, { isLoading: true });
};

onShow(() => {
  loadPageData();
});

onMounted(() => {
  nextTick(async () => {
    const res = await query("#tob");
    const { windowHeight, statusBarHeight } = systemInfo();
    contentHeight.value = windowHeight - res.height - statusBarHeight;
  });
});

uni.hideTabBar();

const onRefresherRefresh = async () => {
  try {
    refreshering.value = true;
    await loadPageData();
  } finally {
    refreshering.value = false;
  }
};

const onRefresherRestore = () => {
  refreshering.value = false;
};
</script>

<style lang="less" scoped>
.wrap {
  background: var(--bg);
  min-height: calc(100vh - var(--tabbarHeight));
  padding-bottom: var(--tabbarHeight);

  .nav_left {
    display: flex;
    align-items: center;

    .nav_logo {
      width: 284rpx;
    }
  }

  .nav_right {
    display: flex;
    align-items: center;

    .mobile_language {
      width: 48rpx;
      height: 48rpx;
      margin: 0 20rpx 0 24rpx;
    }

    .icon-badge-wrap {
      position: relative;
      display: inline-block;
      width: 48rpx;
      height: 48rpx;

      .mobile_system {
        width: 48rpx;
        height: 48rpx;
      }

      .tips {
        position: absolute;
        right: -10rpx;
        top: -8rpx;
        z-index: 2;
      }
    }
  }

  .cont {
    width: 100%;
    background-color: var(--light);
    &_bg {
      position: sticky;
      top: 0;
      z-index: 9999;
      background-color: var(--bg);

      .bg_top {
        padding: 0 30rpx;

        .search {
          padding: 26rpx 0;

          :deep(.u-input) {
            padding: 0 20px 0 16px !important;

            .u-input__content__field-wrapper__field {
              height: 47px;
            }
          }

          .icon-search {
            color: var(--text);
            font-size: 40rpx;
          }

          .icon-camera {
            color: var(--text-01);
            font-size: 70rpx;
          }
        }

        .debug-info {
          padding: 10rpx 0;
          text-align: center;

          text {
            font-size: 24rpx;
            color: var(--primary);
            background: rgba(255, 107, 107, 0.1);
            padding: 8rpx 16rpx;
            border-radius: 20rpx;
          }
        }
      }
    }

    .content-scroll {
      overflow: hidden;
    }

    .content {
      width: 100%;
      padding: 0 30rpx 30rpx;
      position: relative;
      box-sizing: border-box;

      .banner-section {
        margin-bottom: 32rpx;

        .swiper-box {
          width: 100%;
          border-radius: 20rpx;
          overflow: hidden;
        }
      }

      .category-section {
        margin-bottom: 32rpx;

        .category-title {
          font-size: 36rpx;
          font-weight: bold;
          color: var(--black);
          margin-bottom: 24rpx;
        }

        .category-grid {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 24rpx;

          .category-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 24rpx 12rpx;
            background: var(--inputBg);
            border-radius: 20rpx;

            .category-icon {
              width: 60rpx;
              height: 60rpx;
              margin-bottom: 12rpx;
            }

            .category-name {
              font-size: 24rpx;
              color: var(--text);
              text-align: center;
            }

            &.record-item {
              background: linear-gradient(135deg, var(--primary), #ff6b6b);
              position: relative;
              overflow: hidden;

              &::before {
                content: "";
                position: absolute;
                top: -50%;
                left: -50%;
                width: 200%;
                height: 200%;
                background: radial-gradient(
                  circle,
                  rgba(255, 255, 255, 0.1) 0%,
                  transparent 70%
                );
                animation: shimmer 3s infinite;
              }

              .record-icon {
                width: 60rpx;
                height: 60rpx;
                border-radius: 50%;
                background: rgba(255, 255, 255, 0.2);
                display: flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 12rpx;
                position: relative;
                z-index: 1;

                .icon-microphone {
                  font-size: 32rpx;
                  color: var(--light);
                }
              }

              .category-name {
                color: var(--light);
                font-weight: bold;
                position: relative;
                z-index: 1;
              }
            }
          }
        }
      }

      .hot-products-section,
      .recommend-section {
        margin-bottom: 32rpx;

        .section-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 36rpx;
          font-weight: bold;
          color: var(--black);
          margin-bottom: 24rpx;

          .more-btn {
            display: flex;
            align-items: center;
            font-size: 28rpx;
            color: var(--text-01);

            .icon-arrow-right {
              margin-left: 8rpx;
              font-size: 24rpx;
            }
          }
        }

        .products-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 24rpx;

          .product-item {
            background: var(--inputBg);
            border-radius: 20rpx;
            overflow: hidden;

            .product-image {
              width: 100%;
              height: 300rpx;
              object-fit: cover;
            }

            .product-info {
              padding: 20rpx;

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

              .product-price {
                display: flex;
                align-items: center;
                margin-bottom: 12rpx;

                .current-price {
                  font-size: 32rpx;
                  font-weight: bold;
                  color: var(--red);
                  margin-right: 12rpx;
                }

                .original-price {
                  font-size: 24rpx;
                  color: var(--text-01);
                  text-decoration: line-through;
                }
              }

              .product-tags {
                display: flex;
                gap: 8rpx;

                .tag {
                  font-size: 20rpx;
                  color: var(--primary);
                  background: rgba(255, 107, 107, 0.1);
                  padding: 4rpx 12rpx;
                  border-radius: 12rpx;
                }
              }
            }
          }
        }

        .recommend-list {
          .recommend-item {
            display: flex;
            background: var(--inputBg);
            border-radius: 20rpx;
            padding: 20rpx;
            margin-bottom: 16rpx;

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

            .recommend-info {
              flex: 1;
              display: flex;
              flex-direction: column;
              justify-content: space-between;

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

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

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

                .sales {
                  font-size: 24rpx;
                  color: var(--text-01);
                }
              }
            }
          }
        }
      }
    }
  }
}

@keyframes shimmer {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
