<template>
  <div id="screen-container">
    <div v-if="isLoading" class="loading">
      <dv-loading>Loading...</dv-loading>
    </div>
    <!-- Header -->
    <Header :header-title="headerTitle" :current-index="currentIndex" :page-data="pageData" />
    <!-- <div class="header-page">{{ (currentIndex+1) +' / '+ pageData.length }}</div> -->
    <!-- 内容部分 -->
    <!-- <keep-alive>
      <PageOne v-if="currentIndex === 0" ref="pageOneRefs" />
    </keep-alive>
    <PageTwo v-if="currentIndex === 1" />
    <PageThree v-if="currentIndex=== 2" />
    <PageFour v-if="currentIndex === 3" /> -->

    <keep-alive>
      <component :is="currentPage && currentPage.title" />
    </keep-alive>

    <!-- bottom -->
    <div class="bottom-bg">
      <div class="bottom-content">
        <div class="dot-container left-dots">
          <div class="dot" />
          <div class="dot" />
          <div class="dot" />
        </div>
        <div class="dot-container right-dots">
          <div class="dot" />
          <div class="dot" />
          <div class="dot" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { FetchInitToken, FetchInitSetting } from '@/api/library'
import Header from '@/views/header/index.vue'
import PageOne from '@/views/pageOne/index.vue'
import PageTwo from '@/views/map/index.vue'
import PageThree from '@/views/pageThree/index.vue'
import PageFour from '@/views/pageFour/index.vue'
export default {
  name: 'Home',
  components: {
    Header,
    PageOne,
    PageTwo,
    PageThree,
    PageFour
  },
  inject: ['reload'],
  data() {
    return {
      currentIndex: 0, // 当前显示的页面索引
      currentPage: null, // 当前显示的页面数据
      isLoading: false,
      height: '',
      headerTitle: '祁阳陶铸图书馆智慧大屏馆情数据总览',
      pageData: [
        { id: 1, title: 'PageOne', delayed: 20, isShow: false },
        { id: 2, title: 'PageTwo', delayed: 20, isShow: false },
        { id: 3, title: 'PageThree', delayed: 20, isShow: false },
        { id: 4, title: 'PageFour', delayed: 20, isShow: false }
      ],
      swiperOption: null,
      loadingTtimer: null,
      timer2: null,
      leftTimer: null,
      middleTimer: null,
      deviceTimer: null,
      todayTimer: null,
      yearTimer: null,
      intervalId: null,
      orderIds: [],
      wecharQrCodeSrc: null
    }
  },
  computed: {
    shouldCacheComponent() {
      if (this.currentPage) {
        switch (this.currentPage.title) {
          case 'PageOne':
            return 'PageOne'
          case 'PageFour':
            return 'PageFour'
          default:
            return null
        }
      }
      return null
    },
    currentPageComponent() {
      if (this.currentPage) {
        switch (this.currentPage.title) {
          case 'PageTwo':
            return 'PageTwo'
          case 'PageThree':
            return 'PageThree'
          default:
            return null
        }
      }
      return null
    }
  },
  created() {
    // const METAWA = require('../assets/js/META.common.min.js')
    // const meta = new METAWA('665e845538d68')
    // meta.callback = (r) => {
    //   console.log(r, '回调')
    // }
    this.getInitSetting()
  },
  beforeDestroy() {
    this.stopAutoSwitch()
    clearInterval(this.timer2)
    clearInterval(this.leftTimer)
    clearInterval(this.middleTimer)
    clearInterval(this.deviceTimer)
    clearInterval(this.todayTimer)
    clearInterval(this.yearTimer)
    this.middleTimer = null
    this.leftTimer = null
    this.deviceTimer = null
    this.todayTimer = null
    this.yearTimer = null
  },
  mounted() {
    // this.getToken()
    this.showLoading()
  },
  methods: {
    getToken() {
      const params = {
        'appid': 'whfeitian',
        'secret': '1f4unqcgg9j0pvx54cwvillch5xto9e5'
      }
      FetchInitToken(params).then(res => {
        console.log(res)
      })
    },
    startPageSwitch() {
      const delay = parseInt(this.pageData[this.currentIndex].delayed) * 1000
      this.intervalId = setInterval(() => {
        this.currentIndex++
        if (this.currentIndex >= this.pageData.length) {
          this.currentIndex = 0
        }
        const index = this.currentIndex % this.pageData.length
        this.currentPage = this.pageData[index]
      }, delay)
    },
    getInitSetting() {
      // selectorder  显示的屏和顺序   1第一屏 2第二屏
      // show1 第一屏显示时间
      // show2 第二屏显示时间
      const linkSrc = process.env.VUE_APP_BASE_API
      FetchInitSetting().then(res => {
        const result = JSON.parse(res.data)
        this.wecharQrCodeSrc = linkSrc + '/downloadFile' + result.wecharQrCode
        localStorage.setItem('wecharQrCodeSrc', this.wecharQrCodeSrc)

        const selectorder = result.selectorder
        const showDurations = { 1: result.show1, 2: result.show2, 3: result.show3, 4: result.show4 }
        this.orderIds = selectorder.split(',').map(id => parseInt(id.trim()))

        const updatedPageData = this.orderIds.map((id, index) => {
          const pageIndex = this.pageData.findIndex(item => item.id === id)
          if (pageIndex !== -1) {
            const updatedPage = {
              ...this.pageData[pageIndex],
              isShow: true,
              delayed: showDurations[id]
            }
            return updatedPage
          } else {
            console.log(`ID 为 ${id} 的页面未找到。`)
            return null
          }
        }).filter(item => item !== null)

        this.pageData = updatedPageData
        if (this.pageData) {
          this.currentPage = this.pageData[this.currentIndex]
          this.startPageSwitch()
        }
      }).catch(error => {
        console.error('Error', error)
        setTimeout(() => {
          this.reload()
        }, 5000)
      })
    },
    stopAutoSwitch() {
      clearInterval(this.intervalId)
      this.intervalId = null
    },
    goToNextPage() {
      this.currentPage = (this.currentPage + 1) % 4
      this.stopAutoSwitch() // 停止自动切换，以免与手动切换冲突

      // 设置定时器，恢复自动切换
      // setTimeout(() => {
      //   this.startAutoSwitch()
      // }, 200000)
    },
    showLoading() {
      this.isLoading = true
      this.loadingTtimer = setTimeout(() => {
        this.isLoading = false
        window.clearTimeout(this.loadingTtimer)
      }, 1500)
    },
    // 数字3位数加分隔符
    formatter(str) {
      const reg = /(?=(?!\b)(\d{3})+$)/g
      return str.toString().replace(reg, ',')
    },
    // 设置文字滚动
    setNumberTransform(item) {
      const numberItems = document.querySelectorAll(`.${item.id}  i`)
      // const numberItems = this.$refs[`${item.id}`]
      const numberArr = item.valueArr.filter(item => !isNaN(item))
      numberItems.forEach((t) => {
        t.style.transition = 'transform 0s ease-in-out'
        t.style.transform = `translateY(-0%)`
      })
      setTimeout(() => {
        numberItems.forEach((ls, index) => {
          ls.style.transition = 'transform 1s ease-in-out'
          ls.style.transform = `translateY(-${numberArr[index] * 10}%)`
        })
      }, 15)
    },
    // 定时
    initInterval(targetList, time) {
      const { setNumberTransform } = this
      return setInterval((function fn() {
        targetList.forEach(t => {
          setTimeout(() => {
            setNumberTransform(t)
          }, 50)
        })
        return fn
      })(), time)
    },
    // 定时刷新数字翻牌器
    timedRefresh(targetList, type) {
      if (type === 'middle') {
        this.middleTimer = this.initInterval2(targetList, 8000)
      } else if (type === 'left') {
        this.leftTimer = this.initInterval(targetList, 10000)
      } else if (type === 'device') {
        this.deviceTimer = this.initInterval(targetList, 8000)
      } else if (type === 'todayTotal') {
        this.todayTimer = this.initInterval(targetList, 8000)
      } else if (type === 'yearTotal') {
        this.yearTimer = this.initInterval(targetList, 10000)
      }
      this.$once('hook:beforeDestroy', () => {
        clearInterval(this.leftTimer)
        clearInterval(this.middleTimer)
        clearInterval(this.deviceTimer)
        clearInterval(this.todayTimer)
        clearInterval(this.yearTimer)
        this.middleTimer = null
        this.leftTimer = null
        this.deviceTimer = null
        this.todayTimer = null
        this.yearTimer = null
      })
    },
    setNumberTransform2(item) {
      var numberItems = document.querySelectorAll(`.${item.id}  i`)
      const numberArr = item.valueArr.filter(item => !isNaN(item))
      for (var index = 0; index < numberItems.length; index++) {
        const elem = numberItems[index]
        elem.style.transition = 'transform 0s ease-in-out'
        elem.style.transform = `translate(-50%,-0%)`
      }
      setTimeout(() => {
        for (var index = 0; index < numberItems.length; index++) {
          const elem = numberItems[index]
          elem.style.transition = 'transform 1s ease-in-out'
          elem.style.transform = 'translate(-50%, -' + numberArr[index] * 10 + '%)'
        }
      }, 15)
    },
    // 定时
    initInterval2(targetList, time) {
      const { setNumberTransform2 } = this
      return setInterval((function fn() {
        targetList.forEach(t => {
          setTimeout(() => {
            setNumberTransform2(t)
          }, 50)
        })
        return fn
      })(), time)
    }
  }
}
</script>

<style lang="scss">
@import "~@/assets/styles/index.scss";
.swiper-home{
  .swiper-wrapper{
    transition-timing-function: ease-in-out !important;
  }
  .swiper-slide{
    position: relative;
    width: 100%;
    overflow: hidden;
  }
  .swiper-pagination-home{
    position: fixed;
    top: .2rem;
    left: calc( 100% - 2rem);
    font-size: .4rem;
  }
}

</style>
