import _ from 'lodash'
import helpers from '@/helpers'
import { CART_NAME } from '@/store/utils/localStorageKeys'

export default {
  getCartPayCycle: state => state.cartPayCycle || '',
  getCartHasRental: state => state.has_rental,
  getCartHasHa: state => state.has_ha,
  getCartNeedAddressSelection: state => state.need_address_selection,
  getCartNeedSizeSelection: state => state.need_size_selection,
  getCartTotal: state => state.totalQuantity,
  getCartPrice: state => state.total_price,
  getCartAllTotalPrices: state => state.allTotalPrices,
  getCartCv: state => state.totalCv,
  getCheckout: state => state.checkout,
  getCheckoutErrors: state => {
    let errorObj = helpers.getValue(state.checkout, 'errors', {})
    return Object.values(errorObj)
  },
  getCartCwName: state => helpers.getValue(state, 'checkout.current_cw.cw_name', ''),
  getIsPartialCart: state => helpers.getValue(state, 'checkout.isPartialCart'),
  getCartTotalAdminFee: state => state.total_admin_fee,
  getCartTotalAdminFeeFormatted: state => state.total_admin_fee_formatted,
  getCartTotalDeliveryFee: state => state.total_delivery_fee,
  getCartTotalDeliveryFeeFormatted: state => state.total_delivery_fee_formatted,
  getCartTotalNpm: state => state.total_npm,
  getCartTotalNpmFormatted: state => state.total_npm_formatted,
  getCartTotalPrice: state => state.total_price,
  getCartTotalPriceFormatted: state => state.total_price_formatted,
  getCartTotalPriceRoundingAdjustment: state => state.total_price_rounding_adjustment,
  getCartTotalPriceRoundingAdjustmentFormatted: state => state.total_price_rounding_adjustment_formatted,
  getCartTotalTax: state => state.total_tax,
  getCartTotalTaxFormatted: state => state.total_tax_formatted,
  getIsOrderingForDownLine: state => state.isOrderingForDownLine,
  getOrderingFor: state => state.orderingFor,
  getCartUserNeedActivation: state => helpers.getValue(state, 'checkout.member_need_activation'),
  getCartPromotions: state => state.promotions,
  getCartInstDetails: state => state.selectedDummiesInstDetails,
  getCartHasEpp: state => state.has_epp,
  getCartProductOrKitting: state => (productId, kittingId) => {
    let product = state.products.find(function(item) {
      if (
        (item.product_id !== '' && item.product_id !== null && item.product_id === productId) ||
        (item.kitting_id !== '' && item.kitting_id !== null && item.kitting_id === kittingId)
      ) {
        return true
      }
    })
    return product
  },
  getCartProductRentalPlan: (state, getters) => item => {
    let rentalPlan = null
    let product = getters.getCartProductOrKitting(item.product_id, item.kitting_id)
    if (typeof product.rental_plan !== 'undefined' && product.rental_plan !== null) {
      rentalPlan = product.rental_plan
    }
    if (Array.isArray(rentalPlan)) {
      if (rentalPlan.length == 0) {
        rentalPlan = null
      }
    }
    return rentalPlan
  },
  getRentalInstDetails: state => {
    let rentalInstDetails = state.selectedDummiesInstDetails.inst_details
    let data = null

    if (rentalInstDetails.length > 0) {
      data = {
        installation_date: rentalInstDetails[0].installation_date,
        installation_time_section_id: rentalInstDetails[0].installation_time,
      }
    }
    return data
  },

  getCartProductInstDetails: (state, getters) => item => {
    let instDetail = null
    let dummiesInstDetails = state.selectedDummiesInstDetails.inst_details

    for (let i = 0; i < dummiesInstDetails.length; i++) {
      if (
        dummiesInstDetails[i].product_id !== null &&
        dummiesInstDetails[i].product_id !== 'undefined' &&
        dummiesInstDetails[i].product_id == item.product_id
      ) {
        instDetail = dummiesInstDetails[i]
      }
      if (
        dummiesInstDetails[i].kitting_id !== null &&
        dummiesInstDetails[i].kitting_id !== 'undefined' &&
        dummiesInstDetails[i].kitting_id == item.kitting_id
      ) {
        instDetail = dummiesInstDetails[i]
      }
    }

    return instDetail
  },
  getHasInstDetails: (state, getters) => {
    let hasInstDetails = false
    let cartInsItems = getters.getCartInstItems

    if (cartInsItems.length > 0) {
      hasInstDetails = true
    }
    return hasInstDetails
  },
  getCartIsRentalSaleOrder: (state, getters) => {
    let isRentalOrder = false
    let cartItems = getters.getCartItems
    for (let i = 0; i < cartItems.length; i++) {
      let item = cartItems[i]
      if (getters.getCartProductRentalPlan(item) !== null) {
        isRentalOrder = true
      }
    }
    return isRentalOrder
  },
  getCartProductSaleTypeId: (state, getters) => (productId, kittingId) => {
    let product = getters.getCartProductOrKitting(productId, kittingId)
    let saleTypeId = null
    if (typeof product.sales_types !== 'undefined') {
      saleTypeId = product.sales_types[0].id
    }

    return saleTypeId
  },

  getCartProductQuantity: (state, getters) => (productId, kittingId) => {
    let product = getters.getCartProductOrKitting(productId, kittingId)
    return product ? product.quantity : 0
  },
  getCartProductEligibleAsBaUpgrade: (state, getters) => (productId, kittingId) => {
    let product = getters.getCartProductOrKitting(productId, kittingId)
    if (product) {
      let baId = getters.getBaSalesTypeId
      if (typeof product.eligible_sales_type !== 'undefined' && product.eligible_sales_type.id === baId) {
        return true
      } else {
        return false
      }
    } else {
      return false
    }
  },
  getCartProductEligibleSalesType: (state, getters) => (productId, kittingId) => {
    let product = getters.getCartProductOrKitting(productId, kittingId)
    if (product && typeof product.eligible_sales_type !== 'undefined') {
      return product.eligible_sales_type
    } else {
      return false
    }
  },
  getProductSaleType: (state, getters) => (slaesTypeId, salesTypes) => {
    let key = ''
    for (var i = 0; i < salesTypes.length; i++) {
      var data = salesTypes[i]
      if (data.id === slaesTypeId) {
        key = data.title
      }
    }
    return key
  },
  getCartProductSalesTypes: (state, getters) => (productId, kittingId) => {
    let product = getters.getCartProductOrKitting(productId, kittingId)
    if (product) {
      return product.sales_types
    } else {
      return []
    }
  },
  getCartSalesTypes: (state, getters) => {
    let cartItems = getters.getCartItems
    let cartSalesTypes = []
    for (let i = 0; i < cartItems.length; i++) {
      let productId = cartItems[i].product_id
      let kittingId = cartItems[i].kitting_id
      let product = getters.getCartProductOrKitting(productId, kittingId)
      if (product) {
        let salesTypes = product.sales_types
        let index = -1
        if (salesTypes !== undefined && salesTypes.length) {
          for (let j = 0; j < salesTypes.length; j++) {
            index = cartSalesTypes.findIndex(x => x.id == salesTypes[j].id)
            if (index === -1) {
              cartSalesTypes.push(salesTypes[j])
            }
          }
        }
      }
    }
    return cartSalesTypes
  },
  /**
   * Get cart sale type from first item in cart
   * @param state
   * @param getters
   * @returns {boolean}
   */
  getCartSaleType: (state, getters) => {
    let cartItems = getters.getCartItems
    let salesType = false
    if (cartItems.length > 0) {
      let productId = cartItems[0].product_id
      let kittingId = cartItems[0].kitting_id
      let product = getters.getCartProductOrKitting(productId, kittingId)
      salesType = product.eligible_sales_type
    }
    return salesType
  },
  getCartHasRentalProducts: (state, getters) => {
    let cartProductsSalesTypes = []
    let cartItems = getters.getCartItems
    let hasRentalProducts = false
    for (let i = 0; i < cartItems.length; i++) {
      let item = cartItems[i]
      if (getters.getCartProductRentalPlan(item) !== null) {
        hasRentalProducts = true
      }
    }

    return hasRentalProducts
  },
  getCartHasUpgrade: state => {
    if (
      typeof state.totalCv['sales_types'] !== 'undefined' &&
      (typeof state.totalCv['sales_types']['ba-upgrade'] !== 'undefined' ||
        typeof state.totalCv['sales_types']['member-upgrade'] !== 'undefined')
    ) {
      return true
    } else {
      return false
    }
  },
  getCartHasAmpUpgrade: state => {
    if (
      typeof state.totalCv['sales_types'] !== 'undefined' &&
      (typeof state.totalCv['sales_types']['auto-maintenance'] !== 'undefined' ||
        typeof state.totalCv['sales_types']['repurchase'] !== 'undefined')
    ) {
      return true
    } else {
      return false
    }
  },
  getCartItems: (state, getters) => {
    return _.chain(state.products)
      .map(function(item) {
        item.free = getters.isProductFree(item)
        item.memberKit = getters.isMemberKit(item)
        item.starterKit = (item.filters || []).includes('starter_kit')
        item.size = false
        if (item.product_id !== null && item.is_dummy_code === 1) {
          item.size = true
        } else if (item.kitting_id !== null) {
          item.size = true
        }
        let subItems = []
        let vouchers = helpers
          .getValue(state, 'selectedDummies.evoucher', [])
          .filter(p => p.product_id === item.product_id && p.kitting_id === item.kitting_id)
        let sizes = helpers
          .getValue(state, 'selectedDummies.sizes', [])
          .filter(p => p.product_id === item.product_id && p.kitting_id === item.kitting_id)
        if (sizes.length > 0 || vouchers.length > 0) {
          vouchers.forEach(voucher => {
            if (voucher.quantity > 0) {
              subItems.push({
                name: item.name,
                sku: 'eVoucher',
                quantity: voucher.quantity,
              })
            }
          })
          sizes.forEach(size => {
            let details = getters
              .getProductOrKittingDummies(size.product_id, size.kitting_id)
              .find(p => p.product_id === size.product_id && p.kitting_id === size.kitting_id)
            if (details !== undefined) {
              if (size.data !== undefined && size.data.length > 0) {
                size.data.forEach(sz => {
                  if (sz.quantity > 0) {
                    let dummy = details.dummy_products.find(dmy => dmy.id === sz.product_id)
                    subItems.push({
                      name: dummy.name,
                      sku: dummy.sku,
                      quantity: sz.quantity,
                    })
                  }
                })
              } else {
                subItems.push({
                  name: details.name,
                  sku: details.sku,
                  quantity: size.quantity,
                })
              }
            }
          })
          if (subItems.length > 0) {
            item.subItems = subItems
          }
        }
        return item
      })
      .sortBy(['free'])
      .value()
  },
  getCartDisplayItems: (state, getters) => {
    return _.chain(getters.getCartItems)
      .filter(item => item.free === false && item.memberKit === false)
      .sortBy(['free'])
      .value()
  },
  getCartDisplayItemsWithMemberKit: (state, getters) => {
    return _.chain(getters.getCartItems)
      .filter(item => item.free === false)
      .sortBy(['memberKit'])
      .reverse()
      .value()
  },
  getCartHasStarterKit: (state, getters) => {
    return getters.getCartItems.filter(item => item.starterKit).length > 0
  },
  getCartHasDummy: state => {
    let hasDummy = false
    state.products.forEach(item => {
      if (item.is_dummy_code !== null && item.dummy !== '') {
        hasDummy = true
      }
      if (item.kitting_id !== '' && item.kitting_id !== null) {
        if (item.products_of_kitting !== undefined) {
          Array.prototype.forEach.call(item.products_of_kitting, kitting => {
            if (kitting.is_dummy_code !== null && kitting.is_dummy_code !== '') {
              hasDummy = true
            }
          })
        }
      }
    })
    return hasDummy
  },
  getCartInstItems: (state, getters, rootState, rootGetters) => {
    return state.products.filter(item => {
      let instDetails = state.selectedDummiesInstDetails
      item.installation_date = ''
      item.installation_time = ''
      let productAddtionalRequirements = []
      productAddtionalRequirements = rootGetters.getEnrolmentMasterDataIdByKey('product_additional_requirements')
      if (item.additional_requirements.length > 0 && item.sales_types !== undefined) {
        let hasAdditionalRequirement = false
        if (productAddtionalRequirements !== undefined) {
          for (let i = 0; i < productAddtionalRequirements.length; i++) {
            var found = item.additional_requirements.includes(productAddtionalRequirements[i].id)
            if (found) {
              hasAdditionalRequirement = true
              for (let i = 0; i < instDetails.inst_details.length; i++) {
                let d = instDetails.inst_details[i]
                if (d.product_id !== null && d.product_id === item.product_id) {
                  item.installation_date = d.installation_date
                  item.installation_time = d.installation_time
                }
                if (d.kitting_id !== null && d.kitting_id === item.kitting_id) {
                  item.installation_date = d.installation_date
                  item.installation_time = d.installation_time
                }
              }
            }
          }
        }
        return hasAdditionalRequirement
      }
      if (item.kitting_id !== '' && item.kitting_id !== null && typeof item.products !== 'undefined') {
        let hasAdditionalRequirementKitting = false
        if (item.products !== undefined) {
          Array.prototype.forEach.call(item.products, kittingProduct => {
            if (productAddtionalRequirements !== undefined) {
              for (let i = 0; i < productAddtionalRequirements.length; i++) {
                var found = kittingProduct.additional_requirements.includes(productAddtionalRequirements[i].id)
                if (found) {
                  hasAdditionalRequirementKitting = true
                  for (let i = 0; i < instDetails.inst_details.length; i++) {
                    let d = instDetails.inst_details[i]
                    if (d.product_id !== null && d.product_id === item.product_id) {
                      item.installation_date = d.installation_date
                      item.installation_time = d.installation_time
                    }
                    if (d.kitting_id !== null && d.kitting_id === item.kitting_id) {
                      item.installation_date = d.installation_date
                      item.installation_time = d.installation_time
                    }
                  }
                }
              }
            }
          })
        }
        return hasAdditionalRequirementKitting
      }
    })
  },
  getCartSizeSelectionRequired: (state, getters) => {
    let items = getters.getCartDummies
    let isRequired = false
    if (items.length > 0) {
      isRequired = true
    }
    return isRequired
  },
  getCartInstSelectionRequired: (state, getters) => {
    let items = getters.getCartInstItems
    let isRequired = false
    if (items.length > 0) {
      isRequired = true
    }
    return isRequired
  },
  getCartDummies: state => {
    return state.products.filter(item => {
      if (item.is_dummy_code !== null && item.is_dummy_code === 1) {
        return true
      }
      if (item.kitting_id !== '' && item.kitting_id !== null && typeof item.products !== 'undefined') {
        let hasKittingDummy = false
        if (item.products !== undefined) {
          Array.prototype.forEach.call(item.products, kittingProduct => {
            if (kittingProduct.is_dummy_code !== null && kittingProduct.is_dummy_code === 1) {
              hasKittingDummy = true
            }
          })
        }
        return hasKittingDummy
      }
    })
  },
  getCartSelectedInstDetails: state => {
    let dummies = _.cloneDeep(state.selectedDummiesInstDetails)
    return dummies
  },
  getCartIsAllDummiesSelected: state => {
    return state.selectedDummies
  },
  getCartIsAllDummiesSelectedForSales: state => {
    let dummies = _.cloneDeep(state.selectedDummies)
    dummies['sizes'] = _.chain(dummies['sizes'])
      .filter(item => {
        return item.is_dummy === true
      })
      .map(item => {
        if (item.is_foc) {
          item.data = _.map(item.data, data => {
            data.foc_qty = data.quantity
            data.quantity = 0
            return data
          })
        } else {
          item.data = _.map(item.data, data => {
            data.foc_qty = 0
            return data
          })
        }
        delete item.quantity
        delete item.is_dummy
        delete item.is_foc
        return item
      })
      .value()
    dummies['evoucher'] = _.chain(dummies['evoucher'])
      .map(item => {
        item.data = []
        return item
      })
      .filter(item => item.quantity !== 0)
      .value()
    return dummies
  },
  getShowProductDetailModal: state => {
    return state.showProductDetailModal
  },
  getCartHasSubscription: state => {
    return state.products.find(product => {
      return product.filters.includes('member_subscription_item')
    })
  },
  getCartName: () => {
    return localStorage.getItem(CART_NAME) || 'default'
  },
  getCartPreservationStatus: state => state.preserverCartItem,
  getCartCampaignDetails: state => state.cartCampaignDetails,
}
