<template>
  <div>
    <div v-can:view="'dashboard.ba'">
      <b-row class="py-3 text-medium">
        <b-col class="col-12 col-md-8 d-flex flex-column">
          <div>
            <span>
              {{ $t('Dashboard.Landing.BonusMsg', { date: getMemberDashboardDetail.updated_at_formatted || '...' }) }}
            </span>
            <span
              v-if="getCalculating === true"
              class="animated bg-primary fadeOut delay-4s ml-2 px-2 py-1 rounded-4 text-white infinite slower small"
            >
              {{ $t('Dashboard.Landing.Calculating') }}
            </span>
          </div>
          <div v-if="!$appSettings.evo.enable">
            <div>{{ $t('Dashboard.Landing.InfoDisclaimer') }}</div>
            <div v-if="getMemberDashboardDetail.days_left_until_closing">
              {{
                $t('Dashboard.Landing.RemainingClosingDay', { day: getMemberDashboardDetail.days_left_until_closing })
              }}
            </div>
          </div>
        </b-col>
        <b-col class="text-right pt-2 pt-md-0">
          <b-button pill class="bg-white text-primary border-0 px-4 py-2" :to="{ name: 'ReportCampaignReport' }">
            <icon name="campaign-icon" class="mr-2"></icon>
            {{ $t('Common.Campaign') }}
          </b-button>
        </b-col>
      </b-row>

      <home-stats class="py-3 shadow-sm bg-white mb-4 rounded dashboard-panel-element" :stats="getHomeStats">
        <template slot="tri_formation_btn" slot-scope="{ stat }">
          <b-button variant="link" @click="$refs.tvc_detail_modal.show()" class="pos-absolute-top-right">
            <icon :name="stat.top_right_icon"></icon>
          </b-button>
        </template>
      </home-stats>

      <b-row class="text-medium">
        <responsive-card-group
          :card-class="['shadow-sm mb-4']"
          :component-data="getIwbStatusData"
          :is-busy="isLoading('loadingMemberDetail')"
        />
        <gcv-line-chart :total-gcv-data="getTotalGcvData" :is-busy="isLoading('memberDashboardLoading')" class="mb-4" />
      </b-row>

      <b-row>
        <b-col cols="12" :class="{ 'col-lg-8': $security.policy.can('dashboard.ba', 'view') }">
          <rank-goal
            :rank-goal-data="getGoalRankDetail"
            :highest-rank-achieved="getGoalRankDetail.highest_rank"
            class="shadow-sm"
          />

          <responsive-card-group
            v-if="getEnrolmentRankList.length > 0"
            :component-data="getUpgradePlanData"
            :card-class="['shadow-sm']"
          >
            <template slot="cardBody" slot-scope="{ item }">
              <div class="text-center">
                <div class="font-weight-bold-extra text-uppercase font-size-4 mb-2">
                  <span>{{ $helpers.getValue(item, 'rank', '') }}</span>
                </div>
                <div class="h5 mb-2">
                  <span>{{ $t('Eshop.Product.CV') }} {{ $helpers.getValue(item, 'bv', '') }}</span>
                </div>
                <div class="my-4">
                  <b-btn class="border-0 rounded-3 bg-primary px-3" :to="{ name: 'Listing' }">
                    {{ $t('Dashboard.Landing.Card.UpgradePlan.UpgradeNow') }}
                  </b-btn>
                </div>
              </div>
            </template>
          </responsive-card-group>
        </b-col>

        <b-col>
          <profile-summary
            class="shadow-sm"
            :current-rank="getGoalRankDetail.rank"
            :dashboard-data="getMemberDashboardDetail"
            :highest-rank="getGoalRankDetail.highest_rank"
          />
        </b-col>
      </b-row>
    </div>

    <tvc-info-modal ref="tvc_detail_modal" />
  </div>
</template>

<script>
import _ from 'lodash'
import Helpers from '@/helpers'
import { mapGetters } from 'vuex'
import IwbMixin from '@/app/dashboard/home/mixins/iwbMixin'
import RankGoal from '@/app/dashboard/home/components/elements/RankGoal'
import HomeStats from '@/app/dashboard/home/components/elements/HomeStats'
import TvcInfoModal from '@/app/dashboard/home/components/elements/TvcInfoModal'
import GcvLineChart from '@/app/dashboard/home/components/elements/GcvLineChart'
import ResponsiveCardGroup from '@/elements/common/components/ResponsiveCardGroup'
import ProfileSummary from '@/app/dashboard/home/components/elements/ProfileSummary'

export default {
  name: 'IbsDashboard',
  components: { ProfileSummary, RankGoal, GcvLineChart, ResponsiveCardGroup, HomeStats, TvcInfoModal },
  mixins: [IwbMixin],
  computed: {
    ...mapGetters([
      'isLoading',
      'getIwbStatus',
      'getCalculating',
      'getBuilderStatus',
      'getMemberDetails',
      'getGcvGraphDetail',
      'getGoalRankDetail',
      'getMemberDashboardDetail',
      'getMemberEnrollmentRankList',
    ]),
    getHomeStats() {
      let personalSalesPv = Number(this.getMemberDashboardDetail.personal_bv) || 0
      let tvc = Number(this.getMemberDashboardDetail.tvc_percentage) || 0
      let newlySponsored = Number(this.getMemberDashboardDetail.newly_sponsor) || 0
      let directSponsored = Number(this.getMemberDashboardDetail.personal_sponsor) || 0
      let directSponsoredActive = Number(this.getMemberDashboardDetail.personal_sponsor_active) || 0
      let totalSponsored = Number(this.getMemberDashboardDetail.total_sponsor) || 0
      let totalSponsoredActive = Number(this.getMemberDashboardDetail.total_sponsor_active) || 0
      let unredeemEsac = Number(this.getMemberDashboardDetail.unredeem_esac) || 0

      return [
        {
          icon: 'dashboard-pv',
          color: 'caribbean-green',
          title: this.$t('Common.Terminology.PersonalSalesPV'),
          value: personalSalesPv,
          loading: '',
        },
        {
          icon: 'dashboard-member-tree',
          color: 'viking',
          title: this.$t('Dashboard.Landing.Stat.TriFormation'),
          value: tvc + '%',
          loading: '',
          size: 4,
          top_right_icon: 'info-circle-icon',
          top_right_icon_slot_name: 'tri_formation_btn',
        },
        // {
        //   icon: 'dashboard-star',
        //   color: 'cold-purple',
        //   title: this.$t('Dashboard.Landing.Stat.NewlySponsored'),
        //   value: newlySponsored,
        //   loading: '',
        // },
        // {
        //   icon: 'dashboard-target',
        //   color: 'success',
        //   title: this.$t('Dashboard.Landing.Stat.DirectSponsored'),
        //   value: directSponsored,
        //   loading: '',
        //   description: this.$t('Dashboard.Landing.Stat.Active', { count: directSponsoredActive }),
        // },
        // {
        //   icon: 'dashboard-globe-w',
        //   color: 'salmon',
        //   title: this.$t('Dashboard.Landing.Stat.TotalSponsored'),
        //   value: totalSponsored,
        //   loading: '',
        //   description: this.$t('Dashboard.Landing.Stat.Active', { count: totalSponsoredActive }),
        // },
        {
          icon: 'dashboard-esac',
          color: 'info-green',
          title: this.$t('Dashboard.Landing.Stat.UnredeemedEsac'),
          value: unredeemEsac,
          loading: '',
          path: { name: 'EsacDashboard' },
          top_right_icon: 'dashboard-navigate',
        },
      ]
    },
    getTotalGcvData() {
      if (!_.isEmpty(this.getGcvGraphDetail)) {
        let [leftData, rightData, leftCurrent, rightCurrent] = [[], [], [], []]
        if (this.getGcvGraphDetail.values !== undefined) {
          for (let week in this.getGcvGraphDetail.values) {
            let left = Helpers.getValue(this.getGcvGraphDetail, 'values[' + week + '].left') || 0
            let right = Helpers.getValue(this.getGcvGraphDetail, 'values[' + week + '].right') || 0
            leftData.push(left)
            rightData.push(right)
          }
        }
        let isThousand = Math.max(...leftData) >= 1000 || Math.max(...rightData) >= 1000

        /**
         * RGB maker, make rgb from colors set in scss
         */
        let rgbMaker = function(name, opacity) {
          let style = getComputedStyle(document.body)
          let color = style.getPropertyValue(name).trim()
          let c
          let rgba

          if (opacity > 1) {
            throw 'Opacity cannot be greater than 1'
          }
          if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(color)) {
            c = color.substring(1).split('')
            if (c.length === 3) {
              c = [c[0], c[0], c[1], c[1], c[2], c[2]]
            }
            c = '0x' + c.join('')

            rgba = 'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',' + opacity + ')'
          } else {
            rgba = color
          }

          return rgba
        }

        /**
         * Chart Js by default doesnt allow to change colors half way though the chart. Because our chart is
         * showing current PC and past PC's we want to differentiate the progress the. We can do it using gradient and a
         * chart plugin
         */
        let chartColorFn = function(chart) {
          let setColors = ['--chart-color-one', '--chart-color-two']
          for (let ch = 0; ch < setColors.length; ch++) {
            let leftDataSet = chart.data.datasets[ch]
            let style = getComputedStyle(document.body)
            let color = style.getPropertyValue(setColors[ch]).trim()
            let rgba
            let meta = chart.getDatasetMeta(0)
            let startX = meta.data[0]._model.x
            let endX = meta.data[meta.data.length - 1]._model.x
            let breakX = meta.data[meta.data.length - 2]._model.x
            // Check of NaN
            if (!!startX && !!endX && !!breakX) {
              let gradientBackground = chart.canvas.getContext('2d').createLinearGradient(startX, 0, endX, 0)
              let gradientLine = chart.canvas.getContext('2d').createLinearGradient(startX, 0, endX, 0)

              rgba = rgbMaker(setColors[ch], 0.0)
              gradientBackground.addColorStop(0, rgba)

              rgba = rgbMaker(setColors[ch], 0.3)
              gradientBackground.addColorStop((breakX - startX) / (endX - startX), rgba)
              rgba = rgbMaker(setColors[ch], 0.5)
              gradientLine.addColorStop(0, rgba)
              gradientLine.addColorStop((breakX - startX) / (endX - startX), rgba)

              rgba = rgbMaker(setColors[ch], 0.0)
              gradientBackground.addColorStop((breakX - startX) / (endX - startX), rgba)
              gradientBackground.addColorStop(1, rgba)
              rgba = 'rgba(0,0,0,0.2)'
              gradientLine.addColorStop((breakX - startX) / (endX - startX), rgba)
              gradientLine.addColorStop(1, rgba)

              leftDataSet.borderColor = gradientLine
              leftDataSet.backgroundColor = gradientBackground
            }
          }
        }
        let self = this
        let result = {
          callback: function(value) {
            if (isThousand) {
              return value % 1000 === 0 ? self.$t('Dashboard.Landing.Chart.Thousands', { value: value / 1000 }) : null
            }
            return value
          },
          plugin: {
            id: 'tvc-plugin',
            beforeDatasetsUpdate: chartColorFn,
          },
        }
        result['labels'] = this.getGcvGraphDetail.pc_names
        result['legends'] = [
          {
            title: this.$t('Dashboard.Landing.Chart.TotalGcv.Left'),
            color: 'chart-color-one',
          },
          {
            title: this.$t('Dashboard.Landing.Chart.TotalGcv.Right'),
            color: 'chart-color-two',
          },
        ]
        result['data'] = [
          {
            label: this.$t('Dashboard.Landing.Chart.TotalGcv.Left'),
            data: leftData,
            borderColor() {
              return rgbMaker('--chart-color-one', 0.6)
            },
            borderDash: [5, 5],
            pointBackgroundColor: '--chart-color-one',
          },
          {
            label: this.$t('Dashboard.Landing.Chart.TotalGcv.Right'),
            data: rightData,
            borderColor() {
              return rgbMaker('--chart-color-two', 0.6)
            },
            borderDash: [5, 5],
            pointBackgroundColor: '--chart-color-two',
          },
        ]

        return result
      }
      return null
    },
    getIwbStatusData() {
      let result = {}
      let cardDeck = []
      if (!_.isEmpty(this.getIwbStatus)) {
        let dataSet = [this.iwbState('current'), this.iwbState('next')]

        for (let index in dataSet) {
          let blocksArr = []
          let statusArr = []
          let statusSet = [dataSet[index].left, dataSet[index].right]
          let achievementSet = dataSet[index].achievement
          let card = { title: '', body: {}, footer: {} }
          card['title'] =
            dataSet[index].key === 'Current'
              ? this.$t('DashBoard.Landing.FSBStatus.Current.Label')
              : this.$t('DashBoard.Landing.FSBStatus.Goal.Label')

          if (dataSet[index].displayStatuses === true) {
            for (let i in statusSet) {
              // Loop Status
              let status = { state: {} }
              if (statusSet[i].key === 'left') {
                status['title'] = this.$t('DashBoard.Landing.FSBStatus.Left.Label')
                status['state']['stateClass'] = ['flex-row-reverse']
                status['statusClass'] = ['border-right', 'text-right']
              } else {
                status['title'] = this.$t('DashBoard.Landing.FSBStatus.Right.Label')
                status['statusClass'] = ['border-left', 'text-left']
              }
              status['state']['value'] = statusSet[i].value
              statusArr.push(status)
            }
          }
          card['status'] = statusArr
          card['body']['title'] =
            dataSet[index].key === 'Goal' ? this.$t('Dashboard.Landing.FSBStatus.MustAchieve.Label') : ''

          for (let n in achievementSet) {
            // Loop Achievement
            if (achievementSet[n].text) {
              let block = {}
              block['text'] = achievementSet[n].text
              block['icon'] = achievementSet[n].status.icon
              block['iconColor'] = achievementSet[n].status.iconColor
              blocksArr.push(block)
            }
          }
          card['body']['blocks'] = blocksArr

          card['footer']['text'] = dataSet[index].reward
          card['footer']['footerClass'] = ['bg-white', 'text-center']
          let textColor = dataSet[index].key === 'Current' ? 'text-info-green' : 'text-danger'
          card['footer']['footerClass'].push(textColor)

          cardDeck.push(card)
        }
      }
      result['componentClass'] = ['mb-4', 'col-12', 'col-lg-6']
      result['title'] = this.$t('DashBoard.Landing.FSBStatus.Title')
      result['cards'] = cardDeck
      result['splitterIcon'] = 'angle-double-right'
      return result
    },
    getUpgradePlanData() {
      let result = {}
      if (this.getEnrolmentRankList.length > 0) {
        let cardDeck = []

        for (let index in this.getEnrolmentRankList) {
          let card = {}
          card['rank'] = Helpers.getValue(this.getEnrolmentRankList[index], 'rank_code', '')
          card['bv'] = Helpers.getValue(this.getEnrolmentRankList[index], 'CV', '')
          cardDeck.push(card)
        }

        result['componentClass'] = ['px-0']
        result['title'] = this.$t('Dashboard.Landing.Card.UpgradePlan.Title')
        result['description'] = {}
        result['description']['text'] = this.$t('Dashboard.Landing.Card.UpgradePlan.Message')
        result['description']['descriptionClass'] = ['col-12', 'pt-3', 'text-medium']
        result['cards'] = cardDeck
      }

      return result
    },
    getEnrolmentRankList() {
      return this.getMemberEnrollmentRankList
        .slice(2)
        .filter(rank => rank.entitlement_lvl > this.getMemberDetails.enrollment_rank.entitlement_lvl)
    },
  },
}
</script>
