import Vue from 'vue'
import './SntApp.scss'
import { getSlot } from 'vuetify/lib/util/helpers'
import { mapActions, mapGetters } from 'vuex'
import jwt from 'jwt-simple'
import {
  GET_PRODUCT_CATEGORIES,
  GET_PRODUCT_BRANDS,
  GET_SALEPAGE_PRODUCT_CATEGORIES,
  GET_SALEPAGE_PRODUCT_BRANDS
} from '../../resources/graphql'

export default Vue.extend({
  name: 'SntApp',
  apollo: {
    productCategories: {
      query () {
        if (this.isDemo) {
          return GET_PRODUCT_CATEGORIES
        }
        return GET_SALEPAGE_PRODUCT_CATEGORIES
      },
      variables () {
        if (this.isDemo) {
          return {}
        }
        return {
          domain: this.subdomain
        }
      },
      update (data) {
        if (this.isDemo) {
          return data.productCategories
        }
        return data.salePage.productCategoryList.nodes
      }
    },
    productBrands: {
      query () {
        if (this.isDemo) {
          return GET_PRODUCT_BRANDS
        }
        return GET_SALEPAGE_PRODUCT_BRANDS
      },
      variables () {
        if (this.isDemo) {
          return {}
        }
        return {
          domain: this.subdomain
        }
      },
      update (data) {
        if (this.isDemo) {
          return data.productBrands
        }
        return data.salePage.productBrandList.nodes
      }
    }
  },
  data () {
    return {
      productCategories: [],
      productBrands: [],
      scrollY: 0,
      scrollUp: 0,
      lastScrollTop: 0
    }
  },
  computed: {
    ...mapGetters({
      subdomain: 'salePage/subdomain',
      customer: 'salePage/customer',
      purchasesQuantity: 'cart/purchasesQuantity'
    }),
    loading () {
      return this.$apollo.queries.productCategories.loading
        || this.$apollo.queries.productBrands.loading
    },
    isDemo () {
      return !this.subdomain
    },
    isMobileDevice () {
      return /Android|webOS|iPhone|iPad|Mac|Macintosh|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    },
    isAuth () {
      return this.customer?.id || false
    },
    customerName () {
      return this.customer?.name
    }
  },
  beforeDestroy () {
    if (typeof window !== 'undefined') {
      window.removeEventListener('scroll', this.handleScroll)
    }
  },
  created () {
    this.handleScroll = this.$_.throttle(() => {
      const pageYOffset = window.pageYOffset || document.documentElement.scrollTop
      this.scrollY = window.scrollY
      this.scrollUp = this.lastScrollTop - pageYOffset
      this.lastScrollTop = pageYOffset <= 0 ? 0 : pageYOffset
    }, 30)
    if (typeof window !== 'undefined') {
      window.addEventListener('scroll', this.handleScroll)
    }
  },
  methods: {
    ...mapActions({
      addToCart: 'cart/addToCart'
    }),
    resolveCustomer (customer) {
      const { id, taxId, tel, name, address, email, addressList } = customer
      const filteredAddressList = addressList.filter((item) => !!item.name
        && !!item.postcode
        && !!item.address
        && !!item.tel)
      this.setCustomer({
        id,
        taxId,
        addressList: filteredAddressList,
        tel,
        name,
        address,
        email
      })
    },
    async login (user, password) {
      if (!this.$auth) return false
      const secret = 'zdWIiOiIxMjM0NTY3zI1ODkwIiwibm6IFtZSI6I'
      const customer = await this.$auth.loginWith('local', {
        data: {
          query: `
            query ($id: ID, $domain: String, $tel: String!, $postcode: String!) {
              salePage (id: $id, domain: $domain) {
                id
                findCustomer (tel: $tel, postcode: $postcode) {
                  id
                  addressList
                  address,
                  name
                  tel
                  taxId
                  email
                }
              }
            } 
          `,
          variables: {
            domain: this.subdomain,
            tel: user,
            postcode: password
          }
        },
        transformResponse: [function (data) {
          const { data: { salePage: { findCustomer } } } = JSON.parse(data)
          return {
            user: findCustomer,
            token: findCustomer
            ? jwt.encode({
              id: findCustomer.id,
              tel: findCustomer.tel
            }, secret)
            : null
          }
        }]
      }).then(({ data }) => data)
      if (this.$auth.loggedIn) {
        this.resolveCustomer(customer.user)
        // this.setSnackbar({
        //   message: 'เข้าสู่ระบบสำเร็จ',
        //   timeout: 3000,
        //   type: 'success',
        //   value: true
        // })
      } else {
        // this.setSnackbar({
        //   message: 'เข้าสู่ระบบไม่สำเร็จ',
        //   timeout: 3000,
        //   type: 'warning',
        //   value: true
        // })
      }
      return this.$auth.loggedIn
    },
    getContentSlot () {
      return getSlot(this, 'default', {
        _: this.$_,
        router: this.$router,
        route: this.$route,
        shipnity: this.$shipnity,
        loading: this.loading,
        subdomain: this.subdomain,
        isMobileDevice: this.isMobileDevice,
        isAuth: this.isAuth,
        customer: this.customer,
        theme: this.$shipnity.theme.themes.light,
        productBrands: this.productBrands,
        productCategories: this.productCategories,
        purchasesQuantity: this.purchasesQuantity,
        breakpoint: this.$shipnity.breakpoint,
        notification: this.$shipnity.notification,
        goTo: this.$shipnity.goTo,
        addToCart: this.addToCart,
        scrollY: this.scrollY,
        scrollUp: this.scrollUp,
        customerName: this.customerName,
        login: this.login
      }, false) || []
    }
  },
  render (h) {
    return h('div', {
      staticClass: 'snt-app'
    }, this.getContentSlot())
  }
})
