<template>
  <div class="d-flex">
    <div v-for="menu in menus" :key="menu.name" class="ml-3">
      <a-button type="dashed" ghost :class="menu.meta.title === title ? 'active' : ''" @click="selectMenu(menu)">
        {{ menu.meta.title }}
      </a-button>
    </div>
  </div>
</template>

<script>
import { autoIndexRouter } from '@/utils/util'
import { mapState } from 'vuex'

export default {
  name: 'ButtonMenu',
  props: {
    title: {
      type: String,
      required: true
    },
    menus: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      cloneDeepMenus: []
    }
  },
  computed: {
    ...mapState({
      mixMenuModeTitle: state => state.user.mixMenuModeTitle,
      mixMenuModePath: state => state.user.mixMenuModePath,
      mixMenuModeOrigin: state => state.user.mixMenuModeOrigin
    })
  },
  watch: {
    title: {
      handler(val) {
        for (let route of this.menus) {
          if (route.meta.title === val) {
            this.filterMenu(route)
          }
        }
      },
      immediate: true
    },
    mixMenuModeTitle(title) {
      if (this.title !== title) {
        this.$emit('update:title', title)
        for (let route of this.menus) {
          if (route.meta.title === title) {
            this.filterMenu(route)
          }
        }
      }
    }
  },
  methods: {
    selectMenu(menu) {
      const routes = {
        title: menu.meta.title,
        path: '',
        origin: 'menu'
      }
      this.$store.commit('SET_MIX_MENU_MODE_TITLE', routes)
      this.$emit('update:title', menu.meta.title)
    },
    filterMenu(menu) {
      let routes = []
      if (menu.children && menu.children.length > 0) {
        routes = menu.children
      } else {
        routes = [menu]
      }
      this.$store.commit('SET_PERMISSION_LIST', routes)
      if (this.mixMenuModeOrigin === 'tab') {
        this.$router.push(this.mixMenuModePath)
      } else {
        const path = autoIndexRouter(routes)
        this.$router.push(path)
      }
    }
  }
}
</script>

<style scoped>
.ant-btn-dashed:hover,
.ant-btn-dashed:focus {
  color: #faad14;
  border-color: #faad14;
}

.active {
  color: #faad14 !important;
  border-color: #faad14 !important;
}
</style>
