import Vue from 'vue'
import './SntPaymentMethods.scss'
import { mapActions, mapGetters } from 'vuex'
import { VProgressCircular, VRadioGroup, VRadio } from 'vuetify/lib'
import {
  GET_SALEPAGE_SHIPPING,
  GET_SHIPPING_CALCULATORS,
  GET_SALEPAGE_STOCK
} from '../../resources/graphql'

export default Vue.extend({
  name: 'SntPaymentMethods',
  components: { VProgressCircular, VRadioGroup, VRadio },
  apollo: {
    shippingList: () => ({
      query () {
        return this.isDemo ? GET_SHIPPING_CALCULATORS : GET_SALEPAGE_SHIPPING
      },
      variables () {
        return this.isDemo
          ? {
              page: 1,
              perPage: 50
            }
          : {
              domain: this.subdomain,
              input: {
                purchases: []
              }
            }
      },
      update (data) {
        const items = this.isDemo
          ? this.$_.map(data.shippingCalculators.nodes, ({ shippingType: name, cost, type }) => ({ name, cost, type }))
          : this.$_.map(data.salePage.shippingList, ({ name, cost, type }) => ({ name, cost, type }))

        const shippings = []
        const suffixCod = 'COD'
        items.forEach((item) => {
          const words = item.name.split(' ')
          const isCod = this.$_.includes(words, suffixCod)
          const filteredWords = this.$_.filter(words, (str) => str !== suffixCod)
          let name = filteredWords.join(' ')
          if (!name && isCod) {
            name = suffixCod
          }
          const value = {
            name,
            cost: item.cost,
            codCost: item.cost,
            type: item.type,
            isCod
          }
          const shipping = shippings.find((ship) => ship.name === value.name)
          if (!shipping) {
            shippings.push(value)
          } else {
            shipping.codCost = isCod ? item.cost : shipping.codCost
            shipping.isCod = isCod || shipping.isCod
          }
        })
        return shippings
      }
    }),
    scbPayment: () => ({
      fetchPolicy: 'network-only',
      query: GET_SALEPAGE_STOCK,
      skip () {
        return !this.subdomain
      },
      variables () {
        return {
          domain: this.subdomain
        }
      },
      update: (data) => data.salePage.stock.scbPayment
    })
  },
  data () {
    return {
      shippingList: [],
      scbPayment: false
    }
  },
  computed: {
    ...mapGetters({
      subdomain: 'salePage/subdomain',
      customer: 'salePage/customer',
      checkout: 'salePage/checkout'
    }),
    isDemo () {
      return !this.subdomain
    },
    customerId () {
      return this.customer?.id
    },
    shipping () {
      return this.checkout.shipping
    },
    paymentMethod () {
      return this.checkout.paymentMethod
    },
    loading () {
      return this.$apollo.queries.scbPayment.loading
    },
    methods () {
      const method = {
        TRANSFER: {
          text: 'โอนเงินผ่านบัญชีธนาคาร',
          value: 0
        },
        COD: {
          text: 'เก็บเงินปลายทาง',
          value: 1
        },
        SCBQR: {
          text: 'SCB QR Code',
          value: 2
        },
        CREDIT: {
          text: 'บัตรเครดิต',
          value: 3
        }
      }
      if (!this.shipping.name) {
        return []
      }
      if (this.shipping.name === 'COD') {
        return [method.COD]
      }
      const result = [method.TRANSFER]
      const shipping = this.$_.find(this.shippingList, ({ name }) => name === this.shipping.name)
      if (shipping && shipping.isCod) {
        result.push(method.COD)
      }
      if (this.scbPayment) {
        result.push(method.SCBQR)
      }
      result.push(method.CREDIT)
      return result
    },
    slotProps () {
      return {
        loading: this.loading,
        value: this.paymentMethod,
        items: this.methods,
        selectMethod: this.selectMethod
      }
    }
  },
  methods: {
    ...mapActions({
      setCheckout: 'salePage/setCheckout'
    }),
    selectMethod (value) {
      this.setCheckout({
        paymentMethod: value
      })
      this.$emit('input', value)
    }
  },
  template: `
    <div
      v-bind="$attrs"
      class="snt-payment-methods">
      <slot v-bind="slotProps">
        <div
          v-if="loading"
          class="text-center">
          <v-progress-circular
            :size="14"
            :width="1"
            color="secondary"
            indeterminate
          />
        </div>
        <template v-else>
          <snt-container class="snt-payment-methods__container">
            <div>
              เลือกวิธีการชำระเงิน
            </div>
            <v-radio-group
              :value="paymentMethod"
              hide-details
              @change="selectMethod($event)">
              <div class="snt-payment-methods__items">
                <template v-for="(method, i) in methods">
                  <div
                    :key="'payment-method-'+i"
                    class="snt-payment-methods__card"
                    :class="{ 'snt-payment-methods__card--active': paymentMethod === method.value }">
                    <v-radio
                      :value="method.value"
                      :label="method.text"
                      class="snt-payment-methods__radio" />
                  </div>
                </template>
              </div>
            </v-radio-group>
          </snt-container>
        </template>
      </slot>
    </div>
  `
})
