<template>
  <div class="snt-promocodes">
    <v-container class="snt-promocodes__container">
      <v-dialog
        v-model="dialog"
        max-width="500">
        <template #activator="{ on, attrs }">
          <div class="d-flex align-center">
            <div class="snt-promocodes__title">
              <div class="snt-promocodes-title">
                คูปองส่วนลด
              </div>
              <div
                v-if="selectedCode.code"
                class="snt-promocodes-content">
                <div>{{ selectedCode.code }}</div>
                <div>
                  ( ลดราคา {{ selectedCode.discountValue }}  {{ formatDiscountType(selectedCode.discountType) }} )
                </div>
              </div>
            </div>
            <v-spacer />
            <v-btn
              v-bind="attrs"
              color="primary"
              depressed
              v-on="on">
              เลือก
            </v-btn>
          </div>
        </template>
        <div class="snt-promocodes-dialog">
          <v-container class="snt-promocodes-dialog__container">
            <div class="snt-promocodes-dialog__title">
              <span> โค้ดส่วนลด </span>
              <v-spacer />
              <v-icon @click="setDialog(false)">
                mdi-close
              </v-icon>
            </div>
            <div class="snt-promocodes-dialog__text">
              <div class="snt-promocodes__chips">
                <v-chip
                  class="snt-promocodes__chip"
                  :color="!claimable ? 'primary': '#C4C4C4'"
                  dark
                  depressed
                  @click="setPromocodeType(false)">
                  ใช้ได้ทันที
                </v-chip>
                <v-chip
                  v-if="isAuth"
                  class="snt-promocodes__chip"
                  :color="claimable ? 'primary': '#C4C4C4'"
                  dark
                  depressed
                  @click="setPromocodeType(true)">
                  ที่เก็บไว้
                </v-chip>
              </div>
              <div
                v-if="claimable"
                class="snt-promocode-filters">
                <v-text-field
                  :value="search"
                  placeholder="ค้นหา"
                  prepend-inner-icon="mdi-magnify"
                  dense
                  outlined
                  hide-details
                  @input="debounceSetSearch($event)" />
                <v-select
                  v-model="filter"
                  :items="items"
                  item-text="text"
                  item-value="value"
                  dense
                  outlined
                  hide-details />
              </div>
              <div class="snt-promocodes__content">
                <div
                  v-if="loading"
                  class="text-center">
                  <v-progress-circular
                    :size="14"
                    :width="1"
                    color="secondary"
                    indeterminate
                  />
                </div>
                <template v-else>
                  <div
                    v-if="filteredPromoCodes.length"
                    class="snt-promocodes__list">
                    <div
                      v-for="(promoCode, i) in filteredPromoCodes"
                      :key="`promocode-${i}`"
                      class="snt-promocodes__list-card mb-4">
                      <div class="snt-promocodes__list-card-title">
                        <v-chip
                          class="snt-promocodes__list-card-text-discount"
                          color="error"
                          small
                          label>
                          ลดราคา {{ promoCode.discountValue }}
                          {{ formatDiscountType(promoCode.discountType) }}
                        </v-chip>
                        <v-chip
                          class="snt-promocodes__list-card-text-code"
                          color="warning"
                          small
                          label>
                          {{ promoCode.code }}
                        </v-chip>
                      </div>
                      <div class="snt-promocodes__list-card-text">
                        <div class="d-flex justify-space-between">
                          <div>
                            <div>
                              ใช้ {{ promoCode.pointUsed }} แต้ม
                              ซื้อขั้นต่ำอย่างน้อย {{ promoCode.minRedeemValue }} {{ formatRedeemType(promoCode.minRedeemType) }}
                            </div>
                            <div class="snt-promocodes__list-card-text-description">
                              ใช้ได้ถึงวันที่ {{ promoCode.endDate | formatDateNoTime }}
                            </div>
                          </div>
                          <div>
                            <div class="d-flex w-100">
                              <v-spacer />
                              <v-btn
                                :disabled="isSelectedCode(promoCode) ||
                                  !canUsePromoCodes(promoCode.minRedeemType, promoCode.minRedeemValue)"
                                class="snt-promocodes__list-card-text-use"
                                color="primary"
                                depressed
                                @click="update(promoCode)">
                                <v-icon
                                  v-if="selectedCode.code === promoCode.code"
                                  left>
                                  mdi-check
                                </v-icon>
                                {{ canUsePromoCodes(promoCode.minRedeemType, promoCode.minRedeemValue) ? 'ใช้' : 'ใช้ไม่ได้' }}
                              </v-btn>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div
                    v-else
                    class="snt-promocodes__not-found">
                    <v-icon size="32">
                      mdi-sale
                    </v-icon>
                    <div class="snt-promocodes-not-found">
                      ไม่มีส่วนลด
                    </div>
                  </div>
                </template>
                <div class="snt-promocodes__footer">
                  <v-btn
                    v-if="!!selectedCode.code"
                    :ripple="false"
                    color="primary"
                    outlined
                    @click="update({
                      code: ''
                    })">
                    ไม่ใช้ส่วนลด
                  </v-btn>
                  <v-spacer />
                  <v-pagination
                    v-if="promoCodeList.pagesCount > 1"
                    :value="page"
                    :length="promoCodeList.pagesCount"
                    :total-visible="7"
                    class="snt-promocodes__pagination"
                    @input="setPage($event)">
                  </v-pagination>
                </div>
              </div>
            </div>
          </v-container>
        </div>
      </v-dialog>
    </v-container>
  </div>
</template>

<script>
import {
  GET_SALEPAGE_ALLPROMOCODES,
  GET_SALEPAGE_PROMOCODES
} from '@/resources/graphql'
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'SntPromoCodes',
  apollo: {
    promoCodeList: () => ({
      fetchPolicy: 'network-only',
      query () {
        return this.isAuth ? GET_SALEPAGE_ALLPROMOCODES : GET_SALEPAGE_PROMOCODES
      },
      skip () {
        return this.isDemo
      },
      variables () {
        const variables = {
          domain: this.subdomain,
          customerId: this.customerId,
          page: this.page,
          perPage: this.perPage
        }
        if (this.claimable) {
          variables.search = this.search
        }
        return variables
      },
      update ({ salePage }) {
        if (this.isAuth && this.claimable) {
          return salePage.findCustomer.activeClaimedPromoCodes
        }
        return salePage.promoCodeList
      }
    })
  },
  data () {
    return {
      dialog: false,
      claimable: false,
      search: '',
      promoCodeList: {
        nodes: [],
        nodesCount: 0,
        pagesCount: 0
      },
      page: 1,
      perPage: 12,
      filter: '',
      items: [
        {
          text: 'ทั้งหมด',
          value: ''
        },
        {
          text: 'ลดเป็นเปอร์เซ็นต์',
          value: 'percent'
        },
        {
          text: 'ลดเป็นบาท',
          value: 'baht'
        }
      ]
    }
  },
  computed: {
    ...mapGetters({
      subdomain: 'salePage/subdomain',
      customer: 'salePage/customer',
      checkout: 'salePage/checkout',
      selected: 'cart/selected'
    }),
    isDemo  () {
      return !this.subdomain
    },
    customerId () {
      return this.customer?.id
    },
    isAuth () {
      return !!this.customerId
    },
    selectedCode () {
      return this.checkout.promocode
    },
    loading () {
      return this.$apollo.queries.promoCodeList.loading
    },
    filteredPromoCodes () {
      const filteredPromoCodes = this.promoCodeList.nodes.filter((item) => item.claimable === this.claimable)
      if (this.claimable && this.filter) {
        return filteredPromoCodes.filter((item) => item.discountType === this.filter)
      }
      return filteredPromoCodes
    },
    sumPurchaseQuantity () {
      return this.selected.reduce((sum, item) => sum + item.quantity, 0)
    },
    sumPurchasePrice () {
      return this.selected.reduce((sum, item) => sum + (item.price * item.quantity), 0)
    }
  },
  created () {
    this.debounceSetSearch = this.$_.debounce(this.setSearch, 500)
  },
  methods: {
    ...mapActions({
      setCheckout: 'salePage/setCheckout'
    }),
    setSearch (search) {
      this.search = search
    },
    setDialog (val) {
      this.dialog = val
    },
    isSelectedCode (promoCode) {
      return this.selectedCode.code === promoCode.code
    },
    setPromocodeType (val) {
      this.claimable = val
    },
    update (value) {
      this.setCheckout({
        promocode: value
      })
      this.$emit('update', value)
      this.setDialog(false)
    },
    setPage (page) {
      this.page = page
    },
    canUsePromoCodes (redeemType, redeemValue) {
      if (redeemType === 'count_value') {
        return redeemValue <= this.sumPurchasePrice
      }
      return redeemValue <= this.sumPurchaseQuantity
    },
    formatDiscountType (discountType) {
      if (discountType === 'baht') {
        return 'บาท'
      }
      return '%'
    },
    formatRedeemType (redeemType) {
      if (redeemType === 'count_value') {
        return 'บาท'
      }
      return 'ชิ้น'
    }
  }
}
</script>
<style scoped>
  .snt-promocodes {
    background: #ffffff;
  }
  .snt-promocodes__list {
    min-height: 300px;
    max-height: 300px;
    padding-right: 8px;
    margin-right: -8px;
    overflow-y: auto;
  }
  .snt-promocodes__content {
    min-height: 250px;
  }
  .snt-promocodes__chips {
    display: flex;
    margin-bottom: 16px;
  }
  .snt-promocodes__chips > * {
    margin-right: 8px;
  }
  .snt-promocodes__chip {
    height: 40px;
    padding: 8px 20px;
    border-radius: 24px;
  }
  .snt-promocode-filters {
    display: flex;
    gap: 8px;
    margin-bottom: 12px;
  }
  .snt-promocodes-title {
    margin-bottom: 8px;
    font-weight: 500;
  }
  .snt-promocodes-content {
    display: flex;
    gap: 8px;
  }
  .snt-promocodes-no-data {
    font-size: 0.85rem;
  }
  .snt-promocodes-dialog {
    background: #FFFFFF;
  }
  .snt-promocodes-dialog__title {
    display: flex;
    font-size: 1.125rem;
    padding: 12px;
  }
  .snt-promocodes-dialog__text {
    padding: 12px;
  }
  .snt-promocodes__list-card {
    padding: 18px;
    border: 1px solid #e4e4e4;
    border-radius: 8px;
  }
  .snt-promocodes__list-card-text {
    margin-top: 8px;
  }
  .snt-promocodes__list-card-text-description {
    font-size: 0.85rem;
  }
  .snt-promocodes__not-found {
    display: flex;
    flex-direction: column;
    height: 180px;
    align-items: center;
    justify-content: center;
  }
  .snt-promocodes__footer {
    display: flex;
    align-items: center;
    margin-top: 24px;
  }
  .snt-promocodes-not-found {
    margin: 12px;
  }
</style>
