<template>
  <Swiper
    class="classify-scroll"
    :modules="[FreeMode]"
    free-mode
    slides-per-view="auto"
    :space-between="10"
  >
    <SwiperSlide
      v-for="(item, index) in activeTab === 0 ? storageList : exhibitList"
      :key="item.id"
    >
      <div
        class="classify-scroll-item"
        :class="{
          active: (isStorage ? storageActive : exhibitActive) === index,
        }"
        @click="handleClick(item, index)"
      >
        {{ item.name }}
      </div>
    </SwiperSlide>
  </Swiper>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { FreeMode } from "swiper/modules";
import { Swiper, SwiperSlide } from "swiper/vue";
import { getStorageTreeApi, getExhibitTypeListApi } from "@/api";

const props = defineProps({
  activeTab: {
    type: Number,
    required: true,
  },
  storageInitVal: {
    type: Number,
    default: 0,
  },
  exhibitInitVal: {
    type: Number,
    default: 0,
  },
});
const isStorage = computed(() => props.activeTab === 0);
const emits = defineEmits(["storageId", "exhibitId", "init"]);
const storageActive = ref(0);
const exhibitActive = ref(0);
const storageList = ref([]);
const exhibitList = ref([]);

const getStorageTree = async () => {
  const data = await getStorageTreeApi();
  storageList.value = data;

  if (props.storageInitVal) {
    storageActive.value = data.findIndex((i) => i.id === props.storageInitVal);
  }
};

const getExhibitTypeList = async () => {
  const data = await getExhibitTypeListApi();
  exhibitList.value = data;

  if (props.exhibitInitVal) {
    exhibitActive.value = data.findIndex((i) => i.id === props.exhibitInitVal);
  }
};

const handleClick = (item, index) => {
  if (isStorage.value) {
    storageActive.value = index;
    emits("storageId", item.id);
  } else {
    exhibitActive.value = index;
    emits("exhibitId", item.id);
  }
};

watch(
  () => props.activeTab,
  async () => {
    if (isStorage.value && !storageList.value.length) {
      await getStorageTree();
      emits("init", storageList.value[0].id);
    } else if (!isStorage.value && !exhibitList.value.length) {
      await getExhibitTypeList();
      emits("init", exhibitList.value[0].id);
    }
  },
  {
    immediate: true,
  }
);
</script>

<style scoped lang="scss">
.classify-scroll {
  padding: 35px 0 25px;
  /* prettier-ignore */
  height: 60PX;
  background: #fcfcfc;
  box-sizing: border-box;
  z-index: 10;

  .swiper-slide {
    width: auto;

    &:first-child {
      margin-left: 48px;
    }
    &:last-child {
      margin-right: 48px;
    }
  }
  &-item {
    display: inline-block;
    padding: 10px 35px;
    font-size: 27px;
    white-space: nowrap;
    color: var(--van-primary-color);
    border: 2px solid var(--van-primary-color);
    border-radius: 50px;

    &.active {
      color: var(--van-white);
      background: var(--van-primary-color);
    }
  }
}
</style>
