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

export default Vue.extend({
  name: 'SntProducts',
  apollo: {
    products: () => ({
      query () {
        return this.subdomain ? GET_SALEPAGE_PRODUCTS : GET_PRODUCTS
      },
      variables () {
        return this.subdomain
          ? {
              domain: this.subdomain,
              page: 1,
              perPage: Number(this.limit),
              search: '',
              items: this.productIds.map((item) => item.id),
              orderBy: 'id_DESC'
            }
          : {
              page: 1,
              perPage: Number(this.limit),
              stockId: this.stockId,
              id: this.productIds.map((item) => item.id),
              orderBy: 'id_DESC'
            }
      },
      update (data) {
        return this.subdomain ? data.salePage.productList.nodes : data.products.nodes
      }
    }),
    productSets: () => ({
      skip () {
        return !this.items.length
      },
      query () {
        return this.subdomain ? GET_SALEPAGE_SETPRODUCTS : GET_PRODUCTSETS
      },
      variables () {
        const items = this.productSetIds.map((item) => item.id)
        const variables = {
          page: 1,
          perPage: Number(this.limit),
          orderBy: 'price_ASC'
        }
        return this.subdomain
          ? {
              ...variables,
              domain: this.subdomain,
              search: '',
              items
            }
          : {
              ...variables,
              stockId: this.stockId,
              id: items
            }
      },
      update (data) {
        return this.subdomain ? data.salePage.productSetList.nodes : data.productSets.nodes
      }
    })
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    limit: {
      type: [String, Number],
      default: 0
    },
    itemProps: {
      type: Object,
      default: () => ({
        showSku: true,
        showPrice: true,
        showDescription: false,
        showStock: true,
        showCart: false
      })
    },
    items: {
      type: Array,
      default: () => ([])
    },
    cols: {
      type: [Boolean, String, Number],
      default: undefined
    },
    lg: {
      type: [Boolean, String, Number],
      default: undefined
    },
    md: {
      type: [Boolean, String, Number],
      default: undefined
    },
    sm: {
      type: [Boolean, String, Number],
      default: undefined
    },
    xl: {
      type: [Boolean, String, Number],
      default: undefined
    }
  },
  data () {
    return {
      products: [],
      productSets: []
      // shelf: []
    }
  },
  computed: {
    ...mapGetters({
      stockId: 'salePage/stockId',
      subdomain: 'salePage/subdomain'
    }),
    loading () {
      return this.$apollo.queries.products.loading || this.$apollo.queries.productSets.loading
    },
    productIds () {
      return this.items.filter((item) => !item.isProductSet)
    },
    productSetIds () {
      return this.items.filter((item) => item.isProductSet)
    },
    allProducts () {
      return this.items.length
        ? this.items.map((item) => {
          if (item.isProductSet) {
            const product = this.$_.find(this.productSets, ['id', item.id])
            return this.$_.defaultsDeep(product, {
              ...item,
              routerLink: {
                name: 'SalePageCollectionDetail',
                params: {
                  productId: item.id
                }
              },
              isCollection: true,
              productBrand: null,
              productCategory: null,
              images: [],
              subproducts: []
            })
          }
          const product = this.$_.find(this.products, ['id', item.id])
          return this.$_.defaultsDeep(product, {
            ...item,
            routerLink: {
              name: 'SalePageProductDetail',
              params: {
                productId: item.id
              }
            },
            isCollection: false,
            images: [],
            subproducts: []
          })
        })
        : this.products.map((item) => this.$_.defaultsDeep(item, {
          routerLink: {
            name: 'SalePageProductDetail',
            params: {
              productId: item.id
            }
          },
          isCollection: false,
          productBrand: null,
          productCategory: null,
          images: [],
          subproducts: []
        }))
    },
    slotProps () {
      return {
        loading: this.loading,
        items: this.allProducts,
        title: this.title,
        limit: this.limit,
        itemProps: this.itemProps,
        addMainToCart: this.addMainToCart
        // setQuantity: this.setQuantity,
        // getQuantity: this.getQuantity
      }
    }
  },
  methods: {
    ...mapActions({
      addToCart: 'cart/addToCart'
    }),
    getMain (item) {
      let subproducts = item?.subproducts || []
      subproducts = subproducts.filter()
      subproducts = subproducts.map((sub) => ({
        ...sub,
        selected: sub.id === this.selectedPurchase.id
      }))
      return subproducts
    },
    addMainToCart (item) {
      let name = item.name
      const subproducts = item?.subproducts || []
      const subproduct = this.$_.head(subproducts)
      if (!this.isCollection) {
        if (subproduct.name !== 'main') {
          name += ` (${subproduct.name})`
        }
      }
      this.addToCart({
        id: subproduct.id,
        price: subproduct.price,
        available: subproduct.available,
        name,
        pictureUrl: item.pictureUrl,
        isCollection: this.isCollection,
        quantity: 1
      })
      this.$shipnity.notification.success('เพิ่มสินค้าลงตะกร้า')
    }
    // setQuantity (item, quantity) {
    //   this.shelf = this.$_.filter(this.shelf, (shelf) => shelf.id !== item.id)
    //   this.shelf.push({
    //     id: item.id,
    //     quantity: Math.abs(Number(quantity))
    //   })
    // },
    // getQuantity (item) {
    //   return this.$_.find(this.shelf, ['id', item.id])?.quantity || 1
    // }
  },
  template: `
    <div class="snt-products">
      <slot v-bind="slotProps">
        <snt-container
          class="snt-products__container"
          fluid>
          <template v-if="!loading">
            <div class="snt-products__title">
              {{ title }}
            </div>
            <snt-row class="snt-products__row">
              <snt-col
                v-for="(item, i) in allProducts"
                :key="'item-product-'+i"
                :cols="cols"
                :lg="lg"
                :md="md"
                :sm="sm"
                :xl="xl">
                <snt-product
                  :id="item.id"
                  :picture-url="item.pictureUrl || 'https://via.placeholder.com/400x400?text=Image'"
                  :name="item.name"
                  :sub-products="item.subproducts"
                  :description="item.descriptionShort"
                  :price="item.price"
                  :stock="item.available"
                  :is-collection="item.isCollection"
                  :show-sku="itemProps.showSku"
                  :show-description="itemProps.showDescription"
                  :show-price="itemProps.showPrice"
                  :show-stock="itemProps.showStock"
                  :show-cart="itemProps.showCart">
                  <slot
                    name="item"
                    :item="item"
                    :index="i"
                    :itemProps="itemProps" />
                </snt-product>
              </snt-col>
            </snt-row>
          </template>
        </snt-container>
      </slot>
    </div>
  `
})
