<template>
  <div class="dashboard-panel-element" v-can:view="'business-snapshot'">
    <b-col v-show="!isLoading('cwScheduleList')" cols="12" md="5" lg="3" class="my-3">
      <b-form-select :options="getBusinessSnapshotPayCycles" v-model="payCycleId" class="font-weight-bolder" />
    </b-col>

    <div
      v-if="!payCycleId || isLoading('loadingBusinessSnapshotData') || getErrors('businessSnapshotData')"
      class="text-center m-5 h-25 text-primary"
    >
      <template v-if="isLoading('loadingBusinessSnapshotData')">
        <b-spinner class="mr-2" />
        <strong class="h4">{{ $t('Common.Loading') }}</strong>
      </template>
      <template v-else>
        <strong class="h4">{{ $t('Common.RecordNotFound') }}</strong>
      </template>
    </div>

    <div v-else class="p-3">
      <b-row>
        <b-col cols="12" lg="6">
          <!--      Personal Activity, Global Pool Bank, Super Car & Luxury Home Bonus-->
          <custom-card-template
            class="mb-4"
            name="Personal Activity"
            :card-data="personalActivityData"
            data-qa-prefix="businessSnapShot-personalActivity"
          >
            <template slot="commissionsAndBonuses" slot-scope="{ context }">
              <b-col class="font-weight-bold">
                <b-row>
                  <template v-for="(data, indexes) in context">
                    <b-col :cols="Math.floor(12 / context.length)" :key="indexes">
                      <template v-for="(rowItem, index) in data.value">
                        <b-row :class="$helpers.getValue(rowItem, 'class', [])" class="mx-0 my-3" :key="index">
                          <b-col
                            v-if="$helpers.getValue(rowItem, 'iconName')"
                            class="px-0 text-right text-primary c-pointer"
                          >
                            <span :id="'icon' + index">
                              <icon :name="rowItem.iconName" />
                            </span>
                            <b-tooltip
                              v-if="$helpers.getValue(rowItem, 'tooltips')"
                              :target="'icon' + index"
                              :title="$t(rowItem.tooltips)"
                              placement="right"
                            />
                          </b-col>
                          <b-col class="p-0" :class="indexes === 0 ? 'text-right' : ''">
                            <span>{{ commissionAndBonusesDataFormatter(rowItem.value, indexes) }}</span>
                          </b-col>
                        </b-row>
                      </template>
                    </b-col>
                  </template>
                </b-row>
              </b-col>
            </template>
          </custom-card-template>

          <custom-card-template
            v-if="chpData"
            class="mb-4"
            :card-data="chpData"
            name="Super Car & Luxury Home Promotion"
            data-qa-prefix="businessSnapShot-superCarAndLuxuryHomePromotion"
          />

          <custom-card-template
            name="Global Pool Bank"
            class="mb-4"
            :card-data="gpbData"
            data-qa-prefix="businessSnapShot-globalPoolBank"
          />
        </b-col>

        <b-col cols="12" lg="6">
          <!--      Team Paid as Rank-->
          <template v-for="(rank, index) in teamPaidAsRankData">
            <custom-card-template
              class="mb-4"
              :key="index"
              :card-data="rank"
              data-qa-prefix="businessSnapShot-teamPaidAsRank"
            />
          </template>
        </b-col>
      </b-row>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import _ from 'lodash'
import Helpers from '@/helpers'
import CustomCardTemplate from '@/elements/common/components/CustomCardTemplate'
import ImageBa from '@/assets/img/icon-ba.png'
import ImageDirector from '@/assets/img/icon-director.png'
import ImageDiamond from '@/assets/img/icon-diamond.png'
import ImagePresident from '@/assets/img/icon-president.png'
import ImageCrown from '@/assets/img/icon-crown.png'

export default {
  name: 'BusinessSnapshot',
  components: { CustomCardTemplate },
  data() {
    return {
      payCycles: [],
      payCycleId: null,
      payCycleFilter: { filter_type: 'current_past', by_dzyne_only: true, sort: 'id', order: 'desc', limit: 2 },
      rankProperties: new Map([
        [
          'ba',
          {
            key: 'qualifiedBa',
            zoneTitle: 'Report.BusinessSnapshot.QualifiedBaZone',
            styling: { subTitle: ['bg-light-extra', 'text-center'], text: ['text-black'] },
            image: ImageBa,
          },
        ],
        [
          'director',
          {
            key: 'qualifiedDirector',
            zoneTitle: 'Report.BusinessSnapshot.QualifiedDirectorZone',
            styling: { subTitle: ['bg-rank-director', 'text-center'], text: ['text-white'] },
            image: ImageDirector,
          },
        ],
        [
          'diamond',
          {
            key: 'qualifiedDiamond',
            zoneTitle: 'Report.BusinessSnapshot.QualifiedDiamondZone',
            styling: { subTitle: ['bg-rank-diamond', 'text-center'], text: ['text-white'] },
            image: ImageDiamond,
          },
        ],
        [
          'president',
          {
            key: 'qualifiedPresident',
            zoneTitle: 'Report.BusinessSnapshot.QualifiedPresidentZone',
            styling: { subTitle: ['bg-rank-president', 'text-center'], text: ['text-white'] },
            image: ImagePresident,
          },
        ],
        [
          'crown',
          {
            key: 'qualifiedCrown',
            zoneTitle: 'Report.BusinessSnapshot.QualifiedCrownZone',
            styling: { subTitle: ['bg-rank-crown', 'text-center'], text: ['text-white'] },
            image: ImageCrown,
          },
        ],
      ]),
      personalActivities: [
        { key: 'production', subTitle: 'Report.BusinessSnapshot.PersonalActivity.Production' },
        { key: 'commissionsAndBonuses', subTitle: 'Report.BusinessSnapshot.PersonalActivity.CommissionAndBonus' },
      ],
    }
  },
  async mounted() {
    if (!this.hasLoaded('cwInfo')) {
      await this.loadCwInfo()
    }
    this.loadCwScheduleList(this.payCycleFilter).then(cycles => {
      this.payCycles = cycles || []
    })
    this.payCycleId = this.getCwInfo.currentCwId
  },
  computed: {
    ...mapGetters(['getBusinessSnapshotData', 'hasLoaded', 'isLoading', 'getErrors']),
    ...mapGetters('eshop', ['getCwInfo']),

    personalActivityData() {
      let cardData = { title: {}, context: { class: [], data: [] } }
      cardData['title']['text'] = this.$t('Report.BusinessSnapshot.PersonalActivity').toUpperCase()
      cardData['title']['class'] = ['text-rank-crown', 'text-center']

      for (let index in this.personalActivities) {
        let subTitle = {}
        let itemContainer = []
        let footerContainer = []
        subTitle['text'] = this.$t(this.personalActivities[index].subTitle).toUpperCase()
        subTitle['class'] = ['bg-gray-200', 'text-center']
        let snapshotData = this.getBusinessSnapshotData(this.personalActivities[index].key)

        if (this.personalActivities[index].key === 'commissionsAndBonuses') {
          // Set Total Cycle Earning to footer array
          if (snapshotData.total_cycle_earning) {
            let footer = [
              {
                text: snapshotData.total_cycle_earning.title,
                class: ['col-6', 'font-weight-bolder', 'text-right'],
              },
              {
                text: [
                  Helpers.getValue(snapshotData, 'total_cycle_earning.currency.code', ''),
                  Helpers.getCurrencyValue(snapshotData.total_cycle_earning.value),
                ]
                  .join(' ')
                  .trim(),
                class: ['font-weight-bolder', 'text-left'],
              },
            ]
            footerContainer.push(footer)
          }

          // Set custom attributes
          let commissionAndBonuses = _.cloneDeep(snapshotData.weeks)

          commissionAndBonuses.forEach(week => {
            week.value.forEach(data => {
              if (data.key === 'sub_total') {
                data.class === undefined
                  ? (data['class'] = ['font-weight-bolder'])
                  : data['class'].push('font-weight-bolder')

                if (typeof data.value === 'number') {
                  data.value = this.$t('BusinessSnapShot.DefaultCurrencySymbol.Placeholder', {
                    amount: Helpers.getCurrencyValue(data.value),
                  })
                }
              }
            })
          })

          cardData['context']['data'].push({
            subTitle: subTitle,
            items: commissionAndBonuses,
            slotName: 'commissionsAndBonuses',
          })
        } else if (this.personalActivities[index].key === 'production') {
          for (let i in snapshotData) {
            let item = []
            item = [
              { text: snapshotData[i].title, class: ['text-right'] },
              { text: snapshotData[i].value, class: [] },
            ]

            if (snapshotData[i].key === 'active_status') {
              item[1].class = item[1].text ? ['text-info-green'] : ['text-danger']
              item[1].text = item[1].text ? this.$t('Common.Active') : this.$t('Common.Inactive')
            }
            itemContainer.push(item)
          }
          cardData['context']['data'].push({ subTitle: subTitle, items: itemContainer })
        }
        cardData['context']['class'] = ['font-weight-bold']
        cardData['footer'] = footerContainer
      }
      return cardData
    },

    gpbData() {
      let cardData = { title: {}, context: { class: [], data: [] } }
      let itemContainer = []
      let snapshotData = this.getBusinessSnapshotData('gpb')
      cardData['title']['text'] = this.$t('Common.Terminology.GlobalPoolBank').toUpperCase()
      cardData['title']['class'] = ['text-rank-diamond', 'border-bottom', 'mx-3', 'text-center']

      for (let index in snapshotData) {
        let item = [
          { text: snapshotData[index].title, class: ['text-right'] },
          { text: snapshotData[index].value, class: [] },
        ]
        if (snapshotData[index].key === 'total_amount') {
          for (let i in item) {
            item[i].class.push('font-weight-bolder')
          }
          item[1].text = this.$t('BusinessSnapShot.DefaultCurrencySymbol.Placeholder', {
            amount: Helpers.getCurrencyValue(item[1].text),
          })
        }
        itemContainer.push(item)
      }
      cardData['context']['data'].push({ subTitle: {}, items: itemContainer })
      cardData['context']['class'] = ['font-weight-bold']
      return cardData
    },

    chpData() {
      let cardData = { title: {}, context: { class: [], data: [] } }
      let itemContainer = []
      let snapshotData = this.getBusinessSnapshotData('chp')
      cardData['title']['text'] = this.$t('Common.Terminology.CarAndLuxuryHomePromotion').toUpperCase()
      cardData['title']['class'] = ['text-rank-director', 'border-bottom', 'mx-3', 'text-center']

      // remove CHP card if no CHP data was return
      if (snapshotData === null) {
        return false
      }

      for (let key in snapshotData) {
        let item = [
          { text: snapshotData[key].title, class: ['text-right'] },
          { text: snapshotData[key].value, class: [] },
        ]
        if (snapshotData[key].key === 'total_amount') {
          for (let i in item) {
            item[i].class.push('font-weight-bolder')
          }
          item[1].text = this.$t('BusinessSnapShot.DefaultCurrencySymbol.Placeholder', {
            amount: Helpers.getCurrencyValue(item[1].text),
          })
        }
        itemContainer.push(item)
      }
      cardData['context']['data'].push({ subTitle: {}, items: itemContainer })
      cardData['context']['class'] = ['font-weight-bold']
      return cardData
    },

    teamPaidAsRankData() {
      let cardDeck = []
      let ranks = ['ba', 'director', 'diamond', 'president', 'crown']

      ranks.forEach(rank => {
        let rankData = this.rankProperties.get(rank)
        let cardData = { title: {}, context: { class: [], data: [] } }
        let itemContainer = []
        let snapshotData = this.getBusinessSnapshotData(rankData.key)
        cardData['style'] = { backgroundImage: `url(${rankData.image})` }
        cardData['class'] = [...rankData.styling.subTitle, 'lighten-10', 'rounded']

        let subTitle = {}
        subTitle['text'] = this.$t(rankData.zoneTitle).toUpperCase()
        subTitle['class'] = [...rankData.styling.subTitle, ...rankData.styling.text, 'rounded-top']
        for (let key in snapshotData) {
          let item = [
            { text: this.$t(snapshotData[key].title), class: ['text-right'] },
            { text: snapshotData[key].value, class: ['text-left'] },
          ]

          if (item[1].text > 0) {
            item[1].class.push('font-weight-bolder')
          }
          itemContainer.push(item)
        }
        cardData['context']['class'] = [...rankData.styling.text, 'py-3', 'customBackgroundImage', 'font-weight-bold']
        cardData['context']['data'].push({ subTitle: subTitle, items: itemContainer })
        cardDeck.push(cardData)
      })
      cardDeck[0]['title']['text'] = this.$t('Common.Terminology.TeamPaidAsRank').toUpperCase()
      cardDeck[0]['title']['class'] = ['text-black-50', 'bg-white', 'rounded', 'text-center']
      cardDeck[0]['context']['data'][0]['subTitle']['class'].pop('rounded-top')
      return cardDeck
    },

    getBusinessSnapshotPayCycles() {
      let snapshotPayCycle = this.payCycles.map(cycle => {
        return {
          text: this.$t('Common.Terminology.PayCycle.Placeholder', { pc: cycle.cw_name }),
          value: cycle.id,
        }
      })
      return [
        { text: this.$t('Report.BusinessSnapshot.PayCycle.Placeholder'), value: null, disabled: true },
        ...snapshotPayCycle,
      ]
    },
  },
  methods: {
    ...mapActions(['loadCwScheduleList', 'loadBusinessSnapshotData']),
    ...mapActions('eshop', ['loadCwInfo']),
    commissionAndBonusesDataFormatter(data, weekIndex) {
      if (weekIndex !== 0) {
        if (data === 0) {
          return '-'
        } else if (typeof data === 'number') {
          return this.$t('BusinessSnapShot.DefaultCurrencySymbol.Placeholder', {
            amount: Helpers.getCurrencyValue(data),
          })
        }
      }
      return data
    },
  },
  watch: {
    payCycleId(val) {
      this.loadBusinessSnapshotData(val)
    },
  },
}
</script>
