<template>
  <div>
    <div class="dashboard-panel-element rounded-0">
      <section class="py-1 px-3">
        <b-row align-v="end">
          <b-col xl="4" lg="7" md="12">
            <span class="font-weight-bold small text-primary">
              {{ $t('Report.BonusStatement.PleaseSelect') }}
            </span>
            <div class="py-1">
              <b-form-select
                name="Report Type"
                id="campaign-list"
                v-model="reportTypeId"
                :options="reportTypeList"
                @change="validate"
              />
            </div>
          </b-col>
          <b-col xl="2" lg="3" md="4" class="px-lg-0" v-if="reportTypeId === 'weeklyBonusStatement'">
            <span class="font-weight-bold small text-primary">
              {{ $t('Report.BonusStatement.Week') }}
            </span>
            <div class="py-1">
              <b-form-select
                v-validate="'required'"
                name="Week"
                v-model="weekId"
                @change="fetchBonusData"
                :class="{ 'text-danger': errors.has('Week') }"
                :disabled="isLoading('cwScheduleList')"
              >
                <option :key="index" v-for="(week, index) in getWeeks" :value="week.id">
                  {{ week.cw_name }}
                </option>
              </b-form-select>
            </div>
            <span v-show="errors.has('Week')" class="help text-danger">
              {{ errors.first('Week') }}
            </span>
          </b-col>
          <b-col
            xl="2"
            lg="3"
            md="4"
            v-if="reportTypeId === 'annualIncomeStatement' || reportTypeId === 'CP58Statement'"
          >
            <span class="font-weight-bold small text-primary">
              {{ $t('Report.BonusStatement.Year') }}
            </span>
            <div class="py-1">
              <b-form-select
                v-validate="'required'"
                name="Year"
                v-model="yearId"
                :class="{ 'text-danger': errors.has('Year') }"
              >
                <option :key="index" v-for="(year, index) in getYears" :value="year">
                  {{ year }}
                </option>
              </b-form-select>
              <span v-show="errors.has('Year')" class="help text-danger">
                {{ errors.first('Year') }}
              </span>
            </div>
          </b-col>
          <b-col
            lg="3"
            md="4"
            sm="5"
            class="px-lg-0"
            v-if="reportTypeId === 'selfBilledInvoice' || reportTypeId === 'stockistSelfBilledInvoice'"
          >
            <span class="font-weight-bold small text-primary">
              {{ $t('Report.BonusStatement.WeekFrom') }}
            </span>
            <div class="py-1">
              <b-form-select
                @change="checkWeekFrom"
                v-validate="'required'"
                name="Week From"
                v-model="weekFrom"
                :class="{ 'text-danger': errors.has('Week From') }"
              >
                <option :key="index" v-for="(week, index) in getWeeks" :value="week.id">
                  {{ week.cw_name }}
                </option>
              </b-form-select>
              <span v-show="errors.has('Week From')" class="help text-danger">
                {{ errors.first('Week From') }}
              </span>
            </div>
          </b-col>
          <b-col
            lg="3"
            md="4"
            sm="5"
            class="px-xl-0"
            v-if="reportTypeId === 'selfBilledInvoice' || reportTypeId === 'stockistSelfBilledInvoice'"
          >
            <span class="font-weight-bold small text-primary">
              {{ $t('Report.BonusStatement.WeekTo') }}
            </span>
            <div class="py-1">
              <b-form-select
                @change="checkWeekTo"
                v-validate="'required'"
                name="Week To"
                v-model="weekTo"
                :class="{ 'text-danger': errors.has('Week To') }"
              >
                <option :key="index" v-for="(week, index) in getWeeks" :value="week.id">
                  {{ week.cw_name }}
                </option>
              </b-form-select>
              <span v-show="errors.has('Week To')" class="help text-danger">
                {{ errors.first('Week To') }}
              </span>
            </div>
          </b-col>
          <b-col xl="3" lg="5" sm="6" v-if="reportTypeId === 'welcomeBonusDaily'">
            <span class="font-weight-bold small text-primary">
              {{ $t('Report.BonusStatement.DayFrom') }}
            </span>
            <div class="py-1">
              <date-picker v-model="from" :lang="getSelectedLanguageCode" width="160" :not-after="new Date()" />
            </div>
          </b-col>
          <b-col xl="3" lg="5" sm="6" v-if="reportTypeId === 'welcomeBonusDaily'">
            <span class="font-weight-bold small text-primary">
              {{ $t('Report.BonusStatement.DayTo') }}
            </span>
            <div class="py-1">
              <date-picker v-model="to" :lang="getSelectedLanguageCode" width="160" :not-before="from" />
            </div>
          </b-col>
          <b-col class="col-10 col-lg-auto">
            <span class="font-weight-bold small text-primary">
              &nbsp;
            </span>
            <div class="py-1">
              <b-btn
                v-if="
                  !isLoading([
                    'weeklyBonusStatementLoading',
                    'statementLoading',
                    'welcomeBonusDailyLoading',
                    'authorizedReportListLoading',
                  ])
                "
                @click="showModal"
                variant="primary"
              >
                {{ $t('Report.GlobalWords.ViewReport') }}
              </b-btn>
              <icon name="spinner" class="text-primary align-bottom icon-size-3" pulse v-else />
            </div>
          </b-col>
          <b-col class="col-10 col-lg-auto no-gutter">
            <div class="py-1">
              <b-btn
                v-if="
                  (reportTypeId === 'annualIncomeStatement' || reportTypeId === 'CP58Statement') &&
                    !isLoading([
                      'weeklyBonusStatementLoading',
                      'statementLoading',
                      'welcomeBonusDailyLoading',
                      'authorizedReportListLoading',
                    ])
                "
                @click="fetchAuthorizedReports"
                variant="link"
              >
                {{ $t('Common.Refresh') }}
              </b-btn>
            </div>
          </b-col>
        </b-row>
      </section>
      <b-modal
        ok-only
        hide-header
        centered
        no-close-on-backdrop
        no-close-on-esc
        size="sm"
        class="eshop-model"
        ref="report_loading"
      >
        <div>{{ reportMessage }}</div>
        <div class="mt-2">
          <icon name="spinner" class="text-primary align-bottom icon-size-4" pulse />
        </div>
      </b-modal>
      <b-modal ok-only hide-header centered size="sm" class="eshop-model" ref="error_notice">
        <div>{{ getErrorMessage() }}</div>
      </b-modal>
      <b-modal ok-only hide-header centered size="sm" class="eshop-model" ref="report_modal">
        <div>{{ reportTypeId }}</div>
      </b-modal>
      <pdf-viewer-modal
        ref="pdf"
        :title="$t('Report.BonusStatement.Type.WeeklyBonusStatement')"
        :pdf-link="docUrl"
      ></pdf-viewer-modal>
    </div>
    <div v-if="showWelcomeBonusDaily" class="mt-4">
      <welcome-bonus-daily
        :welcome-bonus-data="welcomeBonus"
        :is-bonus-loading="isLoading('welcomeBonusDailyLoading')"
      />
    </div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import DatePicker from 'vue2-datepicker'
import welcomeBonusDaily from './blocks/WelcomeBonusDaily'
import pdfViewerModal from '@/app/_global/components/elements/pdfViewerModal'
import { mapMasterDataId } from '@/app/_global/mixins'
import moment from 'moment'
import _ from 'lodash'

export default {
  name: 'BonusStatement',
  $_veeValidate: {
    validator: 'new',
  },
  components: {
    pdfViewerModal,
    DatePicker,
    welcomeBonusDaily,
  },
  data() {
    return {
      reportTypeId: 'weeklyBonusStatement',
      weekId: '',
      yearId: new Date().getFullYear(),
      weekDetail: [],
      from: null,
      to: null,
      weekFrom: '',
      weekTo: '',
      docUrl: '',
      weeklyReportType: [
        { value: 'weeklyBonusStatement', text: this.$t('Report.BonusStatement.Type.WeeklyBonusStatement') },
        { value: 'selfBilledInvoice', text: this.$t('Report.BonusStatement.Type.SelfBilledInvoice') },
        { value: 'welcomeBonusDaily', text: this.$t('Report.BonusStatement.Type.WelcomeBonusByDaily') },
      ],
      showWelcomeBonusDaily: false,
      welcomeBonus: [],
      IBOData: [],
      reportTypeList: [],
      subscriptionError: false,
      channels: {
        private: {
          BONUS1: 'report.bonus-yearly-report',
        },
      },
      reportMessage: '',
    }
  },
  computed: {
    ...mapGetters([
      'getErrors',
      'isLoading',
      'getMemberIboDetails',
      'getCwScheduleDetails',
      'getCwScheduleListPast',
      'getWeeklyBonusStatementData',
      'getSelectedLanguageCode',
      'getAnnualIncomeStatementData',
      'getWelcomeBonusDailyData',
      'getAuthorizedReportList',
      'getPrivateChannelNameWithUserID',
    ]),
    ...mapGetters({
      getWeeks: 'getCwScheduleListPast',
    }),
    ...mapMasterDataId({
      YEARLY_REPORT_TYPE: {
        statementId: 'STATEMENT_REPORT',
        cp58Id: 'CP58_REPORT',
      },
    }),
    getYears: vue => {
      let years = []
      let selectedReportId = 0
      if (vue.reportTypeId === 'annualIncomeStatement') {
        selectedReportId = vue.statementId
      } else if (vue.reportTypeId === 'CP58Statement') {
        selectedReportId = vue.cp58Id
      }
      let report = vue.getAuthorizedReportList.find(x => x.report_master_data.id === selectedReportId)
      if (report !== undefined) {
        report.report_years
          .filter(year => year.is_published === 1)
          .forEach(year => {
            years.push(year.year)
          })
      }
      if (years.length > 0) {
        vue.yearId = years[0]
      } else {
        years.push(new Date().getFullYear())
      }
      return years
    },
  },
  async mounted() {
    this.loadCwScheduleList({
      filter_type: 'past',
      is_published: 1,
      order: 'desc',
    }).then(() => {
      this.validate('weeklyBonusStatement')
    })
    await this.fetchAuthorizedReports()
    this.$echo
      .private(this.getPrivateChannelNameWithUserID(this.channels.private['BONUS1']))
      .listen('.report.response', data => {
        this.$refs.report_loading.hide()
        if (data.status) {
          if (data.links.length > 0) {
            for (let item of data.links) {
              window.open(item.download_link, '_blank')
            }
          }
        } else {
          this.$refs.error_notice.show()
        }
      })
    this.$echo
      .private(this.getPrivateChannelNameWithUserID(this.channels.private['BONUS1']))
      .listen('.subscription_error', () => {
        this.subscriptionError = true
      })
  },
  methods: {
    ...mapActions([
      'loadCwScheduleList',
      'getWeeklyBonusStatement',
      'loadAnnualIncomeStatement',
      'loadCP58Statement',
      'loadWelcomeBonusDaily',
      'loadAuthorizedReportList',
      'isMobile',
    ]),
    async fetchAuthorizedReports() {
      await this.resolveMasters
      await this.loadAuthorizedReportList().then(async () => {
        this.reportTypeList = await _.cloneDeep(this.weeklyReportType)
        this.getAuthorizedReportList.forEach(report => {
          let publishedYears = report.report_years.filter(year => year.is_published === 1)
          if (publishedYears.length > 0) {
            if (report.report_master_data_id === this.statementId) {
              this.reportTypeList.push({
                value: 'annualIncomeStatement',
                text: this.$t('Report.BonusStatement.Type.AnnualIncomeStatement'),
              })
            } else if (report.report_master_data_id === this.cp58Id) {
              this.reportTypeList.push({
                value: 'CP58Statement',
                text: this.$t('Report.BonusStatement.Type.CP58Statement'),
              })
            }
          }
        })
      })
    },
    fetchBonusData: function(val) {
      if (typeof val !== 'undefined') {
        this.docUrl = ''
        this.getWeeklyBonusStatement(val).then(() => {
          if (!this.getErrors('weeklyBonusStatement')) {
            this.docUrl = this.getWeeklyBonusStatementData.download_link[0].download_link
          }
        })
      }
    },
    showModal() {
      if (this.reportTypeId === 'weeklyBonusStatement') {
        if (this.getErrors('weeklyBonusStatement')) {
          this.$refs.error_notice.show()
        } else {
          this.$refs.pdf.show()
        }
      } else if (this.reportTypeId === 'annualIncomeStatement' || this.reportTypeId === 'CP58Statement') {
        if (!this.subscriptionError) {
          if (this.reportTypeId === 'CP58Statement') {
            this.loadCP58Statement(this.yearId).then(() => {
              if (!this.getErrors('annualIncomeStatement')) {
                this.reportMessage = this.getAnnualIncomeStatementData.message
                this.$refs.report_loading.show()
              }
            })
          } else {
            this.loadAnnualIncomeStatement(this.yearId).then(() => {
              if (!this.getErrors('annualIncomeStatement')) {
                this.reportMessage = this.getAnnualIncomeStatementData.message
                this.$refs.report_loading.show()
              }
            })
          }
        } else {
          this.$refs.error_notice.show()
        }
      } else {
        this.viewReport()
      }
    },
    getErrorMessage() {
      if (this.reportTypeId === 'weeklyBonusStatement') {
        return this.getErrors('weeklyBonusStatement')
      } else if (this.reportTypeId === 'annualIncomeStatement' || this.reportTypeId === 'CP58Statement') {
        return this.$t('Report.BonusStatement.ReportGenerationFailed')
      } else {
        return this.$t('Common.RecordNotFound')
      }
    },
    checkWeekFrom: function(val) {
      if (this.weekTo === '') {
        this.weekTo = val
      } else {
        if (this.weekTo < val) {
          this.weekTo = val
        }
      }
    },
    checkWeekTo: function(val) {
      if (val < this.weekFrom) {
        this.weekTo = this.weekFrom
      }
    },
    validate(val) {
      this.reportTypeId = val
      if (val !== 'welcomeBonusDaily') {
        this.showWelcomeBonusDaily = false
        if (val === 'weeklyBonusStatement') {
          if (this.weekId === '') {
            this.weekId = this.getCwScheduleListPast[0].id
          }
          this.fetchBonusData(this.weekId)
        }
      } else {
        this.from = null
        this.to = null
      }
    },
    viewReport: function() {
      this.showWelcomeBonusDaily = false
      if (this.reportTypeId === 'annualIncomeStatement' || this.reportTypeId === 'CP58Statement') {
        this.IBOData = this.getMemberIboDetails[0]
        this.$refs.report_modal.show()
      } else if (this.reportTypeId === 'welcomeBonusDaily') {
        if (this.from !== null && this.to !== null) {
          this.loadWelcomeBonusDaily({
            from_date: moment(this.from).format('YYYY-MM-DD'),
            to_date: moment(this.to).format('YYYY-MM-DD'),
          }).then(() => {
            this.welcomeBonus = this.getWelcomeBonusDailyData
            this.showWelcomeBonusDaily = true
          })
        }
      } else {
        this.$validator.validate('Week From', this.weekFrom).then(valid => {
          if (valid) {
            if (this.weekTo < this.weekFrom) {
              this.weekTo = this.weekFrom
            }
            this.weekDetail = this.getCwScheduleDetails(this.weekId)
            this.IBOData = this.getMemberIboDetails[0]
            this.$refs.report_modal.show()
          }
        })
      }
    },
  },
  destroyed() {
    this.$echo.leave(this.getPrivateChannelNameWithUserID(this.channels.private['BONUS1']))
  },
}
</script>
