<script setup lang="ts">
import { getCategoryApi, getClassifyDetailApi } from '@/api/catogory'
import type { categoryTopItem } from '@/types/category'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { computed, nextTick, watch } from 'vue'
import { ref } from 'vue'
import { fullUrl } from '@/utils/common'
import { pageUrl } from '@/utils/constants'

//一级tab标识
const activeIndex = ref(0)
//分类数据
const categoryList = ref<categoryTopItem[]>([])
//获取顶级分类数据
const fetchTopCategory = async () => {
  const res = await getCategoryApi()
  categoryList.value = res.result
}
//切换一级分类
const onChangeCategory = (index: number) => {
  activeIndex.value = index
  //重置下标防止错位
  secondaryTabIndex.value = 0
  uni.setStorageSync('activeCategoryIndex', index)
}
//二级所有分类弹窗ref
const allSecondaryRef = ref()
const showAllSecondary = () => {
  allSecondaryRef.value.open()
}
const hiddenAllSecondary = () => {
  allSecondaryRef.value.close()
}
//二级分类tab标识
const secondaryTabIndex = ref(0)
const onChangeSecondary = (index: number) => {
  secondaryTabIndex.value = index
}
const selectSecondary = (index: number) => {
  if (categoryList.value[activeIndex.value].children.length <= 0) return
  secondaryTabIndex.value = index
  allSecondaryRef.value.close()
}
//分类商品列表
const paging = ref()
const secondaryData = ref()
const querySecondary = (page: number, page_size: number) => {
  if (categoryList.value.length <= 0) return
  if (categoryList.value[activeIndex.value]?.children.length <= 0) return

  const item = categoryList.value[activeIndex.value].children[secondaryTabIndex.value]
  if (item?.classify_id === undefined || item.classify_id === '') {
    console.warn('没有分类ID')
    return
  }

  getClassifyDetailApi({
    page,
    page_size,
    classify_id: item.classify_id,
  }).then((res) => {
    paging.value.complete(res.result.data)
  })
}
const activeTabIndex = computed(() => {
  return activeIndex.value + '-' + secondaryTabIndex.value
})
// 监听分类切换
watch(activeIndex, () => {
  secondaryTabIndex.value = 0
})

watch(activeTabIndex, (newVal) => {
  if (newVal) {
    nextTick(() => {
      paging.value?.reload()
    })
  }
})

onLoad(() => {
  uni.setStorageSync('activeCategoryIndex', 0)
})

onShow(() => {
  activeIndex.value = uni.getStorageSync('activeCategoryIndex') || 0
  fetchTopCategory()
})
</script>

<template>
  <view class="viewport">
    <z-paging
      :pagingStyle="{
        backgroud: '#fff',
      }"
      empty-view-text="该分类下暂无商品,看看别的分类吧"
      :empty-view-fixed="false"
    >
      <template #top>
        <shop-goods-search />
      </template>

      <template #left>
        <view class="categories">
          <!-- 左侧：一级分类 -->
          <scroll-view class="primary" scroll-y>
            <view
              v-for="(item, index) in categoryList"
              :key="index"
              class="item"
              @tap="onChangeCategory(index)"
              :class="{ active: index === activeIndex }"
            >
              <text class="name"> {{ item.name }} </text>
            </view>
          </scroll-view>
        </view>
      </template>

      <scroll-view class="secondary" scroll-y v-if="categoryList[activeIndex]?.children.length > 0">
        <z-tabs
          :list="categoryList[activeIndex].children"
          @change="onChangeSecondary"
          :current="secondaryTabIndex"
          :scroll-count="1"
        >
          <template #right>
            <view class="all" @tap="showAllSecondary">
              <text class="icon icon-more"></text>
              <text class="text">全部</text>
            </view>
          </template>
        </z-tabs>
        <!-- 展开全部二级 -->
        <view class="all-secondary">
          <uni-drawer ref="allSecondaryRef" mode="right" :mask-click="false">
            <view class="all-secondary-title">
              {{ categoryList[activeIndex].name }}
            </view>
            <scroll-view style="height: 100%" scroll-y>
              <view class="seconday-panel">
                <view
                  v-for="(item, index) in categoryList[activeIndex].children"
                  class="seconday-panel-item"
                  :class="{ active: index === secondaryTabIndex }"
                  :key="index"
                  @tap="selectSecondary(index)"
                >
                  <view class="title">{{ item.name }}</view>
                  <image class="icon" :src="fullUrl(item.icon)" />
                </view>
              </view>
              <button class="seconday-panel-button" type="warn" @tap="hiddenAllSecondary">
                点击收起
              </button>
            </scroll-view>
          </uni-drawer>
        </view>

        <z-paging
          ref="paging"
          v-model="secondaryData"
          @query="querySecondary"
          :use-page-scroll="true"
          :pagingStyle="{
            backgroud: '#fff',
          }"
          empty-view-text="该分类下暂无商品,看看别的分类吧"
        >
          <view class="panel">
            <view class="section" v-for="(item, index) in secondaryData" :key="index">
              <navigator
                class="goods"
                hover-class="none"
                :url="`${pageUrl['shopping-mall-goods-detail']}?id=${item.id}`"
              >
                <view>
                  <image class="image" :src="fullUrl(item.images[0])" />
                </view>
                <view class="info">
                  <view class="name ellipsis">{{ item.name }}</view>
                  <view class="price">
                    <view class="origin">
                      <text class="symbol">¥</text>
                      <text class="number">{{ item.max_origin_price }}</text>
                    </view>
                    <view class="now">
                      <text class="symbol">¥</text>
                      <text class="number">{{ item.min_price }}</text>
                    </view>
                  </view>
                </view>
              </navigator>
            </view>
          </view>
        </z-paging>
      </scroll-view>
      <z-paging-empty-view v-else empty-view-text="该分类下暂无商品,看看别的分类吧" />
    </z-paging>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
}
.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
}
/* 分类 */
.categories {
  flex: 1;
  display: flex;
  height: 100vh;
}
/* 一级分类 */
.primary {
  overflow: hidden;
  width: 180rpx;
  flex: none;
  background-color: #f6f6f6;
  .item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 96rpx;
    font-size: 26rpx;
    color: #595c63;
    position: relative;
    &::after {
      content: '';
      position: absolute;
      left: 42rpx;
      bottom: 0;
      width: 96rpx;
      border-top: 1rpx solid #e3e4e7;
    }
  }
  .active {
    background-color: #fff;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 8rpx;
      height: 100%;
      background-color: #002fa8;
    }
  }
}
.primary .item:last-child::after,
.primary .active::after {
  display: none;
}
/* 二级分类 */
.secondary {
  background-color: #fff;
  .carousel {
    height: 200rpx;
    margin: 0 30rpx 20rpx;
    border-radius: 4rpx;
    overflow: hidden;
  }
  .panel {
    margin: 0 30rpx 0rpx;
  }
  .title {
    height: 60rpx;
    line-height: 60rpx;
    color: #333;
    font-size: 28rpx;

    .more {
      float: right;
      padding-left: 20rpx;
      font-size: 24rpx;
      color: #999;
    }
  }

  .all {
    color: #939393;
    .text {
      font-size: 30rpx;
      padding: 10rpx;
    }
  }
  .all-secondary-title {
    text-align: center;
    margin: 40rpx;
  }
  .seconday-panel {
    display: flex;
    flex-wrap: wrap;
    padding-left: 10rpx;
  }

  .seconday-panel-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    min-width: 180rpx;

    &.active {
      border: 5rpx solid #f00;
      border-radius: 10rpx;
    }
  }

  .seconday-panel-item .title {
    font-size: 28rpx;
  }

  .seconday-panel-item .icon {
    height: 100rpx;
    width: 100rpx;
    margin-bottom: 10rpx;
  }

  .seconday-panel-button {
    font-size: 20rpx;
    width: 40%;
    margin-top: 50rpx;
    border-radius: 30rpx;
  }

  .section {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    padding: 20rpx 0;
    .goods {
      width: 100%;
      display: flex;
      margin-bottom: 20rpx;
      .image {
        width: 150rpx;
        height: 150rpx;
        margin-right: 10rpx;
      }
      .info {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        width: 70%;
        .name {
          font-size: 24rpx;
        }
        .price {
          display: flex;
          flex-direction: column;
          margin-top: 10rpx;
          .origin {
            font-size: 22rpx;
            margin-right: 10rpx;
            text-decoration: line-through;
          }
          .now {
            color: red;
          }
          .symbol {
            font-size: 18rpx;
          }
        }
      }
    }
  }
}

.z-tabs-item-title {
  font-size: 24rpx !important;
}
</style>
