<template>
  <div
    class="bar-list"
    v-if="
      show &&
      !(
        metadata.catalogRoot &&
        metadata.catalogRoot.length == 1 &&
        scenes.length == 1 &&
        secondaryList.length == 1
      )
    "
    :class="{ barshow: isShowScenesList }"
  >
    <div class="top-con">
      <div
        class="swiper-container swiper1"
        :style="`width:calc(100% - 20px)`"
        id="swScenes"
        v-if="currentScenesList.length > 0"
      >
        <ul class="swiper-wrapper">
          <li
            @click="tabCurrentScene(item)"
            class="swiper-slide"
            :class="{
              active: currentScene.sceneCode == item.sceneCode,
              // loopspan:
              //   item.sceneTitle.length > spanlength &&
              //   currentScene.id == item.id,
            }"
            :style="{ backgroundImage: `url(${item.icon})` }"
            v-for="(item, i) in currentScenesList"
            :key="i"
          >
            <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.sceneTitle.length / 10) * 5"
                :key="item.id"
                v-if="
                  item.sceneTitle.length > spanlength &&
                  currentScene.id == item.id
                "
              >
                {{ item.sceneTitle }}
              </marquee-text>
              <span v-else>
                {{ item.sceneTitle }}
              </span>
            </div>
          </li>
        </ul>
      </div>

      <div
        class="swiper-container swiper2"
        id="swSecondary"
        :style="`width:${clamp(secondaryW, 0, 1150)}px`"
        v-if="secondaryList.length > 1"
      >
        <!-- {{ clamp(secondaryW, 0, 1150) }} -->
        <ul class="swiper-wrapper">
          <li
            class="swiper-slide"
            @click="tabSecondary(item, i)"
            :class="{
              active: currentSecondary.id == item.id,
              // loopspan:
              //   fixTitle(item.name).length > spanlength &&
              //   currentSecondary.id == item.id,
            }"
            v-for="(item, i) in secondaryList"
            :key="i"
          >
            <!-- {{ Math.ceil(fixTitle(item.name).length / 10) }} -->

            <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>
            <!-- <span v-if="currentSecondary.id == item.id">{{
              fixTitle(item.name)
            }}</span>
            <span v-else>{{
              fixTitle(item.name).length > spanlength
                ? fixTitle(item.name).slice(0, spanlength)
                : fixTitle(item.name)
            }}</span> -->
          </li>
        </ul>
      </div>
    </div>

    <div
      class="swiper-container"
      id="swcatalogRoot"
      :style="`width:${catalogRootW > innerW ? '100%' : catalogRootW + 'px'}`"
      v-if="metadata.catalogRoot.length > 0 && metadata.catalogs.length > 1"
    >
      <ul class="swiper-wrapper" v-if="metadata.catalogRoot.length > 1">
        <li
          class="swiper-slide"
          :class="{
            active: currentCatalogRoot.id == item.id,
            // loopspan:
            //   fixTitle(item.name).length > spanlength &&
            //   currentCatalogRoot.id == item.id,
          }"
          @click="tabRoot(item)"
          v-for="(item, i) in metadata.catalogRoot"
          :key="i"
        >
          <!-- <span v-if="currentCatalogRoot.id == item.id">{{
            fixTitle(item.name)
          }}</span>
          <span v-else>{{
            fixTitle(item.name).length > spanlength
              ? fixTitle(item.name).slice(0, spanlength)
              : fixTitle(item.name)
          }}</span> -->

          <marquee-text
            :duration="Math.ceil(fixTitle(item.name).length / 10) * 5"
            :key="item.id"
            :repeat="1"
            v-if="
              fixTitle(item.name).length > spanlength &&
              currentCatalogRoot.id == item.id
            "
          >
            {{ fixTitle(item.name) }}
          </marquee-text>
          <span v-else>
            {{ fixTitle(item.name) }}
          </span>
        </li>
      </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 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 scenesListW = computed(
  () => currentScenesList.value.length * (swidth.value["swScenes"] + 10) - 10
);
const secondaryW = computed(
  () => secondaryList.value.length * (swidth.value["swSecondary"] + 10) - 10
);
const catalogRootW = computed(
  () =>
    metadata.value.catalogRoot.length * (swidth.value["swcatalogRoot"] + 10) -
    10
);
const innerW = computed(() => 1150);

const tabCurrentScene = (data) => {
  console.log("tabCurrentScene", data.id, currentScene.value.id);
  if (data.id !== currentScene.value.id) {
    store.commit("scene/setCurrentScene", data);
    setTimeout(() => {
      scenesSwiperFocus();
    }, 300);
  } else {
    console.log("重复点击当前导航");
    // window.alert("alert-test-->重复点击当前导航");
  }
};

const tabSecondary = (data, index) => {
  store.commit("scene/setCurrentSecondary", data);
};

const tabRoot = (data) => {
  store.commit("scene/setCurrentCatalogRoot", data);
};

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,
  spaceBetween: 10,
  centerInsufficientSlides: true,
  centeredSlidesBounds: true,
  freeMode: {
    enabled: true,
    sticky: false,
    momentumBounce: false,
    // momentumVelocityRatio: 0.5,
  },
};

// const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const initMainSwiper = () => {
  nextTick(() => {
    if (window.mainNatSwiper) {
      // window.mainNatSwiper = null;
      window.mainNatSwiper.update();
      window.sencordNatSwiper.slideReset();
    }
    window.mainNatSwiper = new Swiper("#swcatalogRoot", swiperOptions);
  });
};
const initsencordNatSwiper = () => {
  nextTick(() => {
    console.warn("initsencordNatSwiper");
    if (window.sencordNatSwiper) {
      window.sencordNatSwiper.update();
      window.sencordNatSwiper.slideReset();
    }
    window.sencordNatSwiper = new Swiper("#swSecondary", swiperOptions);
  });
};
const initScenesSwiper = () => {
  console.warn("initScenesSwiper");
  nextTick(() => {
    if (window.scenesNatSwiper) {
      window.scenesNatSwiper.update();
      window.scenesNatSwiper.slideReset();
      // window.scenesNatSwiper = null;
    } else {
      window.scenesNatSwiper = new Swiper("#swScenes", {
        ...swiperOptions,
      });
    }
    scenesSwiperFocus();
  });
};

const scenesSwiperFocus = () => {
  const sceneIndex = Array.from(currentScenesList.value).findIndex(
    (item) => item.id === currentScene.value.id
  );
  if (window.scenesNatSwiper && window.scenesNatSwiper.slides.length > 0) {
    const index = sceneIndex < 0 ? 0 : sceneIndex;
    console.warn("scenesSwiperFocus", index);
    window.scenesNatSwiper.slideTo(index);
  }
};

const sencordNatSwiperFocus = () => {
  nextTick(() => {
    const current = Array.from(secondaryList.value).findIndex(
      (item) => item.id === currentSecondary.value.id
    );
    if (window.sencordNatSwiper) {
      const index = current < 0 ? 0 : current;
      console.warn("sencordNatSwiperFocus", index);
      // window.sencordNatSwiper.slideTo(current);
      window.sencordNatSwiper.slideTo(current);
    }
  });
};

onMounted(() => {
  useApp().then(async (app) => {
    show.value = true;
  });
  watchEffect(() => {
    if (
      metadata.value.catalogRoot &&
      unref(metadata.value.catalogRoot).length > 0
    ) {
      initMainSwiper();
    }
  });

  watch([currentSecondary, secondaryList], () => {
    if (unref(secondaryList).length > 1) {
      initsencordNatSwiper();
      sencordNatSwiperFocus();
    } else {
      if (window.sencordNatSwiper) {
        console.warn("destroy-sencordNatSwiper");
        window.sencordNatSwiper.update();
        window.sencordNatSwiper.slideReset();
      }
    }
  });

  watch(currentScenesList, () => {
    initScenesSwiper();
  });
  watch(currentCatalogRoot, (val) => {
    if (Array.from(unref(val).children).includes(currentScene.value.category)) {
      //当前场景在一类的children
      const activeSecond = Array.from(unref(secondaryList)).find(
        (i) => i.id === currentScene.value.category
      );
      console.log("activeSecond", activeSecond);
      store.commit("scene/setCurrentSecondary", activeSecond);
      if (window.sencordNatSwiper) {
        window.sencordNatSwiper.update();
      }
    }
  });
});
</script>

<style lang="scss" scoped>
$width: 1150px;

.bar-list {
  position: absolute;
  bottom: 68px;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  max-width: $width;
  overflow: hidden;
  max-height: 0;
  transition: 0.3s all ease;
  z-index: 9;

  .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: 10s wordsLoop linear infinite normal;
          }
        }

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

  .top-con {
    margin: 0 auto 10px;
    padding: 10px 0;
    background: linear-gradient(
      268deg,
      rgba(0, 0, 0, 0) 0%,
      rgba(0, 0, 0, 0.4) 25%,
      rgba(0, 0, 0, 0.4) 75%,
      rgba(0, 0, 0, 0) 100%
    );
  }

  #swcatalogRoot {
    > 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;

    > 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 {
    > 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;
            white-space: normal;
          }
        }

        &.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>
