import Vue from 'vue'
import './SntProductDetail.scss'
import { VProgressCircular } from 'vuetify/lib'
import { mapActions, mapGetters } from 'vuex'
import {
  GET_PRODUCTS,
  GET_PRODUCTSETS,
  GET_SALEPAGE_PRODUCTS,
  GET_SALEPAGE_SETPRODUCTS
} from '../../resources/graphql'

export default Vue.extend({
  name: 'SntProductDetail',
  components: { VProgressCircular },
  apollo: {
    product: () => ({
      fetchPolicy: 'network-only',
      skip () {
        return this.skip
      },
      query () {
        if (this.isCollection) {
          return this.subdomain ? GET_SALEPAGE_SETPRODUCTS : GET_PRODUCTSETS
        }
        return this.subdomain ? GET_SALEPAGE_PRODUCTS : GET_PRODUCTS
      },
      variables () {
        return this.subdomain
          ? {
              domain: this.subdomain,
              page: 1,
              perPage: 1,
              search: '',
              items: [this.productId]
            }
          : {
              page: 1,
              perPage: 1,
              search: '',
              stockId: this.stockId,
              id: [this.productId]
            }
      },
      update (data) {
        if (this.isCollection) {
          return this.subdomain
            ? data.salePage.productSetList.nodes[0]
            : data.productSets.nodes[0]
        }
        return this.subdomain
          ? data.salePage.productList.nodes[0]
          : data.products.nodes[0]
      },
      result ({ data }) {
        if (this.isCollection) {
          this.selectedPurchase = this.subdomain
            ? data.salePage.productSetList.nodes[0]
            : data.productSets.nodes[0]
        } else {
          this.selectedPurchase = this.subdomain
            ? data.salePage.productList.nodes[0].subproducts[0]
            : data.products.nodes[0].subproducts[0]
        }
      }
    })
  },
  data () {
    return {
      selectedImage: 0,
      product: {
        name: 'What is Lorem Ipsum?',
        price: 1850,
        descriptionShort: 'Into electronic typesetting, remaining essentially.',
        descriptionLong: `<div><div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer 
        took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but
        also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the 
        release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus 
        PageMaker including versions of Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer 
        took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but
        also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the 
        release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus 
        PageMaker including versions of Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer 
        took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but
        also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the 
        release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus 
        PageMaker including versions of Lorem IpsumLorem Ipsum is simply dummy text of the printing and typesetting industry. 
        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer 
        took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but
        also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the 
        release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus 
        PageMaker including versions of Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer 
        took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but
        also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the 
        release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus 
        PageMaker including versions of Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer 
        took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but
        also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the 
        release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus 
        PageMaker including versions of Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer 
        took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but
        also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the 
        release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus 
        PageMaker including versions of Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer 
        took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but
        also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the 
        release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus 
        PageMaker including versions of Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div></div>`,
        subproducts: [
          {
            id: 'main',
            name: 'main',
            available: 100
          },
          {
            id: 'desktop',
            name: 'desktop',
            available: 100
          },
          {
            id: 'tablet',
            name: 'tablet',
            available: 100
          },
          {
            id: 'mobile',
            name: 'mobile',
            available: 0
          }
        ],
        pictureUrl: 'https://via.placeholder.com/300/eee/c6c6c6?text=No image',
        available: 300,
        images: [
          'https://via.placeholder.com/300/eee/c6c6c6?text=No image',
          'https://via.placeholder.com/300/eee/c6c6c6?text=No image',
          'https://via.placeholder.com/300/eee/c6c6c6?text=No image',
          'https://via.placeholder.com/300/eee/c6c6c6?text=No image',
          'https://via.placeholder.com/300/eee/c6c6c6?text=No image',
          'https://via.placeholder.com/300/eee/c6c6c6?text=No image',
          'https://via.placeholder.com/300/eee/c6c6c6?text=No image',
          'https://via.placeholder.com/300/eee/c6c6c6?text=No image',
          'https://via.placeholder.com/300/eee/c6c6c6?text=No image'
        ]
      },
      quantity: 1,
      selectedPurchase: {
        id: '',
        name: '',
        price: 0,
        available: 0
      },
      countRules: [
        (v) => !!v || 'กรุณาใส่จำนวน',
        (v) => v <= this.selectedPurchase.available || 'เกินจำนวนสต๊อก',
        (v) => v > 0 || 'จำนวนขั้นต่ำ 1'
      ]
    }
  },
  computed: {
    ...mapGetters({
      salePage: 'salePage/salePage',
      subdomain: 'salePage/subdomain',
      purchases: 'cart/purchases',
      setPurchases: 'cart/setPurchases'
    }),
    skip () {
      return this.productId === 'default'
    },
    loading () {
      return this.$apollo.queries.product.loading
    },
    stockId () {
      return this.salePage?.stockId
    },
    isCollection () {
      return this.$route.name === 'SalePageCollectionDetail'
    },
    productId () {
      return this.$route.params.productId
    },
    images () {
      const images = this.product.images
      if (!images.length) {
        images.push('https://via.placeholder.com/300/eee/c6c6c6?text=No image')
      }
      return images.map((src) => ({
        src
      }))
    },
    subproducts () {
      let subproducts = this.product?.subproducts || []
      subproducts = subproducts.filter((item) => item.name !== 'main')
      subproducts = subproducts.map((item) => ({
        ...item,
        selected: item.id === this.selectedPurchase.id
      }))
      return subproducts
    },
    available () {
      let nextValue = Number(this.quantity)
      const items = this.$_.concat(this.purchases, this.setPurchases)
      const selected = items.find((item) => item.id === this.selectedPurchase.id)
      if (selected) {
        nextValue += selected.quantity
      }
      return this.selectedPurchase.available >= nextValue
    },
    slotProps () {
      return {
        item: {
          ...this.product,
          isCollection: this.isCollection,
          subproducts: this.subproducts
        },
        loading: this.loading,
        quantity: this.quantity,
        selectedOption: this.selectedPurchase,
        isOptionSelected: this.isSkuSelected,
        isImageSelected: this.isImageSelected,
        isAvailable: this.available,
        selectImage: this.selectImage,
        selectOption: this.selectSku,
        selectQuantity: this.selectQuantity,
        addCart: this.addCart
      }
    }
  },
  methods: {
    ...mapActions({
      addToCart: 'cart/addToCart'
    }),
    selectImage (index) {
      this.selectedImage = index
    },
    isImageSelected (index) {
      return this.selectedImage === index
    },
    isSkuSelected (item) {
      return this.selectedPurchase.id === item.id
    },
    selectSku (realItem) {
      this.selectedPurchase = this.$_.cloneDeep(realItem)
    },
    selectQuantity (value) {
      this.quantity = value
    },
    addCart () {
      let name = this.product.name
      if (!this.isCollection) {
        if (this.selectedPurchase.name !== 'main') {
          name += ` (${this.selectedPurchase.name})`
        }
      }
      this.addToCart({
        id: this.selectedPurchase.id,
        price: this.selectedPurchase.price,
        available: this.selectedPurchase.available,
        name,
        pictureUrl: this.product.pictureUrl,
        isCollection: this.isCollection,
        quantity: Number(this.quantity)
      })
      this.$shipnity.notification.success('เพิ่มสินค้าลงตะกร้า')
    },
    shopNow () {
      this.addCart()
      this.$router.push({ name: 'SalePageCart' })
    }
  },
  template: `
    <div class="snt-product-detail">
      <slot v-bind="slotProps">
        <div
          v-if="loading"
          class="text-center">
          <v-progress-circular
            :size="14"
            :width="1"
            color="secondary"
            indeterminate
          />
        </div>
        <snt-container
          v-else
          class="snt-product-detail__container">
          <snt-row class="snt-product-briefing">
            <snt-col
              cols="12"
              md="5"
              sm="6">
              <slot
                v-bind="slotProps"
                name="images">
                <snt-carousel
                  :value="selectedImage"
                  :items="images"
                  class="snt-product-briefing__carousel"
                  height="400"
                  hide-delimiter-background
                  show-arrows-on-hover
                  contain
                  @change="selectImage($event)" />
                <snt-row
                  class="snt-product-briefing__images"
                  dense>
                  <snt-col
                    v-for="(item, i) in images"
                    :key="'snt-product-briefing__image-'+i"
                    cols="3"
                    md="3"
                    sm="4">
                    <snt-image
                      :src="item.src"
                      :class="{ 'snt-product-briefing__image--active': selectedImage === i }"
                      class="snt-product-briefing__image"
                      aspect-ratio="1"
                      contain
                      @mouseover="selectImage(i)" />
                  </snt-col>
                </snt-row>
              </slot>
            </snt-col>
            <snt-col
              cols="12"
              md="7"
              sm="6">
              <slot
                v-bind="slotProps"
                name="item">
                <div class="snt-product-briefing__name">
                  {{ product.name }}
                </div>
                <div class="snt-product-briefing__price">
                  {{ product.price | toLocaleString }} บาท
                </div>
                <template v-if="!isCollection && subproducts.length">
                  <div class="snt-product-briefing__label">
                    สินค้าย่อย
                  </div>
                  <div class="snt-product-briefing__sku">
                    <template v-for="(sub, i) in subproducts">
                      <snt-button
                        :key="'product-sku-'+i"
                        :ripple="false"
                        :class="{ 'snt-product-sku--active': sub.selected }"
                        class="snt-product-sku"
                        depressed
                        @click="selectSku(sub)">
                        <span>{{ sub.name }}</span>
                        <snt-icon
                          v-if="sub.selected"
                          icon="mdi-check"
                          right
                          x-small />
                      </snt-button>
                    </template>
                  </div>
                </template>
                <div class="snt-product-briefing__label">
                  จำนวน
                </div>
                <div class="snt-product-briefing__quantity">
                  <snt-number-field
                    :value="quantity"
                    :min="1"
                    :max="selectedPurchase.available"
                    controls
                    center
                    @input="selectQuantity($event)" />
                  <div class="snt-product-quantity__available">
                    <div v-if="selectedPurchase.available > 0">
                      เหลือ {{ selectedPurchase.available | toLocaleString }} ชิ้น
                      <div
                        v-if="!available"
                        class="snt-product-quantity__error">
                        สินค้าถึงจำนวนคงเหลือแล้ว
                      </div>
                    </div>
                    <div
                      v-else
                      class="snt-product-quantity__error">
                      สินค้าหมด
                    </div>
                  </div>
                </div>
                <div class="snt-product-briefing__action">
                  <snt-button
                    :disabled="!available"
                    color="primary"
                    x-large
                    outlined
                    depressed
                    @click="addCart()">
                    ใส่ลงตะกร้า
                  </snt-button>
                  <snt-button
                    :disabled="!available"
                    color="primary"
                    x-large
                    depressed
                    @click="shopNow()">
                    ซื้อสินค้าทันที
                  </snt-button>
                </div>
              </slot>
            </snt-col>
          </snt-row>
          <snt-row class="snt-product-description">
            <snt-col cols="12">
              <slot
                v-bind="slotProps"
                name="description">
                <div class="snt-product-description__heading">
                  รายละเอียดสินค้า
                </div>
                <snt-text-editor :html="product.descriptionLong" />
              </slot>
            </snt-col>
          </snt-row>
        </snt-container>
      </slot>
    </div>
  `
})
