<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">
        <div class="swiper-container" id="layout--swiper-container">
          <div class="swiper-wrapper">
            <div class="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>
            </div>
          </div>
          <div class="swiper-scrollbar" id="layout--swiper-scrollbar"></div>
        </div>
      </div>
    </a-layout-sider>
  </section>
</template>
<script>
import Logo from '../logo';
import Menu from './menu';

import Swiper from 'swiper';

let timer,
  swiper,
  siderSwiperOptions = {
    direction: 'vertical',
    slidesPerView: 'auto',
    freeMode: true,
    scrollbar: {
      el: '#layout--swiper-scrollbar',
    },
    mousewheel: true,
  };

export default {
  components: {
    Logo,
    Menu,
  },
  props: {
    nav: {
      default() {
        return {
          apps: [],
          menus: [],
          loading: false,
        };
      },
      type: Object,
    },
  },
  data() {
    return {
      siderCollapsed: undefined,
    };
  },
  mounted() {
    // swiper不能使用vue版本的组件.效果相当差
    swiper = new Swiper('#layout--swiper-container', siderSwiperOptions);
    this.$nextTick(() => {
      this.onUpdateSwiper();
    });

    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;
          }
        }

        this.onUpdateSwiper();
      }
    });
  },
  methods: {
    onUpdateSwiper() {
      clearTimeout(timer);
      timer = setTimeout(() => {
        // 需要更新两次
        swiper.update();
        swiper.update();
      }, 300);
    },

    onMenuOpenChange() {
      this.onUpdateSwiper();
    },

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

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