import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import app from '../../main' // import the instance
import checkResponse from '@/utils/checkResponse'
import parserFilters from '@/utils/parserFilters'
import parserSlug from '@/utils/parserSlug'

Vue.use(Vuex)

const state = {
  customers: [],
  pagination: {
    currentPage: 1,
    perPage: 5,
    totalCustomers: 0,
    totalPages: 0
  },
  customersCatalog: {},
  filterParams: '',
  isModalVisible: false
}

const mutations = {
  SET_CUSTOMERS (state, payload) {
    state.customers = payload.data

    state.pagination = {
      currentPage: payload.current_page,
      perPage: payload.per_page,
      totalCustomers: payload.total,
      totalPages: payload.last_page
    }
  },
  ADD_CUSTOMER (state, payload) {
    state.customers.push(payload)
  },
  UPDATE_CUSTOMER (state, payload) {
    const idx = state.customers.findIndex(u => u.id === payload.id)

    if (idx >= 0) {
      Vue.set(state.customers, idx, payload)
    }
  },
  DELETE_CUSTOMER (state, payload) {
    const idx = state.customers.findIndex(u => u.id === payload.id)

    if (idx >= 0) {
      Vue.delete(state.customers, idx)
    }
  },
  DELETE_CUSTOMERS (state, payload) {
    for (let id of payload.ids) {
      const idx = state.customers.findIndex(u => u.id === id)

      if (idx >= 0) {
        Vue.delete(state.customers, idx)
      }
    }
  },
  SET_MODAL_VISIBLE (state, payload) {
    state.isModalVisible = payload
  },
  SET_FILTER_PARAMS (state, payload) {
    state.filterParams = payload
  },
  SET_CATALOG (state, { object, payload }) {
    state.customersCatalog[object] = payload.data
  }
}

const actions = {
  async loadCustomers ({ commit }, payload) {
    app.$Progress.start()
    try {
      const response = await axios.get(`customers?page=${payload.page}${state.filterParams}`)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('SET_CUSTOMERS', response.data)
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  async addCustomer ({ commit }, payload) {
    const customer = {
      contact: payload.contact,
      address: payload.address,
      state: payload.state,
      phone: payload.phone,
      email: payload.email
    }

    app.$Progress.start()

    try {
      const response = await axios.post('customers', customer)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('ADD_CUSTOMER', response.data)
        commit('SET_MODAL_VISIBLE', false)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.customers', text: 'front.added_successfully', icon: 'checkmark-circle-outline' }, { root: true })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  async editCustomer ({ commit }, payload) {
    const customer = {
      contact: payload.contact,
      address: payload.address,
      state: payload.state,
      phone: payload.phone,
      email: payload.email
    }

    app.$Progress.start()

    try {
      const response = await axios.put(`customers/${payload.id}`, customer)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('UPDATE_CUSTOMER', response.data)
        commit('SET_MODAL_VISIBLE', false)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.customers', text: 'front.updated_successfully', icon: 'checkmark-circle-outline' }, { root: true })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  async deleteCustomer ({ commit }, payload) {
    app.$Progress.start()
    try {
      const response = await axios.delete(`customers/${payload.id}`)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('DELETE_CUSTOMER', payload)
        commit('SET_MODAL_VISIBLE', false)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.customers', text: 'front.deleted_successfully', icon: 'checkmark-circle-outline' }, { root: true })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  async deleteCustomers ({ commit }, payload) {
    app.$Progress.start()
    try {
      const response = await axios.delete(`customers/delete`, { params: { ids: payload.ids } })
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('DELETE_CUSTOMERS', payload)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.customers', text: 'front.deleted_successfully', icon: 'checkmark-circle-outline' }, { root: true })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  async actionCustomer ({ commit }, payload) {
    app.$Progress.start()
    try {
      const response = await axios.put(`customers/${payload.id}/${payload.action}`)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('UPDATE_CUSTOMER', response.data)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.customers', text: `customers.${payload.action}`, icon: 'checkmark-circle-outline' }, { root: true })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  printReport ({ commit }, payload) {
    app.$Progress.start()
    try {
      window.open(axios.defaults.baseURL + '/customers/export?' + state.filterParams)
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  applyFilter ({ commit }, payload) {
    const filter = parserFilters(payload)
    commit('SET_FILTER_PARAMS', filter)
  },
  clearFilter ({ commit }, payload) {
    const filter = ''
    commit('SET_FILTER_PARAMS', filter)
  },
  async loadCatalog ({ commit }, payload) {
    let url = parserSlug(payload.url)
    app.$Progress.start()
    try {
      const response = await axios.get(`${url}${payload.filter}`)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('SET_CATALOG', { object: payload.url, payload: response.data })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  setModalVisible ({ commit }, payload) {
    commit('SET_MODAL_VISIBLE', payload)
  }
}

const getters = {
  customers: state => state.customers,
  customersCatalog: state => state.customersCatalog,
  pagination: state => state.pagination,
  isModalVisible: state => state.isModalVisible,
  filterParams: state => state.filterParams
}

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