<template>
  <div class="ipub-breadcrumb ipub-p2">
    <span v-for="(item, index) in pathList"
          :key="'pathList' + index">
      <template v-if="index !== pathList.length - 1">
        <router-link v-if="item.path !== pathList[pathList.length - 1].href&&!item.unClick"
                     :to="item.redirect || item.href"
                     class="path"
                     :key="index">
          <template v-if="language === 'zh-CN'">{{ item.name }}</template>
          <template v-else-if="language === 'en-US'">{{ item.enName }}</template>
        </router-link>
        <template v-else>
          <template v-if="language === 'zh-CN'">
            <font>{{ item.name }}</font>
          </template>
          <template v-else-if="language === 'en-US'">
            <font>{{ item.enName }}</font>
          </template>
        </template> {{separator}}
      </template>
      <font class="link-color"
            v-else>
        <template v-if="language === 'zh-CN'">
          {{ item.name }}
        </template>
        <template v-else-if="language === 'en-US'">
          {{ item.enName }}
        </template>
      </font>
    </span>
  </div>
</template>

<script>
export default {
  name: 'IpubBreadcrumb',
  props: {
    menus: {
      type: Array,
      default () {
        return []
      }
    },
    separator: {
      type: String,
      default: '>>'
    },
    language: {
      type: String,
      default: 'en-US'
    }
  },
  data () {
    return {
      pathList: [],
    }
  },
  created () {
    this.path = this.$route.path
  },
  mounted () {
    this.pathList = []
    this.findPath(this.menus)
    if (this.pathList[0].href !== '/home') {
      this.pathList.unshift(this.menus[0])
    }
  },
  watch: {
    //监听相同路由下参数变化的时候，从而实现异步刷新
    $route () {
      this.path = this.$route.path
      this.pathList = []
      this.findPath(this.menus)
      if (this.pathList[0].href !== '/home') {
        this.pathList.unshift(this.menus[0])
      }
    },
  },
  methods: {
    findPath (paths) {
      let detail = ''
      const flag = paths.some((item) => {
        if (this.path.includes(item.href) && item.href !== '/') {
          this.pathList.push(item)
          if (item.children && item.href !== this.path) {
            this.findPath(item.children)
          }
          return true
        } else if (item.isDetail) {
          detail = item
        }
      })
      if (!flag && detail) {
        this.pathList.push(detail)
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.ipub-breadcrumb {
  padding: 10px 0;
}
</style>
