<template>
  <div class="aos-dynamic-alive-query" :id="id">
    <div v-for="item in queryList[id]" :key="item.queryString" :class="{ height100: $_.isEqual(item.query, currentQuery)}">
      <span v-if="queryObject[item.queryString]">
        <slot v-bind:activeQuery="item.query"></slot>
      </span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AosDynamicAliveQuery',
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      queryList: {},
      currentQuery: '',
      queryObject: {}
    }
  },
  computed: {
    routeQuery () {
      return this.$route.query
    }
  },
  watch: {
    routeQuery: {
      handler: function (val, oldVal) {
        if (val && this.id === this.$route.name) {
          this.currentQuery = val
          this.setQueryList(val)
        }
      },
      immediate: true,
      deep: true
    }
  },
  created () {
    this.$eventBus.on('removeKeepAliveTab', this.removeKeepAliveTabs)
    this.$eventBus.on('refreshDynamicAliveQuery', this.refreshDynamicAliveQuery)
  },
  methods: {
    removeKeepAliveTabs (tabData) {
      const tabName = tabData.name
      if (tabName && this.queryList[tabName]) {
        const tabParamsList  = this.queryList[tabName]
        const valString = this.objectToString(tabData.query)
        for (let index = 0; index < tabParamsList.length; index++) {
          const element = tabParamsList[index];
          if (valString === element.queryString) {
            tabParamsList.splice(index, 1)
            break
          }
        }
      }
    },
    refreshDynamicAliveQuery (route) {
      if (!route) {
        console.log('need $route')
        return
      }
      if (this.id === route.name) {
        const valString = this.objectToString(route.query)
        if (valString) {
          this.queryObject[valString] = false
          this.$nextTick(() => {
            this.queryObject[valString] = true
          })
        }
      }
    },
    objectToString (source) {
      if (!source) return source
      const keys = Object.keys(source)
      let stringObj = '{'
      if (keys.length > 0) {
        keys.forEach(key => {
          stringObj += (key + ':' + source[key])
        })
      }
      stringObj += '}'
      return stringObj
    },
    setQueryList (val) {
      let flag = true
      if (!this.queryList[this.id]) {
        this.queryList[this.id] = []
      }
      const valString = this.objectToString(val)
      const currentQueryList = this.queryList[this.id]
      for (let index = 0; index < currentQueryList.length; index++) {
        const element = currentQueryList[index];
        if (valString === element.queryString) {
          flag = false
          break
        }
      }
      if (flag && this.id === this.$route.name) {
        this.$set(this.queryObject, valString, true)
        currentQueryList.push({
          queryString: valString,
          query: val
        })
      }
    }
  }
}
</script>
