<template>
  <div class="bar-list" v-if="metadata?.navigationTrees?.length" :class="{ barshow: isShowScenesList }">
    <div class="top-con" v-show="currentScenesList.length">
      <div
        ref="scene-swiper"
        class="scene-list swiper-container"
        id="swScenes"
        :style="`width:${Math.min(scenesListW, innerW)}px;
      padding:${scenesListW > innerW ? '0 15px' : '0'}`"
        v-if="currentScenesList.length > 0"
      >
        <ul class="swiper-wrapper">
          <template v-for="(item, i) in currentScenesList" :key="item.id">
            <li
              @click="tabCurrentScene(item)"
              class="swiper-slide"
              :style="`background-image:url(${item.icon});`"
              :class="{
                active: currentScene.sceneCode == item.sceneCode,
                loopspan: item.name.length > spanlength && currentScene.id == item.id,
              }"
            >
              <i class="iconfont" :class="item.type == '4dkk' ? 'icon-editor_3d' : 'icon-editor_panoramic'"></i>
              <div class="marquee">
                <marquee-text :repeat="1" :duration="Math.ceil(item.name.length / 10) * 5" :key="item.id" v-if="item.name.length > spanlength && currentScene.id == item.id">
                  {{ item.name }}
                </marquee-text>
                <span v-else>
                  {{ item.name }}
                </span>
              </div>
            </li>
          </template>
        </ul>
      </div>

      <div
        class="swiper-container second-group-list"
        ref="second-group-swiper"
        id="swSecondary"
        :style="`width:${Math.min(secondaryW, innerW)}px;
      padding:${secondaryW > innerW ? '0 15px' : '0'}`"
        v-if="metadata?.navigationTrees[rootTabIndex] && metadata?.navigationTrees[rootTabIndex]?.children[0]?.type == 'group' && showSecondTab"
      >
        <ul class="swiper-wrapper">
          <template v-for="(item, i) in metadata?.navigationTrees[rootTabIndex]?.children">
            <li
              class="swiper-slide"
              @click="tabSecond(item, i)"
              :class="{
                active: currentSecondId == item.id,
                loopspan: fixTitle(item.name).length > spanlength && currentSecondId == item.id,
              }"
              :key="item.id"
              v-if="item.children.length"
            >
              <marquee-text :duration="Math.ceil(fixTitle(item.name).length / 10) * 5" :key="item.id" :repeat="1" v-if="fixTitle(item.name).length > spanlength && currentSecondary.id == item.id">
                {{ fixTitle(item.name) }}
              </marquee-text>
              <span v-else>
                {{ fixTitle(item.name) }}
              </span>
            </li>
          </template>
        </ul>
      </div>
    </div>

    <div
      class="swiper-container root-group-list"
      ref="root-group"
      id="swcatalogRoot"
      :style="`width:${Math.min(catalogRootW, innerW)}px;
    padding:${catalogRootW > innerW ? '0 15px' : '0'}`"
      v-if="metadata?.navigationTrees?.length > 1"
    >
      <ul class="swiper-wrapper">
        <template v-for="(item, i) in metadata?.navigationTrees" :key="item.id">
          <li
            v-if="item.children.length"
            class="swiper-slide"
            :class="{
              active: currentRootId == item.id,
              loopspan: fixTitle(item.name).length > spanlength && currentRootId == item.id,
            }"
            @click="tabRoot(item, i)"
          >
            <marquee-text :duration="Math.ceil(fixTitle(item.name).length / 10) * 5" :key="item.id" :repeat="1" v-if="fixTitle(item.name).length > spanlength && currentRootId == item.id">
              {{ fixTitle(item.name) }}
            </marquee-text>
            <span v-else>
              {{ fixTitle(item.name) }}
            </span>
          </li>
        </template>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed, onMounted, nextTick, unref, watchEffect } from "vue";
import { useStore } from "vuex";
import { useApp } from "@/app";
import MarqueeText from "vue-marquee-text-component";
import { useI18n, getLocale } from "@/i18n";
const { t } = useI18n({ useScope: "global" });

const store = useStore();

const spanlength = ref(5);

const metadata = computed(() => store.getters["scene/metadata"]);
const scenes = computed(() => store.getters["scene/list"]);
const currentScene = computed(() => store.getters["scene/currentScene"]);
const currentSecondId = computed(() => store.getters["scene/currentSecondId"]);
const currentRootId = computed(() => store.getters["scene/currentRootId"]);

const clamp = computed(() => (num, min, max) => Math.min(Math.max(num, min), max));

const currentCatalogRoot = computed(() => store.getters["scene/currentCatalogRoot"]);
const currentSecondary = computed(() => store.getters["scene/currentSecondary"]);

const secondaryList = computed(() => store.getters["scene/secondaryList"]);

const isShowScenesList = computed(() => store.getters["functions/isShowScenesList"]);

const currentScenesList = computed(() => store.getters["scene/currentScenesList"]);

const show = ref(false);
const swidth = ref({
  swcatalogRoot: 104,
  swSecondary: 84,
  swScenes: 72,
});

const SceneSwiper = ref(null);
const SecondGroupSwiper = ref(null);
const rootGroupSwiper = ref(null);

const rootTabIndex = computed(() => {
  let idx = 0;
  if (metadata.value && metadata.value?.navigationTrees) {
    idx = metadata.value?.navigationTrees.findIndex((item) => item.id == currentRootId.value);
  }
  return idx;
});

const secondTabIndex = computed(() => {
  let idx = 0;
  if (metadata.value && metadata.value?.navigationTrees) {
    idx = metadata.value.navigationTrees[rootTabIndex.value]?.children.findIndex((item) => item.id == currentSecondId.value);
  }
  return idx;
});

const showSecondTab = computed(() => {
  return metadata.value && metadata.value?.navigationTrees ? metadata.value?.navigationTrees[rootTabIndex.value].children.some((item) => item.id != currentSecondId.value) : false;
});

const scenesListW = computed(() => currentScenesList.value.length * (swidth.value["swScenes"] + 10) - 10);
const secondaryW = computed(() => {
  let list = metadata.value?.navigationTrees[rootTabIndex.value].children.filter((item) => item.children.length);
  return list.length * (swidth.value["swSecondary"] + 10) - 10;
});

const catalogRootW = computed(() => {
  let list = metadata.value.navigationTrees.filter((item) => item.children.length);
  return list.length * (swidth.value["swcatalogRoot"] + 10);
});

const innerW = computed(() => window.innerWidth);

watch(
  () => currentScenesList.value,
  () => {
    nextTick(() => {
      initSceneSwiper();
      initRootGroupSwiper();

      // if (metadata.value.navigationTrees[rootTabIndex.value]?.children[secondTabIndex.value]?.type == "group") {
      //   initSecondGroupSwiper();
      // }
    });
  }
);
watch(
  () => rootTabIndex.value,
  (val) => {
    console.error(val);
    nextTick(() => {
      if (metadata.value.navigationTrees[rootTabIndex.value]?.children[secondTabIndex.value]?.type == "group") {
        initSecondGroupSwiper();
      }
    });
  }
);

const fixTitle = (name) => {
  if (name == "默认二级分组") {
    name = t("navigation.default_group_two");
  } else if (name == "一级分组") {
    name = t("navigation.group_one");
  } else {
    name = name;
  }
  return name;
};
const swiperOptions = {
  slidesPerView: "auto",
  centeredSlides: true,
  slideToClickedSlide: true,
  spaceBetween: 10,
  centerInsufficientSlides: true,
  centeredSlidesBounds: true,
  freeMode: {
    enabled: true,
    sticky: false,
  },
};
const tabRoot = (item, index) => {
  store.commit("scene/setData", { currentRootId: item.id, currentSecondId: null });
  setTimeout(() => {
    changeSceneList();
  }, 0);

  // setTimeout(() => {
  //   rootGroupSwiper.value.slideTo(index);
  //   SecondGroupSwiper.value.slideTo(rootTabIndex.value);
  // }, 0);
};
const tabSecond = (item, index) => {
  store.commit("scene/setData", { currentSecondId: item.id });
  let sceneList = metadata.value.navigationTrees[rootTabIndex.value].children[secondTabIndex.value].children;
  store.commit("scene/setCurrentScenesList", sceneList);

  //

  // setTimeout(() => {
  //   SecondGroupSwiper.value.slideTo(index);
  // }, 0);

  // changeSceneList();
};
const changeSceneList = () => {
  let currentList = null;

  if (metadata.value.navigationTrees[rootTabIndex.value].children.length && metadata.value.navigationTrees[rootTabIndex.value].children[0].type == "group") {
    store.commit("scene/setData", { currentSecondId: metadata.value.navigationTrees[rootTabIndex.value].children[0].id });
    //如果有当前视图则选择二级目录
    metadata.value.navigationTrees[rootTabIndex.value].children.forEach((item, index) => {
      if (item.children.length) {
        item.children.forEach((t_item, t_index) => {
          if (t_item.id == currentScene.value.id || (t_item.sid && currentScene.value.sid && t_item.sid == currentScene.value.sid)) {
            store.commit("scene/setData", { currentSecondId: item.id });
          }
        });
      }
    });

    currentList = metadata.value.navigationTrees[rootTabIndex.value].children[secondTabIndex.value].children;
    store.commit("scene/setCurrentScenesList", currentList);
  }

  if (secondTabIndex.value == -1) {
    console.error("没有二级目录");
    let rootList = metadata.value.navigationTrees.find((item) => item.id == currentRootId.value);
    store.commit("scene/setCurrentScenesList", rootList.children);
  }
  nextTick(() => {
    initSceneSwiper();
    initRootGroupSwiper();
    if (metadata.value.navigationTrees[currentRootId.value]?.children[currentSecondId.value]?.type == "group") {
      initSecondGroupSwiper();
    }
  });
};
const initSceneSwiper = () => {
  if (SceneSwiper.value) {
    SceneSwiper.value.destroy();
    SceneSwiper.value = null;
  }
  if (!currentScenesList.value.length) {
    return;
  }

  nextTick(() => {
    SceneSwiper.value = new Swiper(".scene-list", swiperOptions);
    let index = currentScenesList.value.findIndex((item) => item.id == currentScene.value.id);
    if (index >= 0) {
      SceneSwiper.value.slideTo(index);
    }
  });
};
const tabCurrentScene = (data, index) => {
  store.commit("scene/setCurrentScene", data);

  // SceneSwiper.value.slideTo(index);
};
const initSecondGroupSwiper = () => {
  console.error("initSecondGroupSwiper");
  if (SecondGroupSwiper.value) {
    SecondGroupSwiper.value.destroy();
    SecondGroupSwiper.value = null;
  }

  nextTick(() => {
    SecondGroupSwiper.value = new Swiper(".second-group-list", swiperOptions);
    if (secondTabIndex.value >= 0) {
      SecondGroupSwiper.value.slideTo(secondTabIndex.value);
    }
  });
};

const tabCurrentSecondGroup = (data, index) => {
  // store.commit("scene/setCurrentScene", data);

  SecondGroupSwiper.value.slideTo(index);
};

const initRootGroupSwiper = () => {
  // if (rootGroupSwiper.value) {
  //   rootGroupSwiper.value.destroy();
  //   rootGroupSwiper.value = null;
  // }
  // nextTick(() => {
  //   rootGroupSwiper.value = new Swiper(".root-group-list", swiperOptions);
  // });

  if (!rootGroupSwiper.value) {
    rootGroupSwiper.value = new Swiper(".root-group-list", swiperOptions);
    if (rootGroupSwiper.value >= 0) {
      rootGroupSwiper.value.slideTo(rootTabIndex.value);
    }
    initSecondGroupSwiper();
  }
};

const tabCurrentRootGroup = (data, index) => {
  // store.commit("scene/setCurrentScene", data);

  SecondGroupSwiper.value.slideTo(index);
};

onMounted(() => {
  useApp().then(async (app) => {
    if(currentScene.value.type == '4dkk' && currentScene.value.version == 'V4') {
      store.commit("functions/setShowScenesList", false);
    }
    show.value = true;
    console.error("app", show.value);
  });
});
</script>

<style lang="scss" scoped>
.bar-list {
  position: absolute;
  bottom: 88px;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  overflow: hidden;
  max-height: 0;
  transition: 0.3s all ease;
  z-index: 9;
  width: 100%;

  .swiper-container {
    width: 100%;
    position: relative;
    margin: 0 auto;

    > ul {
      > li {
        white-space: nowrap;

        > span,
        > div > span {
          cursor: pointer;
          display: inline-block;
          color: rgba(255, 255, 255, 0.6);
        }

        &.loopspan {
          > span,
          > div > span {
            animation: 5s wordsLoop linear infinite normal;
          }
        }

        &.active {
          > span,
          > div > span {
            color: rgba(255, 255, 255, 1);
          }
        }
      }
    }
  }

  .top-con {
    margin-bottom: 10px;
    padding: 10px 0;
    width: 100%;
    background: rgba(0, 0, 0, 0.5);
  }

  #swcatalogRoot {
    padding: 0 15px;

    > ul {
      > li {
        width: 104px;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        padding: 4px 10px;
        border: 1px solid rgba(255, 255, 255, 0.5);
        box-sizing: border-box;
        overflow: hidden;

        > span {
          width: 100%;
          word-break: keep-all;
        }

        &.active {
          border: 1px solid rgba(255, 255, 255, 1);
        }
      }
    }
  }

  #swSecondary {
    margin: 20px auto 10px;
    padding: 0 15px;

    > ul {
      > li {
        width: 84px;
        box-sizing: border-box;
        overflow: hidden;
        padding-bottom: 6px;

        > span {
          width: 100%;
          word-break: keep-all;
        }

        &.active {
          position: relative;

          &::before {
            content: "";
            display: inline-block;
            position: absolute;
            bottom: 0;
            width: 20px;
            height: 2px;
            z-index: 9999;
            left: 50%;
            transform: translateX(-50%);
            background: var(--colors-primary-base);
          }
        }
      }
    }
  }

  #swScenes {
    // padding: 0 15px;
    > ul {
      > li {
        cursor: pointer;
        width: 72px;
        height: 72px;
        border-radius: 6px;
        border: 1px solid #ffffff;
        background-size: cover;
        position: relative;
        overflow: hidden;

        .iconfont {
          position: absolute;
          left: 4px;
          top: 4px;
          z-index: 99;

          &::after {
            background: rgba(0, 0, 0, 0.3);
            content: "";
            width: 14px;
            height: 14px;
            display: inline-block;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: -1;
            filter: blur(4px);
          }
        }

        > div {
          position: absolute;
          bottom: 0;
          left: 0;
          height: 20px;
          background: rgba(0, 0, 0, 0.5);
          width: 100%;
          overflow: hidden;
          > span,
          div {
            width: 100%;
            line-height: 20px;
            word-break: keep-all;
          }
        }

        &.active {
          border: 1px solid var(--colors-primary-base);
          > div {
            > span {
            }
          }
        }
      }
    }
  }
}

.barshow {
  max-height: 190px;
}

@keyframes wordsLoop {
  0% {
    transform: translateX(100%);
    -webkit-transform: translateX(100%);
  }
  100% {
    transform: translateX(-180%);
    -webkit-transform: translateX(-180%);
  }
}
.marquee {
  .marquee-text-wrap {
    height: 20px;
    line-height: 20px;
  }
}
</style>
<style>
.marquee-text-text {
  padding: 0 5px;
}
</style>