import { post, get } from '../../utils/api'
import Vue from 'vue'
import * as U from '../../utils/apiUrls'
import * as T from '../../utils/types'

import router from '@/router'
import { getValue } from '@/helpers/variable-handling'

// event handler when user click Back button in esac header
export const clickEsacHeaderBack = ({ commit, getters, dispatch }, payload) => {
  let currentStep = getters.getEsacRouterData.currentStep
  if (currentStep === 'SelectProduct') {
    dispatch('clickEsacProductSelectionBack')
  } else {
    dispatch('redirectToDashboardScreen')
  }
  let pageNumber = getValue(getters.getPagination('esacvoucherlist'), 'page', 1)
  router.push({ name: 'EsacVoucherListHomePaginated', params: { page: pageNumber } })
}

// event handler when user select/deselect voucher in voucher listing or product selection screen
export const toggleEsacVoucherSelection = ({ commit, getters, dispatch }, payload) => {
  let voucherData = JSON.parse(JSON.stringify(getters.getEsacVoucherData))
  let voucher = voucherData.find(item => item.id === payload.id)
  voucher.selected = !voucher.selected
  commit(T.SET_ESAC_VOUCHER_DATA, voucherData)
  if (payload.sender === 'ProductSelection') {
    if (getters.getEsacSelectedVoucherCount > 0) {
      dispatch('loadEsacProductList', { sender: payload.sender })
    } else {
      // no voucher selected, hide all products
      let productData = JSON.parse(JSON.stringify(getters.getEsacProductData))
      productData.forEach(item => {
        item.selected = false
        item.visible = false
        item.search = false
        item.disabled = true
      })
      commit(T.SET_ESAC_PRODUCT_DATA, productData)
    }
  }
}

// event handler when user click Search Downline button in voucher listing screen
export const clickEsacVoucherSelectionSearchDownline = ({ commit, getters }, payload) => {
  let voucherData = JSON.parse(JSON.stringify(getters.getEsacVoucherData))
  voucherData.forEach(item => {
    let iboId = ''
    let iboName = ''
    if (item.ibo_id !== null) {
      iboId = item.ibo_id.toString()
    }
    if (item.ibo_name !== null) {
      iboName = item.ibo_name.toLowerCase()
    }
    if (iboId.indexOf(payload) >= 0 || iboName.indexOf(payload) >= 0) {
      item.search_visible = true
    } else {
      item.search_visible = false
    }
  })
  commit(T.SET_ESAC_VOUCHER_DATA, voucherData)
}

// event handler when user click Clear Search button in voucher listing screen
export const clickEsacVoucherSelectionClearSearch = ({ commit, getters }, payload) => {
  let voucherData = JSON.parse(JSON.stringify(getters.getEsacVoucherData))
  voucherData.forEach(item => {
    item.search_visible = true
  })
  commit(T.SET_ESAC_VOUCHER_DATA, voucherData)
}

// event handler when user click Redeem button in voucher listing screen
export const clickEsacVoucherSelectionRedeem = ({ commit, getters, dispatch }, payload) => {
  // only selected voucher visible on next screen
  let voucherData = JSON.parse(JSON.stringify(getters.getEsacVoucherData))
  voucherData.forEach(item => {
    item.visible = item.selected
  })
  commit(T.SET_ESAC_VOUCHER_DATA, voucherData)
  dispatch('loadEsacProductList', { sender: 'VoucherSelection' })
  router.push({ name: 'EsacRedemptionForm' })
}

// event handler when user click Back button in product selection screen
export const clickEsacProductSelectionBack = ({ commit, getters }, payload) => {
  // all vouchers should be visible on voucher listing screen
  let voucherData = JSON.parse(JSON.stringify(getters.getEsacVoucherData))
  voucherData.forEach(item => {
    item.visible = true
  })
  commit(T.SET_ESAC_VOUCHER_DATA, voucherData)
  let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
  routerData.currentStep = 'SelectVoucher'
  routerData.preventReloadVoucher = 3
  commit(T.SET_ESAC_ROUTER_DATA, routerData)
  router.push({ name: 'EsacVoucherList' })
}

// event handler when user changing quantity in product selection scrren (click -/+/key in qty)
export const updateEsacPurchaseQuantity = ({ commit, getters }, payload) => {
  // lookup selected item and update its quantity
  let productData = JSON.parse(JSON.stringify(getters.getEsacProductData))
  let product = productData.find(item => item.item_type === payload.item_type && item.item_id === payload.item_id)
  if (payload.update_type === '+') {
    product.quantity += payload.update_value
  } else if (payload.update_type === '-') {
    product.quantity -= payload.update_value
  } else {
    product.quantity = payload.update_value
  }
  if (product.quantity < 0) {
    product.quantity = 0
  }
  product.amount = product.quantity * product.item_price
  commit(T.SET_ESAC_PRODUCT_DATA, productData)
}

// event handler when user changing quantity in product search screen (click -/+/key in qty)
export const updateEsacProductSearchQuantity = ({ commit, getters }, payload) => {
  // lookup selected item and update its quantity
  let productData = JSON.parse(JSON.stringify(getters.getEsacProductData))
  let product = productData.find(item => item.item_type === payload.item_type && item.item_id === payload.item_id)
  if (payload.update_type === '+') {
    product.searchQuantity += payload.update_value
  } else if (payload.update_type === '-') {
    product.searchQuantity -= payload.update_value
  } else {
    product.searchQuantity = payload.update_value
  }
  if (product.searchQuantity < 0) {
    product.searchQuantity = 0
  }
  product.searchAmount = product.searchQuantity * product.item_price
  commit(T.SET_ESAC_PRODUCT_DATA, productData)
}

// event handler when user change paging in product search screen
export const updateEsacProductSearchPaging = ({ commit, getters }, payload) => {
  let productData = JSON.parse(JSON.stringify(getters.getEsacProductData))
  let totalItem = getters.getEsacProductSearchTotalItem
  let pagingSize = getters.getEsacProductSearchPaginationSize
  let minIndex = (payload.currentPage - 1) * pagingSize
  let maxIndex = minIndex + pagingSize - 1
  if (minIndex >= totalItem) {
    minIndex = totalItem - 1
  }
  if (maxIndex >= totalItem) {
    maxIndex = totalItem - 1
  }
  let currentIndex = 0
  productData.forEach(item => {
    item.searchedPaging = false
    if (item.searched === true) {
      if (currentIndex >= minIndex && currentIndex <= maxIndex) {
        item.searchedPaging = true
      }
      currentIndex++
    }
  })
  commit(T.SET_ESAC_PRODUCT_DATA, productData)
}

// event handler when user click Browse Product button in product selection screen
export const clickEsacProductSelectionBrowseProduct = ({ commit, getters }, payload) => {
  // all product search quantity should follow purchase quantity
  let productData = JSON.parse(JSON.stringify(getters.getEsacProductData))
  productData.forEach(item => {
    item.searchQuantity = item.quantity
    item.searchAmount = item.amount
  })
  commit(T.SET_ESAC_PRODUCT_DATA, productData)
  commit(T.SET_ESAC_PRODUCT_SEARCH_VISIBLE, true)
}

// event handler when user click Redeem button in product selection screen
export const clickEsacProductSelectionRedeem = ({ commit, getters, dispatch, rootGetters }, payload) => {
  commit(T.PROCESSING_STARTED, 'settingEsacSalesCreationData')
  dispatch('loadMasterDataKeys', ['sale_types', 'sale_delivery_method']).then(response => {
    let saleTypesRepurchase = getters
      .getMasterDataByKey('sale_types')
      .find(item => item.title.toLowerCase() === 'repurchase')
    let voucherData = JSON.parse(JSON.stringify(getters.getEsacVoucherData))
    let productData = JSON.parse(JSON.stringify(getters.getEsacProductData))
    let saleCreationData = {
      function_type: 'promo',
      status: 'save',
      cw_id: getters.getEsacCwSchedulesData[0].id,
      is_esac_redemption: true,
      country_id: getters.getEsacCountryId,
      downline_member_id: getters.getEsacUserId,
      location_id: getters.getEsacTransactionLocationId,
      stock_location_id: getters.getEsacStockLocationId(getters.getEsacCountryId),
      remarks: '',
      esac_vouchers: [],
      esac_vouchers_list: [],
      products: [],
      kittings: [],
      selected: {
        shipping: rootGetters['eshop/getOrderShipping'],
        payments: {
          paid: [],
          unpaid: [],
        },
        promotions: [],
      },
    }
    voucherData.forEach(item => {
      if (item.selected === true) {
        saleCreationData.esac_vouchers.push(item.id)
        saleCreationData.esac_vouchers_list.push({
          id: item.id,
          voucher_number: item.voucher_number,
          voucher_value: item.voucher_value,
        })
      }
    })
    productData.forEach(item => {
      if (item.disabled === false && item.selected === true && item.visible === true && item.quantity > 0) {
        if (item.item_type === 'P') {
          saleCreationData.products.push({
            product_id: item.item_id,
            quantity: item.quantity,
            transaction_type: saleTypesRepurchase.id,
            name: item.item_name,
            sku: item.item_code,
            eligible_cv: 0,
            base_price: { gmp_price_tax: item.item_price },
          })
        } else {
          saleCreationData.kittings.push({
            kitting_id: item.item_id,
            quantity: item.quantity,
            transaction_type: saleTypesRepurchase.id,
            name: item.item_name,
            code: item.item_code,
            eligible_cv: 0,
            kitting_price: { gmp_price_tax: item.item_price },
          })
        }
      }
    })
    dispatch('loadEsacSaleCreationData', saleCreationData).then(response => {
      let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
      routerData.currentStep = 'ReviewAndShipping'
      commit(T.SET_ESAC_ROUTER_DATA, routerData)
    })
  })
  commit(T.PROCESSING_FINISHED, 'settingEsacSalesCreationData')
}

// event handler when user click Back button in review and shipping screen
export const clickEsacReviewAndShippingBack = ({ commit, getters }, payload) => {
  let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
  routerData.currentStep = 'SelectProduct'
  commit(T.SET_ESAC_ROUTER_DATA, routerData)
}

// event handler when user click Continue button in review and shipping screen
export const clickEsacReviewAndShippingContinue = ({ commit, getters, dispatch }, payload) => {
  let shippingData = payload
  let saleCreationData = JSON.parse(JSON.stringify(getters.getEsacSaleCreationData))
  saleCreationData.sales_data.selected.shipping = {
    sale_delivery_method: shippingData.sale_delivery_method,
    recipient_name: shippingData.recipient_name === null ? '' : shippingData.recipient_name,
    recipient_mobile_country_code_id: shippingData.recipient_mobile_country_code_id,
    recipient_mobile_phone_number:
      shippingData.recipient_mobile_phone_number === null ? '' : shippingData.recipient_mobile_phone_number,
    recipient_selected_shipping_index: shippingData.recipient_selected_shipping_index || 0,
    recipient_addresses: shippingData.recipient_addresses || [],
    self_collection_point_id: shippingData.self_collection_point_id || null,
  }
  saleCreationData.sales_data.selected.promotions = []
  commit(T.SET_ESAC_SALE_CREATION_DATA, saleCreationData)
  commit(T.SET_ESAC_PAYMENT_SALE_ID, null)
  let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
  routerData.currentStep = 'MakePayment'
  commit(T.SET_ESAC_ROUTER_DATA, routerData)
}

// event handler when user click Back button in make payment screen
export const clickEsacMakePaymentBack = ({ commit, getters }, payload) => {
  let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
  routerData.currentStep = 'ReviewAndShipping'
  commit(T.SET_ESAC_ROUTER_DATA, routerData)
}

// event handler when payment completed
export const clickEsacMakePaymentComplete = ({ commit, getters }, payload) => {
  let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
  routerData.currentStep = 'OrderCompleted'
  commit(T.SET_ESAC_ROUTER_DATA, routerData)
}

// event handler when user click Back button in order completed screen
export const clickEsacOrderCompletedNext = ({ commit, getters, dispatch }, payload) => {
  let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
  routerData.currentStep = 'SelectVoucher'
  commit(T.SET_ESAC_ROUTER_DATA, routerData)
  dispatch('redirectToDashboardScreen')
}

// event handler when user click Next button in product search screen
export const clickEsacProductSearchNext = ({ commit, getters }, payload) => {
  // loop thru item visible on product search screen, make them visible on product selection screen with choosen quantity
  commit(T.PROCESSING_STARTED, 'esacProductSearchUpdate')
  let productData = JSON.parse(JSON.stringify(getters.getEsacProductData))
  productData.forEach(item => {
    if (item.disabled === false && item.searched === true) {
      item.quantity = item.searchQuantity
      item.amount = item.searchAmount
      if (item.quantity > 0) {
        item.selected = true
        item.visible = true
      } else if (item.quantity <= 0) {
        item.selected = false
        item.visible = false
      }
    }
  })
  commit(T.SET_ESAC_PRODUCT_DATA, productData)
  commit(T.SET_ESAC_PRODUCT_SEARCH_VISIBLE, false)
  commit(T.PROCESSING_FINISHED, 'esacProductSearchUpdate')
}

// event handler when user click Cancel button in product search screen
export const clickEsacProductSearchCancel = ({ commit, getters }, payload) => {
  commit(T.SET_ESAC_PRODUCT_SEARCH_VISIBLE, false)
}

// event handler when user click Search button in product search screen
export const clickEsacProductSearchSearch = ({ commit, getters }, payload) => {
  // filter the item according to the search text and category
  commit(T.PROCESSING_STARTED, 'esacProductSearchListLoading')
  let productData = JSON.parse(JSON.stringify(getters.getEsacProductData))
  productData.forEach(item => {
    if (
      (item.disabled === false && payload.codeName === '') ||
      item.item_name.toLowerCase().indexOf(payload.codeName.toLowerCase()) >= 0
    ) {
      item.searched = true
    } else {
      item.searched = false
    }
  })
  if (payload.category !== null) {
    productData.forEach(item => {
      if (item.item_broad_category !== payload.category) {
        item.searched = false
      }
    })
  }
  commit(T.SET_ESAC_PRODUCT_DATA, productData)
  commit(T.PROCESSING_FINISHED, 'esacProductSearchListLoading')
}

// update shipping data (triggered when anything changed in esac review and shipping screen)
export const updateEsacShippingData = ({ commit }, payload) => {
  commit(T.SET_ESAC_SHIPPING_DATA, payload)
}

// set order completed sale id
export const setEsacCompletedSaleId = ({ commit }, payload) => {
  commit(T.SET_ESAC_COMPLETED_SALE_ID, payload)
}

// redirect to voucher selection screen
export const redirectToEsacVoucherListScreen = ({ commit, getters }, payload) => {
  let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
  routerData.currentStep = 'SelectVoucher'
  routerData.preventReloadVoucher = 0
  commit(T.SET_ESAC_ROUTER_DATA, routerData)
  router.push({ name: 'EsacVoucherList' })
}

// show product selection screen
export const showProductSelectionScreen = ({ commit, getters }, payload) => {
  let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
  routerData.currentStep = 'SelectProduct'
  commit(T.SET_ESAC_ROUTER_DATA, routerData)
}

// redirect to make payment screen
export const redirectToEsacMakePaymentScreen = ({ commit, getters }, payload) => {
  commit(T.SET_ESAC_SALE_CREATION_DATA, null)
  commit(T.SET_ESAC_PAYMENT_SALE_ID, payload.saleId)
  let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
  routerData.currentStep = 'MakePayment'
  commit(T.SET_ESAC_ROUTER_DATA, routerData)
}

// redirect to dashboard
export const redirectToDashboardScreen = () => {
  router.push({ name: 'DashboardHome' })
}

export const setEsacVoucherListSearchText = ({ commit }, data) => {
  commit(T.SET_ESAC_VOUCHER_LIST_SEARCH_TEXT, data)
}

// API call to retrieve all redeem-able voucher belongs to current login member, invoke once
export const loadEsacVoucherList = ({ commit, getters, dispatch, rootGetters }, payload) => {
  let routerData = JSON.parse(JSON.stringify(getters.getEsacRouterData))
  let pagination = rootGetters.getPagination('esacvoucherlist') || {
    limit: rootGetters['getEsacVoucherListPaginationSize'],
    offset: 0,
  }
  let searchText = rootGetters['getEsacVoucherListSearchText']
  let loadData = true
  if (typeof routerData.preventReloadVoucher !== 'undefined' && routerData.preventReloadVoucher !== null) {
    routerData.preventReloadVoucher--
    if (routerData.preventReloadVoucher > 0) {
      loadData = false
    }
    commit(T.SET_ESAC_ROUTER_DATA, routerData)
  }
  if (loadData === true) {
    commit(T.PROCESSING_STARTED, 'eSacVoucherListLoading')
    // Reset Data
    commit(T.SET_ESAC_VOUCHER_DATA, [])
    let query = {
      country_id: getters.getEsacCountryId,
      voucher_status: 'N',
      sponsor_id: getters.getEsacUserId,
      for_redemption: 1,
      search: searchText,
      limit: pagination.limit,
      offset: pagination.offset || 0,
    }
    return post(U.API_GET_ESAC_VOUCHER_LIST_URL, query)
      .then(response => {
        let voucherData = []
        response.data.data
          .slice()
          .sort(function(a, b) {
            return a.sponsor_child_level === b.sponsor_child_level
              ? b.id - a.id
              : a.sponsor_child_level - b.sponsor_child_level
          })
          .forEach(item => {
            voucherData.push({
              id: item.id,
              country_id: item.country_id,
              voucher_number: item.voucher_number,
              voucher_value: item.voucher_value,
              voucher_type_id: item.voucher_type_id,
              max_purchase_qty: item.max_purchase_qty,
              min_purchase_amount: item.min_purchase_amount,
              issued_date: item.issued_date,
              expiry_date: item.expiry_date,
              esac_voucher_type_name: item.esac_voucher_type.name,
              esac_promotion_entitled_by: item.esac_promotion.entitled_by,
              sponsor_child_level: item.sponsor_child_level,
              ibo_id: item.user.old_member_id,
              ibo_name: item.user.member.name,
              enabled: item.user.id === getters.getEsacUserId,
              visible: true, // visible in product selection screen
              search_visible: true, // visible in voucher selection screen
              selected: false, // denote checkbox tick status
            })
          })
        commit(T.SET_ESAC_VOUCHER_DATA, voucherData)
        commit(T.SET_ESAC_VOUCHER_LIST_TOTAL_ROWS, response.data.total)
        commit(T.PROCESSING_FINISHED, 'eSacVoucherListLoading')
      })
      .catch(e => {
        dispatch('logError', { esac_voucher_list_loading: e })
        commit(T.PROCESSING_FINISHED, 'eSacVoucherListLoading')
      })
  }
}

// API call to retrieve product category needed in product search screen, invoke once
export const loadEsacProductCategoryList = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacProductCategoryListLoading')
  let query = {
    for_sales: 1,
    active: 1,
    limit: 0,
    sort: 'name',
    order: 'asc',
    offset: 0,
  }
  return post(U.API_GET_ESAC_PRODUCT_CATEGORY_LIST_URL, query)
    .then(response => {
      let productCategoryOptions = []
      let productCategories = response.data.data
      // Step 1 get all id for main category & broad category respectively
      let mainCategoryIds = []
      let broadCategoryIds = []
      let mainCategories = productCategories.filter(item => item.parent_id === 0)
      if (mainCategories.length > 0) {
        mainCategories.forEach(mainCategory => {
          mainCategoryIds.push(mainCategory.id)
          let broadCategories = productCategories.filter(item => item.parent_id === mainCategory.id)
          if (broadCategories.length > 0) {
            broadCategories.forEach(broadCategory => {
              broadCategoryIds.push(broadCategory.id)
            })
          }
        })
      }
      // Step 2 - initialize result
      productCategories.forEach(productCategory => {
        let broadCategoryId = -1
        let broadCategoryFound = false
        if (mainCategoryIds.indexOf(productCategory.id) >= 0) {
          broadCategoryFound = true
        } else {
          broadCategoryId = productCategory.id
          if (broadCategoryIds.indexOf(productCategory.id) >= 0) {
            broadCategoryFound = true
          }
        }
        productCategoryOptions.push({
          id: productCategory.id,
          name: productCategory.name,
          broad_category_id: broadCategoryId,
          broad_category_found: broadCategoryFound,
        })
      })
      // Step 3 - recusively loop
      let loopCondition = true
      while (loopCondition) {
        loopCondition = false
        let childCategories = productCategoryOptions.filter(item => item.broad_category_found === false)
        if (childCategories.length > 0) {
          childCategories.forEach(childCategory => {
            let parentCategory = productCategories.find(item => item.id === childCategory.broad_category_id)
            if (typeof parentCategory !== 'undefined' && parentCategory !== null) {
              childCategory.broad_category_id = parentCategory.parent_id
              if (broadCategoryIds.indexOf(parentCategory.parent_id) >= 0) {
                childCategory.broad_category_found = true
                loopCondition = true
              }
            } else {
              childCategory.broad_category_id = -1
              childCategory.broad_category_found = true
              loopCondition = true
            }
          })
        }
      }
      let productCategoryData = {
        data: productCategoryOptions,
        options: [
          {
            value: null,
            text: Vue.i18n.translate('Esac.EsacVoucherRedemption.PlaceHolder.AllCategories'),
          },
        ],
      }
      commit(T.SET_ESAC_PRODUCT_CATEGORY_DATA, productCategoryData)
      commit(T.PROCESSING_FINISHED, 'esacProductCategoryListLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_product_category_list_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacProductCategoryListLoading')
    })
}

// API call to retrieve product eligible for esac voucher deemption, invoke everytime voucher selection changed
export const loadEsacProductList = ({ commit, getters, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacProductListLoading')
  let esacVouchers = []
  getters.getEsacVoucherData.forEach(item => {
    if (item.selected) {
      esacVouchers.push(item.id)
    }
  })
  let query = {
    country_id: getters.getEsacCountryId,
    user_id: getters.getEsacUserId,
    text: null,
    transaction_location_id: getters.getEsacTransactionLocationId,
    stock_location_id: getters.getEsacStockLocationId(getters.getEsacCountryId),
    exclude_kitting_search: false,
    esac_vouchers: esacVouchers,
    limit: 100,
    offset: 0,
  }
  return post(U.API_GET_ESAC_PRODUCT_LIST_URL, query)
    .then(response => {
      let productCategoryData = JSON.parse(JSON.stringify(getters.getEsacProductCategoryData))
      let productData = JSON.parse(JSON.stringify(getters.getEsacProductData))
      let entitledByProductCategory = getters.getEntitledByProductCategory
      // first mark all as disabled
      productData.forEach(item => {
        item.disabled = true
      })
      // next add new item / or unmark disable flag for product/kitting valid to used in redemption
      response.data.products.data.forEach(item => {
        let product = productData.find(match => match.item_type === 'P' && match.item_id === item.id)
        if (typeof product === 'undefined' || product === null) {
          if (typeof item.price !== 'undefined' && item.price !== null) {
            productData.push({
              item_type: 'P',
              item_id: item.id,
              item_code: item.sku,
              item_name: item.name,
              item_category: item.category_id,
              item_broad_category: item.broad_category_id,
              item_image: item.image_link,
              item_price: parseFloat(item.price.gmp_price_tax),
              eligible_cv: parseFloat(item.eligible_cv),
              quantity: 0,
              amount: 0,
              searchQuantity: 0,
              searchAmount: 0,
              selected: !entitledByProductCategory, // no checkbox, visible implies selected
              visible: !entitledByProductCategory, // visible in product selection screen
              searched: true, // visible in product search screen
              searchedPaging: true,
              disabled: false, // disabled mean not applicable for currently selected vouchers
            })
          }
        } else {
          if (payload.sender === 'VoucherSelection') {
            product.quantity = 0
            product.amount = 0
            product.searchQuantity = 0
            product.searchAmount = 0
            product.selected = !entitledByProductCategory
            product.visible = !entitledByProductCategory
            product.searched = true
            product.searchedPaging = true
            product.disabled = false
          } else {
            if (product.selected === false && (entitledByProductCategory === false || product.quantity > 0)) {
              product.selected = true
              product.visible = true
            }
            product.disabled = false
          }
        }
      })
      response.data.kitting.data.forEach(item => {
        let product = productData.find(match => match.item_type === 'K' && match.item_id === item.id)
        if (typeof product === 'undefined' || product === null) {
          if (typeof item.price !== 'undefined' && item.price !== null) {
            productData.push({
              item_type: 'K',
              item_id: item.id,
              item_code: item.code,
              item_name: item.name,
              item_category: -1,
              item_broad_category: -1,
              item_image: item.image_link,
              item_price: parseFloat(item.price.gmp_price_tax),
              eligible_cv: parseFloat(item.eligible_cv),
              quantity: 0,
              amount: 0,
              searchQuantity: 0,
              searchAmount: 0,
              selected: !entitledByProductCategory,
              visible: !entitledByProductCategory,
              searched: true,
              searchedPaging: true,
              disabled: false,
            })
          }
        } else {
          if (payload.sender === 'VoucherSelection') {
            product.quantity = 0
            product.amount = 0
            product.searchQuantity = 0
            product.searchAmount = 0
            product.selected = !entitledByProductCategory
            product.visible = !entitledByProductCategory
            product.searched = true
            product.searchedPaging = true
            product.disabled = false
          } else {
            if (product.selected === false && (entitledByProductCategory === false || product.quantity > 0)) {
              product.selected = true
              product.visible = true
            }
            product.disabled = false
          }
        }
      })
      // lastly, disabled item should not be selected, visible
      productData.forEach(item => {
        if (item.disabled === true) {
          item.selected = false
          item.visible = false
          item.searched = false
          item.searchedPaging = false
        }
      })
      // update product category options
      productCategoryData.options = [
        {
          value: null,
          text: Vue.i18n.translate('Esac.EsacVoucherRedemption.PlaceHolder.AllCategories'),
        },
      ]
      productData.forEach(item => {
        if (item.disabled === false && item.item_broad_category !== -1) {
          let productCategoryCheck = productCategoryData.options.find(
            categoryItem => categoryItem.value === item.item_broad_category
          )
          if (typeof productCategoryCheck === 'undefined' || productCategoryCheck === null) {
            let productCategoryAdd = productCategoryData.data.find(
              categoryItem => categoryItem.id === item.item_broad_category
            )
            if (typeof productCategoryAdd !== 'undefined' && productCategoryAdd !== null) {
              productCategoryData.options.push({
                value: productCategoryAdd.id,
                text: productCategoryAdd.name,
              })
            }
          }
        }
      })
      commit(T.SET_ESAC_PRODUCT_CATEGORY_DATA, productCategoryData)
      commit(T.SET_ESAC_PRODUCT_DATA, productData)
      dispatch('updateEsacProductSearchPaging', { currentPage: 1 })
      commit(T.PROCESSING_FINISHED, 'esacProductListLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_product_list_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacProductListLoading')
    })
}

// API call to retrieve cw schedule
export const loadEsacCwScheduleList = ({ commit, getters, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacCwScheduleLoading')
  return post(U.API_GET_CW_SCHEDULES_LIST_URL, payload)
    .then(response => {
      commit(T.SET_ESAC_CW_SCHEDULES_DATA, JSON.parse(JSON.stringify(response.data.data)))
      commit(T.PROCESSING_FINISHED, 'esacCwScheduleLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_cw_schedule_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacCwScheduleLoading')
    })
}

// API call to retrieve active country
export const loadEsacActiveCountry = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacActiveCountryLoading')
  let query = {
    active: 1,
    limit: 100,
    order: 'asc',
  }
  return post(U.API_GET_ACTIVE_COUNTRY_URL, query)
    .then(response => {
      commit(T.SET_ESAC_ACTIVE_COUNTRY_DATA, JSON.parse(JSON.stringify(response.data.data)))
      commit(T.PROCESSING_FINISHED, 'esacActiveCountryLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_active_country_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacActiveCountryLoading')
    })
}

// API call to retrieve country relation
export const loadEsacCountryRelation = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacCountryRelationLoading')
  let query = {
    country_id: payload.country_id,
    relations: ['entity.locations', 'currency', 'stockLocation'],
  }
  return post(U.API_COUNTRY_RELATION, query)
    .then(response => {
      commit(T.SET_ESAC_COUNTRY_RELATION_DATA, JSON.parse(JSON.stringify(response.data)))
      commit(T.PROCESSING_FINISHED, 'esacCountryRelationLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_country_relation_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacCountryRelationLoading')
    })
}

// API call to retrieve stock location by transaction location
export const loadEsacStockLocationByTransactionLocation = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacStockLoadtionByTransactionLocationLoading')
  return get(U.API_GET_STOCK_LOCATION_BY_TRANSACTION_LOCATION + '/' + payload.location_id)
    .then(response => {
      let stockLocationId = null
      if (typeof response.data.stock_locations !== 'undefined') {
        if (response.data.stock_locations.length > 0) {
          stockLocationId = response.data.stock_locations[0].id
        }
      }
      commit(T.SET_ESAC_STOCK_LOCATION_DATA, JSON.parse(JSON.stringify(stockLocationId)))
      commit(T.PROCESSING_FINISHED, 'esacStockLoadtionByTransactionLocationLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_stock_location_by_transaction_location_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacStockLoadtionByTransactionLocationLoading')
    })
}

// API call to retrieve state & city
export const loadEsacStateCity = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacStateCityLoading')
  let query = {
    country_id: payload.country_id,
    location_address_data: true,
  }
  return post(U.API_GET_ESAC_STATE_CITY_URL, query)
    .then(response => {
      commit(T.SET_ESAC_STATE_CITY_DATA, JSON.parse(JSON.stringify(response.data.data)))
      commit(T.PROCESSING_FINISHED, 'esacStateCityLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_state_city_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacStateCityLoading')
    })
}

// API call to retrieve address format
export const loadEsacAddressFormat = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacAddressFormatLoading')
  let query = {
    country_id: payload.country_id,
    types: ['address'],
  }
  return post(U.API_GET_ADDRESS_FORMAT_URL, query)
    .then(response => {
      let data = response.data.address
      if (typeof data !== 'undefined' && data !== null) {
        data = JSON.parse(data)
      }
      commit(T.SET_ESAC_ADDRESS_FORMAT_DATA, data)
      commit(T.PROCESSING_FINISHED, 'esacAddressFormatLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_state_list_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacAddressFormatLoading')
    })
}

// API call to retrieve member details
export const loadEsacMemberData = ({ commit, getters, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacMemberDataLoading')
  let query = {
    user_id: getters.getEsacUserId,
  }
  return post(U.MEMBER_DETAILS, query)
    .then(response => {
      commit(T.SET_ESAC_MEMBER_DATA, response.data.member_data)
      commit(T.PROCESSING_FINISHED, 'esacMemberDataLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_member_data_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacMemberDataLoading')
    })
}

// API call to retrieve location addresses
export const loadEsacLocationAddressList = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacLocationAddressListLoading')
  let query = {
    country_id: payload.country_id,
    state_id: payload.state_id,
    city_id: payload.city_id,
    location_type_codes: ['stockist'],
    relations: ['location'],
    stockists_ibs_online: true,
    limit: 100,
    offset: 0,
  }
  return post(U.API_GET_LOCATION_ADDRESS_LIST_URL, query)
    .then(response => {
      let data = []
      response.data.data.forEach(item => {
        data.push({
          id: item.id,
          name: item.location.name,
          country_id: item.country_id,
          state_id: item.state_id,
          city_id: item.city_id,
          location_id: item.location_id,
          telephone_num: item.telephone_num,
          telephone_code_id: item.telephone_code_id,
          mobile_phone_num: item.mobile_phone_num,
          mobile_phone_code_id: item.mobile_phone_code_id,
          address_data: JSON.parse(item.address_data),
        })
      })
      commit(T.SET_ESAC_LOCATION_ADDRESS_DATA, data)
      commit(T.PROCESSING_FINISHED, 'esacLocationAddressListLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_location_address_list_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacLocationAddressListLoading')
    })
}

// API call to load sale creation data
export const loadEsacSaleCreationData = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacSaleCreationDataLoading')
  return post(U.API_GET_ESAC_SALE_CREATION_DATA_URL, payload)
    .then(response => {
      commit(T.SET_ESAC_SALE_CREATION_DATA, { sales_data: response.data })
      commit(T.PROCESSING_FINISHED, 'esacSaleCreationDataLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_sale_creation_data_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacSaleCreationDataLoading')
    })
}

// API call to create esac redemption (sale)
export const createEsacRedemption = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacSaleCreationLoading')
  return post(U.API_CREATE_ESAC_REDEMPTION_URL, payload)
    .then(response => {
      commit(T.SET_ESAC_SALE_DATA, response.data)
      commit(T.PROCESSING_FINISHED, 'esacSaleCreationLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_sale_creation_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacSaleCreationLoading')
    })
}

// API Call to retrieve sale detail
export const loadEsacSaleDetail = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacSaleDetailLoading')
  return post(U.API_GET_ESAC_SALE_DETAIL_URL, payload)
    .then(response => {
      commit(T.SET_ESAC_SALE_DATA, response.data)
      commit(T.PROCESSING_FINISHED, 'esacSaleDetailLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_sale_detail_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacSaleDetailLoading')
    })
}

// API call to load payment mode setting
export const loadEsacPaymentModeSettingData = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacPaymentModeSettingLoading')
  let query = {
    country_id: payload.country_id,
    location_id: payload.location_id,
    exclude_payment_mode: payload.exclude_payment_mode,
  }
  return post(U.API_GET_PAYMENT_MODE_SETTING_URL, query)
    .then(response => {
      commit(T.SET_ESAC_PAYMENT_MODE_SETTING_DATA, response.data)
      commit(T.PROCESSING_FINISHED, 'esacPaymentModeSettingLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_payment_mode_setting_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacPaymentModeSettingLoading')
    })
}

export const downloadEsacInvoice = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'esacDownloadInvoiceLoading')
  return post(U.API_DOWNLOAD_INVOICE_URL, payload)
    .then(response => {
      commit(T.SET_ESAC_DOWNLOAD_INVOICE_DATA, response.data)
      commit(T.PROCESSING_FINISHED, 'esacDownloadInvoiceLoading')
    })
    .catch(e => {
      dispatch('logError', { esac_download_invoice_loading: e })
      commit(T.PROCESSING_FINISHED, 'esacDownloadInvoiceLoading')
    })
}
