<template>
  <div class="sidebar-content d-print-none" :class="{ 'sidebar-collapsed': menuCollapsed }" ref="sidebar">
    <div class="branding">
      <b-img :src="logo" center class="icon-size-4 object-fit-contain" fluid />
    </div>
    <div class="profile border-bottom">
      <div>
        <span class="profile-pic">
          <span class="w-100 h-100">
            <b-img :src="getProfilePicture" class="object-fit-cover h-100 border" fluid-grow rounded="circle" />
          </span>
          <span v-if="getMemberFounderBonus" class="founder-badge">
            <b-img :src="founderBadge" class="icon-size-5" />
          </span>
        </span>
      </div>
      <div class="info">
        <div class="info-inner">
          <h6 class="mt-4 mb-0 member-info">
            {{ getLoggedInUser.name }}
          </h6>
          <span class="small member-info">
            {{ getLoggedInUser.old_ibs_user_id || getLoggedInUser.old_member_id }}
          </span>
        </div>
      </div>
    </div>
    <div class="menu" :key="getPermissionRefreshTime">
      <template v-for="(route, index) in sortedMenu">
        <template v-if="isMemberAuthorityInitialized">
          <template v-if="route.children.length === 0">
            <b-link
              v-if="displayConstraints(route)"
              :to="{ name: route.name, params: setOnDemandProps(route) }"
              @click.native="menuClicked"
              :key="`right-${index}`"
              v-can:[linkAccess(route).operation]="linkAccess(route).module"
              :data-qa="`${$helpers.kebabCase(route.name)}-side-menu`"
              :class="{
                active: new RegExp('^' + route.path).test($route.path),
              }"
            >
              <icon v-if="route.dashboardMenu.icon" :name="route.dashboardMenu.icon" />
              <span> {{ translateName(route) }}</span>
            </b-link>
          </template>
          <template v-else>
            <b-link
              v-b-toggle="`sidesub_${index}`"
              :class="{
                'has-child': true,
                active: new RegExp('^' + route.path).test($route.path),
              }"
              :key="`right-${index}`"
              v-can:[linkAccess(route).operation]="linkAccess(route).module"
              :data-qa="`${$helpers.kebabCase(route.name)}-side-menu`"
            >
              <icon v-if="route.dashboardMenu.icon" :name="route.dashboardMenu.icon" />
              <span> {{ translateName(route) }} </span>
            </b-link>
            <b-collapse
              :key="index"
              :visible="new RegExp('^' + route.path).test($route.path)"
              :id="`sidesub_${index}`"
              accordion="sidebar-accordion"
            >
              <b-link
                v-for="(sub, subRouteIndex) in route.children"
                :to="{ name: sub.name, params: setOnDemandProps(sub) }"
                @click.native="menuClicked($event)"
                :key="`right-${subRouteIndex}`"
                v-can:[linkAccess(sub).operation]="linkAccess(sub).module"
                exact
                :data-qa="`${$helpers.kebabCase(route.name)}-sub-side-menu`"
              >
                <div class="d-flex">
                  <icon :name="sub.dashboardMenu.icon || `caret-right`" />
                  <div class="text-wrap">{{ translateName(sub) }}</div>
                </div>
              </b-link>
            </b-collapse>
          </template>
        </template>
        <template v-else>
          <div class="shine sidebar-loader m-3 rounded-pill" :key="index"></div>
        </template>
      </template>
    </div>
    <span class="d-block d-md-none py-3"></span>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import EkgFounderBadge from '@/assets/img/ekg-pin-founders-club.svg'

export default {
  name: 'DashboardSidebar',
  data() {
    return {
      logo: this.$const.constImage.COMPANY_LOGO,
      profilePicture: '/static/misc/img-avatar-default.png',
      founderBadge: EkgFounderBadge,
      genderIds: {},
      test: 'view',
      menuCollapsed: false,
      sidebarChecker: false,
    }
  },
  computed: {
    ...mapGetters('dashboardMenu', ['sortedMenu']),
    ...mapGetters([
      'getMemberDetails',
      'getMemberInformation',
      'getLoggedInUser',
      'getMasterDataIdByKeyAndTitle',
      'isMemberAuthorityInitialized',
      'getPermissionRefreshTime',
      'getMemberFounderBonus',
    ]),
    ...mapMasterDataId({
      MEMBER_STATUS: {
        memberStatusActiveId: 'MEMBER_STATUS_ACTIVE',
      },
    }),
    getProfilePicture() {
      this.setProfileType()
      return this.profilePicture
    },
    linkAccess: vue => route => {
      let access = {
        operation: 'view',
        module: '',
      }
      if (route.meta !== undefined && route.meta.policy !== undefined) {
        let module = Object.keys(route.meta.policy)[0]
        if (module !== undefined) {
          access.module = module
          access.operation = route.meta.policy[module]
        }
      }

      return access
    },
  },
  created() {
    this.loadMasterDataKeys([this.$const.masterKey.GENDER]).then(() => {
      this.setProfileType()
    })
  },
  mounted() {
    this.$scrollTo('body')
    jQuery('body').css({ overflow: '' })
    this.loadMemberDetails()
    this.sidebarChecker = setInterval(() => {
      this.checkMenuCollapsed()
    }, 1000)
  },
  methods: {
    ...mapActions(['loadMasterDataKeys', 'loadMemberDetails']),
    translateName: function(route) {
      if (route.dashboardMenu.displayName) {
        if (route.dashboardMenu.displayName.constructor === Array) {
          return this.$t(...route.dashboardMenu.displayName)
        } else {
          return this.$t(route.dashboardMenu.displayName)
        }
      } else {
        return route.name
      }
    },
    menuClicked: function(event) {
      this.$scrollTo('body')
      document.querySelector('#app').classList.remove('app-sidebar-open')
      let freshwidget = document.querySelector('.freshwidget-button')
      if (freshwidget !== null) {
        freshwidget.classList.remove('freshwidget-button-toggle')
      }
      let lcChatLayout = document.querySelector('#lc_chat_layout')
      if (lcChatLayout !== null) {
        lcChatLayout.classList.remove('lc_chat_layout-button-toggle')
      }
      this.checkMenuCollapsed()
    },
    checkMenuCollapsed() {
      setTimeout(() => {
        if (
          this.$refs.sidebar !== undefined &&
          this.$refs.sidebar.clientWidth !== undefined &&
          this.$refs.sidebar.clientWidth > 50
        ) {
          this.menuCollapsed = false
        } else {
          this.menuCollapsed = true
        }
      }, 1000)
    },
    setProfileType() {
      if (this.getMemberDetails.avatar_image_link !== null && this.getMemberDetails.avatar_image_link !== '') {
        this.profilePicture = this.getMemberDetails.avatar_image_link
      } else {
        this.profilePicture = '/static/misc/img-default-male.png'
        if (
          this.getMemberInformation.gender_id ===
          this.getMasterDataIdByKeyAndTitle(this.$const.masterKey.GENDER, this.$const.masterData.FEMALE)
        ) {
          this.profilePicture = '/static/misc/img-default-female.png'
        }
      }
    },
    /**
     * Special case set props on-demand
     * PreDefined values will be used here - under dashboardMenu -> onDemandProps
     * @param route
     */
    setOnDemandProps(route) {
      let params = {}
      let onDemandProps = this.$helpers.getValue(route, 'dashboardMenu.onDemandProps', [])
      let currentRouteParams = route.path.match(/:[a-zA-Z]*/g) // search for router parameters

      onDemandProps.forEach(prop => {
        let paramList = (currentRouteParams && currentRouteParams.map(param => param.substring(1))) || [] // remove colon symbol for all element in the currentRouteParams

        if (paramList.includes(prop)) {
          if (
            prop === 'sponsorID' &&
            this.$helpers.getValue(this.getMemberDetails, 'enrollment_rank.enrollment_type.title', '').toLowerCase() ===
              'ba'
          ) {
            params = { ...params, sponsorID: this.getLoggedInUser.old_member_id }
          }
        }
      })

      return params
    },
    displayConstraints(route) {
      if (typeof this.$helpers.getValue(route, 'meta.dashboardMenu.externalPolicy') === 'function') {
        return route.meta.dashboardMenu.externalPolicy(this)
      } else {
        return true
      }
    },
  },
}
</script>
