<script setup lang="ts">
import itemGoods from '../../components/goodsItem/index.vue'
import { StaticUrl } from '@/config'
import router from '@/router'

const props = defineProps<{ error: any, lastPage: boolean, categoryList: Api.xsbCategories[], swiper: Api.xsbAdvertInfo[], hotText: Api.xsbSearchTerm[], recommendText: Api.xsbSearchTerm[], loading: boolean, goodsList: Api.xsbCategoryProductList[] }>()

const emit = defineEmits(['changeNav', 'scrollBottom'])

const { statusBarHeight, MenuButtonHeight } = storeToRefs(useSysStore())
const { topNavActive, leftActive, backTop, SelectShopInfo, opcity } = storeToRefs(useSysXsbStore())
const swiperList = computed(() => props.swiper)
const navActive = ref(0)
const classfiylist = computed(() => props.categoryList.slice(0, 10))
const swiperClassList = computed(() => props.categoryList.slice(10, props.categoryList.length))
const scrollTop = ref()
const currentIndex = ref([0, 1, 2, 3, 4])
const navList = ref([
  { title: '为你推荐' },
  { title: '疯狂折扣' },
  { title: '' },
  { title: '地道特产' },
  { title: '预售' },
])
const textArray = ref([
  '因订单高峰期，配送可能延迟，请提前下单',
])
function handleChangeNav(idx: number) {
  navActive.value = idx
}
function handleScroll(e: UniHelper.ScrollViewOnScrollEvent) {
  const calculatedOpacity = e.detail.scrollTop / 100
  opcity.value = Math.min(1, Math.max(0.1, calculatedOpacity))
}
onMounted(() => {
  opcity.value = 0
})

function handleCommonClass(item: Api.xsbCategories) {
  console.log(item, '===================')
  if (!item.children) {
    useGlobalToast().show('敬请期待！')
    return
  }

  topNavActive.value = item.code
  leftActive.value = item.children && item.children[0].code
  emit('changeNav')
}
function handleSwiperClick(e: { index: number, item: Api.xsbCategories }) {
  handleCommonClass(e.item)
}
function handleGo(e: { index: number, item: Api.xsbAdvertInfo }) {
  console.log(e, '跳转消息')
}

const state = computed(() => {
  return props.error ? 'error' : !props.lastPage ? 'loading' : 'finished'
})

watch(() => backTop.value, () => {
  if (backTop.value) {
    scrollTop.value = null
    nextTick(() => {
      scrollTop.value = 0
    })
    backTop.value = false
  }
})
function handleChangeSwiper(e: UniHelper.SwiperOnChangeEvent) {
  const current = e.detail.current
  const total = swiperClassList.value.length

  // 确保最多取到数组末尾，不足5个时从前面补
  const newIndices = []
  for (let i = 0; i < 5; i++) {
    let index = current + i
    if (index >= total) {
      // 如果超出范围，从0开始补足
      index = i
    }
    newIndices.push(index)
  }

  currentIndex.value = newIndices
}
</script>

<template>
  <view class="page-xsb">
    <wd-navbar
      title=""
      :custom-style="`background-color: ${hexToRgba(useManualThemeStore().themeVars.colorTheme as string, opcity)};`"
      :bordered="false" :z-index="99" safe-area-inset-top left-arrow fixed @click-left="router.back()"
    >
      <template #left>
        <view class="h-full flex items-center">
          <wd-icon name="arrow-left" size="22px" color="#fff" />
          <view class="ml10rpx flex items-center" @click.stop="router.push({ name: 'xsb-selectAddress' })">
            <image :src="`${StaticUrl}/location.png`" class="h33.8rpx w29rpx" />
            <view class="ml10rpx max-w-280rpx truncate text-32rpx text-white">
              {{ SelectShopInfo?.shopName || '请选择位置' }}
            </view>
          </view>
        </view>
      </template>
    </wd-navbar>
    <scroll-view
      :lower-threshold="80"
      scroll-y enable-passive scroll-anchoring :scroll-top="scrollTop" class="ios content" @scroll="handleScroll" @scrolltolower="emit('scrollBottom')"
    >
      <view
        class="header-linear h320rpx px24rpx"
        :style="{ paddingTop: `${(Number(statusBarHeight) || 44) + MenuButtonHeight + 12}px` }"
      >
        <wd-skeleton animation="gradient" theme="image" :loading="loading" :row-col="[{ height: '30px', width: '100%' }]">
          <view class="h60rpx w-full flex items-center justify-between rounded-40rpx bg-white pr6rpx" @click="router.push({ name: 'xsb-search' })">
            <view class="flex items-center pb14rpx pl24rpx pt16rpx">
              <wd-icon name="search" size="14" color="#ccc" />
              <view class="search ml12rpx h-full w-full overflow-hidden">
                <wd-notice-bar
                  :text="hotText.map((it) => it.searchName)" custom-class="notice-bar" color="#ccc"
                  background-color="#fff" direction="vertical"
                />
              </view>
            </view>
            <view
              class="h50rpx w96rpx flex items-center justify-center rounded-26rpx bg-[var(--them-color)] text-24rpx text-white font-semibold"
            >
              搜索
            </view>
          </view>
        </wd-skeleton>
        <scroll-view v-if="recommendText.length" scroll-x class="mb20rpx mt20rpx h44rpx whitespace-nowrap">
          <view class="h-full flex items-center">
            <view
              v-for="item in recommendText"
              :key="item.id" class="mr32rpx h-full flex items-center justify-center rounded-22rpx bg-[rgba(255,255,255,.5)] px16rpx text-24rpx"
              @click="router.push({ name: 'xsb-search', params: { text: item.searchName } })"
            >
              {{ item.searchName }}
            </view>
          </view>
        </scroll-view>
      </view>

      <view class="px24rpx" :class="[recommendText.length ? '-mt180rpx' : '-mt240rpx']">
        <wd-skeleton theme="image" animation="gradient" :loading="loading" :row-col="[{ height: '138px', width: '100%' }]">
          <wd-swiper
            :list="swiperList" :height="138" :indicator="false" value-key="advertImg" @click="handleGo"
          />
        </wd-skeleton>
        <view class="mt20rpx">
          <wd-card title="" custom-class="card-zt">
            <view :class="[loading ? 'p24rpx' : '']">
              <wd-skeleton
                :loading="loading"
                theme="image" :row-col="[
                  [
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                  ],
                  [
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                  ],
                  [
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                    { width: '48px', height: '48px' },
                  ],
                ]"
              >
                <view class="px24rpx pt24rpx">
                  <view class="grid grid-cols-5 gap-x-24rpx gap-y-24rpx">
                    <view v-for="item, index in classfiylist" :key="index" class="relative">
                      <view @click="handleCommonClass(item)">
                        <image :src="item.icon" class="h100rpx w100rpx" />
                        <view class="mt12rpx whitespace-nowrap text-nowrap text-24rpx text-#222">
                          {{ item.name }}
                        </view>
                      </view>
                      <view v-if="!item.children" class="absolute left-0 top-0 h100rpx w100rpx flex items-center justify-center rounded-26rpx bg-[rgba(0,0,0,0.6)] text-16rpx text-white">
                        敬请期待
                      </view>
                    </view>
                  </view>
                </view>

                <view v-if="swiperClassList.length" class="swiper-img swiper mt26rpx">
                  <swiper class="h125rpx gap-16rpx" :display-multiple-items="5" @change="handleChangeSwiper">
                    <swiper-item v-for="item, idx in swiperClassList" :key="item.id" class="mb20rpx flex flex-col items-center text-center" @click="handleSwiperClick({ index: idx, item })">
                      <view class="pic-box">
                        <image class="h72rpx w72rpx" :src="item.icon" />
                      </view>
                      <view class="text-24rpx text-#222">
                        {{ item.name }}
                      </view>
                      <view v-if="!item.children" class="absolute left-50% top-0 h72rpx w72rpx flex items-center justify-center rounded-26rpx bg-[rgba(0,0,0,0.6)] text-16rpx text-white -translate-x-50%">
                        敬请期待
                      </view>
                    </swiper-item>
                  </swiper>
                  <view class="mt24rpx flex items-center justify-center">
                    <view v-for="item, idx in swiperClassList" :key="idx" class="mr14rpx transition-all transition-duration-400 ease-in" :class="[currentIndex.includes(idx) ? 'rounded-12rpx w-40rpx h12rpx bg-[var(--them-color)]' : 'w12rpx h12rpx rounded-50% bg-#F0F0F0']" />
                  </view>
                </view>
              </wd-skeleton>
            </view>
          </wd-card>
        </view>
        <view class="mt20rpx">
          <wd-notice-bar direction="vertical" :text="textArray" :delay="3" color="#222222" background-color="#fff">
            <template #prefix>
              <view class="mr20rpx">
                <wd-icon name="sound" size="22px" color="var(--them-color)" />
              </view>
            </template>
          </wd-notice-bar>
        </view>
        <view class="relative mt20rpx box-border" @click="useGlobalToast().show('敬请期待 ！')">
          <image :src="`${StaticUrl}/xsb-index-bg.jpg`" class="h236rpx w-full rounded-16rpx" />
          <!-- <view class="absolute left-0 top-0 box-border h-full w-full flex items-end justify-between px16rpx pb16rpx">
            <image
              :src="`${StaticUrl}/xsb-index1.png`"
              class="h148rpx w328rpx"
            />
            <image
              :src="`${StaticUrl}/xsb-index2.png`"
              class="h148rpx w328rpx"
            />
          </view> -->
        </view>
        <view class="my20rpx">
          <scroll-view scroll-x class="whitespace-nowrap">
            <view class="h40rpx flex items-center">
              <view v-for="item, idx in navList" :key="idx" class="relative mr44rpx" @click="handleChangeNav(idx)">
                <image v-if="idx == 2" :src="`${StaticUrl}/chaozhi.png`" class="relative z-2 h-29.06rpx w-105.34rpx" />
                <view
                  v-show="idx != 2" class="relative z-2 text-32rpx"
                  :class="[navActive == idx ? 'text-36rpx font-semibold' : '']"
                >
                  {{ item.title }}
                </view>
                <view
                  v-show="navActive == idx"
                  class="nav-line absolute bottom-0rpx left-50% z-1 h18rpx w80rpx rounded-10rpx -translate-x-50%"
                />
              </view>
            </view>
          </scroll-view>
        </view>
        <view class="mt20rpx">
          <wd-skeleton theme="image" animation="gradient" :loading="loading" :row-col="[[{ height: '568rpx', width: '344rpx' }, { height: '568rpx', width: '344rpx' }], [{ height: '568rpx', width: '344rpx' }, { height: '568rpx', width: '344rpx' }]]">
            <view class="flex items-center">
              <view class="w-full columns-2 gap-[10px]">
                <view class="mb-[10px] break-inside-avoid">
                  <wd-swiper
                    :autoplay="false" :list="[
                      `${StaticUrl}/xsb-swiper1.png`,
                      `${StaticUrl}/xsb-swiper2.png`,
                    ]" :height="231"
                    :indicator="{ type: 'dots-bar' }"
                    @click="useGlobalToast().show('敬请期待 ！')"
                  />
                </view>
                <view v-for="it in goodsList" :key="it.id" class="mb-[10px] break-inside-avoid">
                  <itemGoods :item-goods="it" />
                </view>
              </view>
            </view>
          </wd-skeleton>
        </view>
        <wd-loadmore :state="state" :loading-props="{ color: '#9ED605', size: 20 }" @reload="emit('scrollBottom')" />
      </view>
      <view class="h60rpx" />
    </scroll-view>
  </view>
</template>

<style scoped lang="scss">
.content {
  height: calc(100vh - var(--window-top) - 100rpx);
}
.nav-line{
  background: linear-gradient( 90deg, #9ED605 0%, rgba(158,214,5,0.7) 43%, rgba(158,214,5,0.2) 79%, rgba(158,214,5,0) 100%);
}
</style>
