<template>
  <div style="display: inline" @click="handleBookMarkChange" name="bmk-star">
    <!-- <span v-if="!bookmark.hasOwnProperty(menuId_)">
      <i class="el-icon-star-off" ></i>
    </span>
    <span v-if="bookmark.hasOwnProperty(menuId_)">
      <i class="el-icon-star-on" ></i>
    </span> -->
    <i class="icon-collect collect-icon" :class="{'is-collect':bookmark.hasOwnProperty(menuId_)}"></i>
  </div>
</template>

<script>
import {mapState} from 'vuex'

export default {
  props: {
    menuId: {
      type: String,
    },
    tabAlias: {
      type: String,
    },
  },

  data() {
    return {
      isBookmark: false,
      menuId_: "",
      loading: false
    }
  },
  computed: {
    ...mapState({
      menus: (state) => state.menu.menus,
      bookmark: (state) =>  Object.keys(state.menu.bookmark).length>0 ? state.menu.bookmark : JSON.parse(sessionStorage.getItem("currentMenuBookmark")),
    }),
  },
  created() {},
  methods: {
    handleBookMarkChange(e) {
      if(this.loading){
        return ;
      }
      let event = e || window.event
      event.stopPropagation()
      let menuId = this.getMenuId()
      this.$http
        .post(`${window.context.portal}/portal/menuBookmark/v1/bookmark`, {
          menuId: menuId,
        })
        .then((resp) => {
          if (resp.data && resp.data.state) {
            this.$message.success(resp.data.message)
            this.isBookmark = !this.isBookmark;
            this.$store.dispatch("menu/actionMenuBookmark").then(()=>{
                this.$root.$emit("menuBookmarkChange");
            })
          }
        })
    },
    getMenuId() {
      let storageMenus = sessionStorage.getItem("currentMenus") && JSON.parse(sessionStorage.getItem("currentMenus")) || this.menus
      if (this.menuId) {
        return this.menuId
      }
      let tabAlias = this.tabAlias
      let innerFun = function (menu) {
        if (menu && menu.length > 0) {
          for (let i = 0; i < menu.length; i++) {
            if (menu[i].alias === tabAlias) {
              return menu[i].id
            } else {
              let menuId = innerFun(menu[i].children)
              if (menuId) {
                return menuId
              }
            }
          }
        }
      }
      return innerFun(storageMenus)
    },
  },
  async mounted() {
    let menuId = this.getMenuId()
    this.menuId_ = menuId;
    if (this.bookmark.hasOwnProperty(menuId)) {
      this.isBookmark = true
    }
  },
}
</script>

<style lang="scss" scoped>
.collect-icon{
  color: #E2E2E2;
  font-size: 18px;
}
.is-collect{
  color: #FFCA28;
}
</style>