<template>
  <section>
    <a-layout-sider
      :collapsed="siderCollapsed === undefined ? $root.global.settings.siderCollapsed : siderCollapsed"
      @collapse="onCollapse"
      v-if="$root.global.settings.layout === 'left-menu' || $root.global.settings.layout === 'right-menu'"
      width="200"
    >
      <Logo />
      <div class="yo-sider-nav">
        <App :apps="nav.apps" @change-app="(app) => $emit('change-app', app)" />
        <swiper :options="siderSwiperOptions" ref="sider-swiper">
          <swiper-slide>
            <a-spin :spinning="nav.loading">
              <a-icon slot="indicator" spin type="loading" />
              <Menu
                :menu-style="{ height: '100%', borderRight: 0 }"
                :nav="nav"
                @openChange="onMenuOpenChange"
                mode="inline"
              />
            </a-spin>
          </swiper-slide>
          <div class="swiper-scrollbar" id="layout--swiper-scrollbar" slot="scrollbar"></div>
        </swiper>
      </div>
    </a-layout-sider>
    <template v-else-if="$root.global.settings.layout === 'top-nav'">
      <Menu
        :menu-style="{ borderBottom: 0 }"
        :nav="nav"
        @openChange="onMenuOpenChange"
        mode="horizontal"
      />
    </template>
  </section>
</template>
<script>
import Logo from '../logo';
import App from './app';
import Menu from './menu';

let timer;

export default {
  components: {
    Logo,
    App,
    Menu,
  },
  props: {
    nav: {
      default() {
        return {
          apps: [],
          menus: [],
          loading: false,
        };
      },
      type: Object,
    },
  },
  data() {
    return {
      siderSwiperOptions: {
        direction: 'vertical',
        slidesPerView: 'auto',
        freeMode: true,
        scrollbar: {
          el: '#layout--swiper-scrollbar',
        },
        mousewheel: true,
      },

      siderCollapsed: undefined,
    };
  },
  mounted() {
    window.addEventListener('resize', () => {
      if (this.$root.global.settings.layout === 'left-menu' || this.$root.global.settings.layout === 'right-menu') {
        if (!this.$root.global.settings.siderCollapsed) {
          if (window.innerWidth < 1000) {
            this.siderCollapsed = true;
          } else {
            this.siderCollapsed = undefined;
          }
        }

        clearTimeout(timer);
        timer = setTimeout(() => {
          if (this.$refs['sider-swiper']) {
            this.$refs['sider-swiper'].$swiper.update();
          }
        }, 300);
      }
    });
  },
  methods: {
    onMenuOpenChange() {
      this.windowTriggerResize();
    },

    onCollapse() {
      this.windowTriggerResize();
    },

    windowTriggerResize() {
      let e = new Event('resize');
      window.dispatchEvent(e);
    },
  },
};
</script>