import helpers from '@/helpers'
import constants from '@/config/const'
import _ from 'lodash'
import AppSettings from '@/config/app-settings'

export default {
  getSalesPaymentModes: state => state.paymentModes,
  getCurrentSaleId: state => state.currentSaleId,
  getCurrentPayment: state => state.currentPayment,
  getCurrentPaymentId: state => state.currentPaymentId,
  getEvouchers: state => state.eVouchers,
  getSaleEvouchers: state => state.saleEvouchers,
  getRedemptionReceipt: state => state.redemptionReceipt,
  getSubscriptionSale: state => state.subscriptionSale,
  getSubscriptionProductsAndKitting: state => {
    return _.union(state.subscriptionSale.products, state.subscriptionSale.kittings)
  },
  getSubscriptionTax: state => {
    return helpers.getCurrencyValue(
      parseFloat(state.subscriptionSale.order_fees.admin_fee) -
        parseFloat(state.subscriptionSale.order_fees.admin_fee_tax) +
        (parseFloat(state.subscriptionSale.order_fees.delivery_fee) -
          parseFloat(state.subscriptionSale.order_fees.delivery_fee_tax)) +
        (parseFloat(state.subscriptionSale.order_fees.other_fee) -
          parseFloat(state.subscriptionSale.order_fees.other_fee_tax))
    )
  },
  getSalesList: state => state.salesList,
  getEkSmartSalesList: state => state.ekSmartSalesList,
  getOnHoldPaymentMode: state => state.onHoldPaymentMode,
  getShowLoadingPopup: state => state.showLoadingPopup,
  getCurrentPaymentIsQr: state => state.currentPaymentIsQr,
  getSalesListData: state => {
    return state.salesListData
  },
  getSalesDetails: state => {
    return state.sale
  },
  getSalesListDataTotalRows: state => {
    return state.salesListDataTotalRows
  },
  getSalesListTotalRows: state => {
    return state.salesListTotalRows
  },
  getEkSmartSalesListTotalRows: state => {
    return state.ekSmartSalesListTotalRows
  },
  getCreditNotePdf: state => {
    return state.creditNotePdf
  },
  getSalesPaymentData: (state, getters, rootState, rootGetters) => {
    let orderData = state.sale
    let payments = []
    let paymentsData = helpers.getValue(orderData, 'selected.payments')
    let masterIds = rootGetters.getMasterDataIdsByKeysTitlesMapped(constants.masterKey.PAYMENT_MODE, {
      eppMotoId: constants.masterData.EPP_MOTO,
      eppOnlineId: constants.masterData.EPP_ONLINE,
      eppTerminalId: constants.masterData.EPP_TERMINAL,
      aeonId: constants.masterData.AEON,
    })
    let eppMotoId = masterIds.eppMotoId
    let eppOnlineId = masterIds.eppOnlineId
    let eppTerminalId = masterIds.eppTerminalId
    let aeonId = masterIds.aeonId
    if (paymentsData) {
      if (paymentsData['paid'].length > 0) {
        payments = paymentsData['paid'].filter(x => x.status === 1 || (x.is_qr === 1 && x.status === 2)) // 0 = Failed, 1 = Success, 2 = Pending
        payments.forEach(payment => {
          payment['bank'] = ''
          payment['tenure'] = ''
          payment['approvecode_agreementno'] = ''
          if (payment.status === 1) {
            payment['is_qr'] = 0
          }
          if (payment.payment_mode_provider.master_data_id === aeonId) {
            payment.payment_detail = JSON.parse(payment.payment_detail)
            payment['approvecode_agreementno'] = payment.payment_detail.payment_response.agreement_no
          }
          if (
            payment.payment_mode_provider.master_data_id === eppMotoId ||
            payment.payment_mode_provider.master_data_id === eppOnlineId ||
            payment.payment_mode_provider.master_data_id === eppTerminalId
          ) {
            payment.payment_detail = JSON.parse(payment.payment_detail)
            payment['bank'] = payment.payment_detail.payment_response.card_type
            payment['tenure'] = payment.payment_detail.payment_response.tenure
            payment['approvecode_agreementno'] = payment.payment_detail.payment_response.approval_code
          }
        })
      }
    }
    return payments
  },
  populateProductItems: (state, rootGetters) => {
    let orderData = state.sale
    let products = []
    let total = 0
    let promoIds = rootGetters.getMasterDataIdsByKeysTitlesMapped(constants.masterKey.PROMOTION_FREE_ITEM_PROMO_TYPES, {
      focId: constants.masterData.PROMO_TYPE_FOC,
      pwpfId: constants.masterData.PROMO_TYPE_PWPF,
      pwpnId: constants.masterData.PROMO_TYPE_PWPN,
    })
    if (typeof orderData.products !== 'undefined') {
      orderData.products.forEach(item => {
        item['cv'] = item.total_bv || 0
        item['amp'] = item.quantity * parseFloat(item.virtual_invoice_cv)
        item['sv'] = item.total_sv
        item['cbp'] = item.total_cbp_point
        item['price'] = item.base_price.total
        total += parseFloat(item.price)
        products.push(item)
      })
    }
    if (typeof orderData.kittings !== 'undefined') {
      orderData.kittings.forEach(kitting => {
        products.push({
          name: kitting.name,
          sku: kitting.code,
          quantity: kitting.quantity,
          cv: kitting.total_bv || 0,
          amp: kitting.quantity * parseFloat(kitting.virtual_invoice_cv),
          sv: kitting.total_sv,
          cbp: kitting.total_cbp_point,
          price: kitting.quantity * parseFloat(kitting.kitting_price.gmp_price_tax),
        })
        total += kitting.quantity * parseFloat(kitting.kitting_price.gmp_price_tax)
      })
    }
    if (
      orderData.promotion !== undefined &&
      orderData.selected.promotions !== undefined &&
      orderData.selected.promotions.length > 0
    ) {
      orderData.promotion.forEach(item => {
        item['sku'] =
          (item.promo_type_id === promoIds.pwpfId && constants.masterData.PROMO_TYPE_PWPF) ||
          (item.promo_type_id === promoIds.pwpnId && constants.masterData.PROMO_TYPE_PWPN) ||
          constants.masterData.PROMO_TYPE_FOC
        item['cv'] = (AppSettings.evo.enable && '0.00') || 0
        item['amp'] = 0
        item['sv'] = 0
        item['cbp'] = '0.0000'
        item['quantity'] = 1
        item['price'] = item.pwp_value
        total += parseFloat(item.price)
        products.push(item)
      })
    }
    return { products: products, total: total }
  },
  getEsacVouchers: state => state.sale.esac_vouchers_list || [],
  getPaymentUserId: (state, getters) => {
    if (getters.getAppStatus('eshop') === true) {
      if (getters['eshop/getIsOrderingForDownLine'] === true) {
        return getters['eshop/getOrderingFor'].details.user_id
      } else {
        return getters.getMemberDetails.user_id
      }
    } else if (getters.getAppStatus('enrolment') === true) {
      return helpers.getValue(getters['enrolment/getSponsorDetails'], 'user_id', null)
    }
    return null
  },
  getWillPaymentPend: state => saleId => {
    return state.saleInPreorder === saleId
  },
  getEppPaymentCodes: state => state.eppPaymentCodes,
  getPaymentQrCode: state => state.qrCodeData,
  getCurrentPaymentStatus: state => state.paymentStatus,
  isOrderFailed: (state, getters) => {
    return getters.getCurrentSaleId !== 0 && getters.getCurrentSaleId !== '' && getters.getCurrentPaymentStatus === 0
  },
  isOrderComplete: (state, getters) => {
    return getters.getCurrentSaleId !== 0 && getters.getCurrentSaleId !== ''
  },
  isOrderCompleteWithPayment: (state, getters) => {
    return (
      getters.getCurrentSaleId !== 0 &&
      getters.getCurrentSaleId !== '' &&
      (getters.getCurrentPaymentStatus === 1 ||
        helpers.getValue(getters, 'getOnHoldPaymentMode.is_paylater') ||
        helpers.getValue(getters, 'getOnHoldPaymentMode.is_cash_on_delivery'))
    )
  },
}
