<template>
  <div class="index">
    <christmas v-if="isOpen" @listenopen="listenOpen" :hasNewYear="hasNewYear"></christmas>
    <carousel>
      <kind-category @loadchild="loadProductKinds"></kind-category>
    </carousel>
    <advert></advert>
    <floor-list></floor-list>
    <news></news>
    <partner></partner>
  </div>
</template>
<script>
  import { KindCategory, Carousel, Advert, FloorList, Partner, News } from '~components/home'
  import { Christmas } from '~components/default'

  export default {
    name: 'index',
    layout: 'main',
    data () {
      return {
        isOpen: false,
        hasNewYear: false
      }
    },
    fetch ({ store }) {
      return Promise.all([
        store.dispatch('loadFloors'),
        store.dispatch('loadBanners', {type: 'home'}),
        store.dispatch('loadProductKinds', { id: 0 }),
        store.dispatch('loadNewsSnapshot', { page: 1, pageSize: 10 })
      ])
    },
    components: {
      KindCategory,
      Carousel,
      Advert,
      FloorList,
      Partner,
      News,
      Christmas
    },
    mounted () {
      let user = this.user.logged
      let count = 1
      let self = this
      const nowDate = new Date()
      const activeStartDate = new Date('2017/12/20 00:00:00')
      const activeEndDate = new Date('2018/1/2 00:00:00')
      const EndDate = new Date('2017/12/26 00:00:00')
      this.hasNewYear = nowDate > EndDate
      if (nowDate > activeStartDate && nowDate < activeEndDate) {
        const endTime = window.localStorage.getItem('endTime')
        if (!user) {
          setInterval(function () {
            count++
            if (count >= 30) {
              count = 1
              self.isOpen = true
            }
          }, 1000)
        }
        if (endTime) {
          if (nowDate.getTime() - endTime >= 1000 * 60) {
            this.isOpen = true
            window.localStorage.setItem('endTime', nowDate.getTime())
          } else {
            this.isOpen = false
          }
        } else {
          this.isOpen = true
          window.localStorage.setItem('endTime', nowDate.getTime())
        }
      } else {
        this.isOpen = false
      }
    },
    computed: {
      user () {
        return this.$store.state.option.user
      }
    },
    methods: {
      listenOpen () {
        this.isOpen = false
      },
      loadProductKinds (id) {
        this.$store.dispatch('loadAllProductKinds', {id})
      }
    }
  }
</script>
