<template>
  <div class="main">
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive" />
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
  </div>
</template>
<script>
import Vue from 'vue'
import { EventBus } from '@/eventBus'
export default {
  name: 'RouteView',
  components: {
  },
  data () {
    return {
      componentsArr: []
    }
  },
  created () {
    // 设置iframe页的数组对象
    const componentsArr = this.getComponentsArr()
    if (componentsArr && componentsArr.length > 0) {
      componentsArr.forEach((item) => {
        Vue.component(item.name, item.component)
      })
    }

    this.componentsArr = componentsArr || []
    // 判断当前路由是否iframe页
    this.isOpenIframePage()
    EventBus.$on('deleteIframe', (data) => {
      this.deleteIframe(data)
    })
  },
  computed: {
    hasOpenComponentsArr () {
      return this.componentsArr.filter(item => item.hasOpen)
    }
  },
  methods: {
    // 根据当前路由设置hasOpen
    isOpenIframePage () {
      const target = this.componentsArr.find(item => {
        return item.path === this.$route.path
      })
      if (target && !target.hasOpen) {
        target.hasOpen = true
      }
    },
    // 遍历路由的所有页面，把含有iframeComponent标识的收集起来
    getComponentsArr () {
      if (this.$store.getters.addRouters && this.$store.getters.addRouters[0] && this.$store.getters.addRouters[0].children) {
        const contentPages = this.$store.getters.addRouters[0].children
        const iframeArr = contentPages.filter(item => item.isiFrame)
        return iframeArr.map((item) => {
          const name = item.name || item.path.replace('/', '')
          return {
            name: name,
            path: item.path,
            hasOpen: false, // 是否打开过，默认false
            isiFrame: item.isiFrame // 组件文件的引用
          }
        })
      }
    },
    deleteIframe (path) {
      if (path) {
        console.log('deleteIframe：原长度', this.componentsArr)
        const index = this.componentsArr.findIndex(item => item.path === path)
        console.log('deleteIframe', index)
        this.componentsArr.splice(this.componentsArr.findIndex(item => item.path === path), 1)
        console.log('deleteIframe：现长度', this.componentsArr)
      }
    }

  },

  watch: {
    $route () {
      if (this.$route.path.indexOf('report/view') >= 0) {
        const target = this.componentsArr.find(item => item.path === this.$route.path)
        if (target) {
          target.hasOpen = true
        } else {
          const frame = {
            name: this.$route.name,
            path: this.$route.path,
            hasOpen: true, // 是否打开过，默认false
            isiFrame: true // 组件文件的引用
          }
          this.componentsArr.push(frame)
          Vue.component(this.$route.name, this.$route.path)
        }
      }
    }
  }
}
</script>
