import _ from 'lodash'

export const namespaced = true
export const state = () => ({
  subdomain: '',
  stockId: null,
  checkout: {
    paymentMethod: null,
    promocode: {
      code: '',
      claimable: null,
      discountType: null,
      discountValue: 0,
      minRedeemType: null,
      minRedeemValue: 0
    },
    shipping: {
      name: '',
      cost: 0,
      codCost: 0
    }
  },
  customer: {
    id: null,
    name: 'Guest',
    addressList: [],
    address: '',
    tel: '',
    taxId: '',
    email: ''
  },
  order: {
    id: null,
    shippingType: '',
    address: '',
    bankAccountId: '',
    customerId: '',
    email: '',
    name: '',
    paymentSlip: '',
    promotionCode: '',
    salePageDomain: '',
    shippop: false,
    taxable: false,
    taxId: '',
    tel: '',
    transferredAt: '',
    purchases: [],
    setPurchases: [],
    net: 0
  }
})

export const mutations = {
  SET_SUBDOMAIN (state, payload) {
    state.subdomain = payload
  },
  SET_STOCK_ID (state, payload) {
    state.stockId = payload
  },
  SET_CUSTOMER (state, payload) {
    state.customer = _.cloneDeep(payload)
  },
  SET_ADDRESS (state, payload) {
    state.customer = {
      ...state.customer,
      ...payload
    }
  },
  ADD_ADDRESSLIST (state, payload) {
    state.customer.addressList.push(payload)
  },
  SET_CHECKOUT (state, payload) {
    state.checkout = {
      ...state.checkout,
      ...payload
    }
  },
  CLEAR_CHECKOUT (state) {
    state.checkout = {
      promocode: {
        code: ''
      },
      shipping: {
        name: ''
      }
    }
  },
  SET_ORDER (state, payload) {
    state.order = payload
  },
  CLEAR_ORDER (state, payload) {
    state.order = payload
  }
}

export const actions = {
  setSubdomain ({ commit }, payload) {
    commit('SET_SUBDOMAIN', payload)
  },
  setStockId ({ commit }, payload) {
    commit('SET_STOCK_ID', payload)
  },
  setCustomer ({ commit }, payload) {
    commit('SET_CUSTOMER', payload)
  },
  setAddress ({ commit }, payload) {
    commit('SET_ADDRESS', payload)
  },
  addAddressList ({ commit }, payload) {
    commit('ADD_ADDRESSLIST', payload)
  },
  setCheckout ({ commit }, payload) {
    commit('SET_CHECKOUT', payload)
  },
  clearCheckout ({ commit }) {
    commit('CLEAR_CHECKOUT')
  },
  setOrder ({ commit }, payload) {
    commit('SET_ORDER', payload)
  },
  clearOrder ({ commit }) {
    const defaultState = state()
    commit('CLEAR_ORDER', defaultState.order)
  }
}

export const getters = {
  subdomain: (state) => state.subdomain,
  stockId: (state) => state.stockId,
  customer: (state) => state.customer,
  checkout: (state) => state.checkout,
  order: (state) => state.order
}

export default {
  namespaced,
  state,
  actions,
  mutations,
  getters
}
