<template>
  <div ref="layout" :class="classObj" class="app-wrapper">
    <div v-if="layout.device==='mobile'&&layout.opened" class="drawer-bg" @click="handleClickOutside" />
    <dk-sidebar class="sidebar-container">
      <template v-slot:footer>
        <slot name="sidebar-footer" />
      </template>
      <template v-slot:menu>
        <slot name="sidebar-menu" />
      </template>
    </dk-sidebar>
    <div class="main-container">
      <dk-navbar />
      <dk-app-main />
    </div>
  </div>
</template>

<script>

import Cookies from 'js-cookie'

export default {
  name: 'DkLayout',
  components: {},
  provide() {
    return {
      layout: this.layout
    }
  },
  data() {
    return {
      layout: {
        opened: false,
        withoutAnimation: false,
        device: 'pc'
      }
    }
  },
  computed: {
    classObj() {
      return {
        hideSidebar: !this.layout.opened,
        openSidebar: this.layout.opened,
        withoutAnimation: this.layout.withoutAnimation,
        mobile: this.layout.device === 'mobile'
      }
    }
  },
  watch: {
    'layout.opened': function(val) {
      if (val) {
        Cookies.set('sidebarStatus', 1)
      } else {
        Cookies.set('sidebarStatus', 0)
      }
    }
  },
  created() {
  },
  mounted() {
    this.layout.opened = Cookies.get('sidebarStatus') !== '0'
    this.$_resizeHandler()
    window.addEventListener('resize', this.$_resizeHandler)
  },
  methods: {
    $_resizeHandler() {
      // 获取当前窗口的宽度
      const width = window.innerWidth
      // 如果当前窗口的宽度小于768px则切换为移动端
      if (width <= 768) {
        this.layout.opened = false
        this.layout.device = 'mobile'
      } else {
        this.layout.device = 'desktop'
      }
    },
    handleClickOutside() {
      this.layout.withoutAnimation = false
      this.layout.opened = false
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../styles/variables.scss";
@import './style/index.scss';

.sidebar-container {
  box-shadow: 0 1px 10px rgb(0 0 0 / 10%)
}

.app-wrapper {
  &:after {
    content: "";
    display: table;
    clear: both;
  }

  position: relative;
  height: 100%;
  width: 100%;

  &.mobile.openSidebar {
    position: fixed;
    top: 0;
  }
}

.drawer-bg {
  background: #000;
  opacity: 0.3;
  width: 100%;
  top: 0;
  height: 100%;
  position: absolute;
  z-index: 999;
}

.fixed-header {
  position: fixed;
  top: 0;
  right: 0;
  z-index: 9;
  width: calc(100% - #{$sideBarWidth});
  transition: width 0.28s;
}

.hideSidebar .fixed-header {
  width: calc(100% - 64px)
}

.mobile .fixed-header {
  width: 100%;
}
</style>
