<template lang="pug">
  .crud
    modal-customers(:form='form', :is-add='isModalAdd')
    .container-fluid
      vm-row.heading(vm-w="12")
        vm-col(vm-type="flex" vm-align="center" vm-lg=6 vm-sm=12)
          div
            h2 \{{ $t('strings.customers') }}:
            span \{{ $t('strings.description', {attribute: $t('strings.customers')}) }}
          div(style="display:none;")
            vm-button(type="default" icon="list")
            vm-button(type="default" icon="grid" color="rgba(var(--gray),1)")
        vm-col(vm-type="flex" vm-align="center" vm-justify="flex-end" vm-lg=6 vm-sm=6)
          div
            vm-button(icon="plus" @click="addCustomer") \{{ $t('strings.add') }}
            vm-tooltip(:text="$t('strings.options')" delay=".5s")
              vm-dropdown(vm-custom-content vm-trigger-click)
                vm-button(type="border" icon="more-horizotnal" color="#afbbc6")

                vm-dropdown-menu
                  vm-dropdown-item.d-flex.justify-content-between(@click="printReport")
                    vm-icon(icon="printer-outline")
                    slot &nbsp;\{{ $t('strings.print') }}
                  vm-dropdown-item.d-flex.justify-content-between(@click="deleteCustomersConfirm" :disabled="!enabledDelete")
                    vm-icon(icon="trash-2-outline")
                    slot &nbsp;\{{ $t('strings.delete') }}
      vm-row(vm-w="12")
        vm-col.card(vm-sm=12)
          vm-table(multiple v-model="selected"  max-height="350px" :data="customers")
            template(slot="header")
              .d-flex.justify-content-between
                vm-input(icon="search" size="small" :placeholder="$t('strings.search')" v-model="filters.where.param" @keyup.enter="applyFilter(filters)")
                div
                  vm-select(:placeholder="$t('strings.order_by')" autocomplete v-model="filters.orderBy" @change="applyFilter(filters)" size="small")
                    div(v-for="(item,index) in columns")
                      vm-select-item(:key="item + ',asc'" v-if="item !== ''" :value="item + ',asc'" :text="$t('customers.'+ item) + ', asc'")
                      vm-select-item(:key="item + ',desc'" v-if="item !== ''" :value="item + ',desc'" :text="$t('customers.'+ item) + ', desc'")
                  vm-tooltip(:text="$t('strings.filters')" delay=".5s")
                    vm-dropdown(vm-custom-content vm-trigger-click)
                      vm-button(type="default" icon="funnel-outline" size="small")

                      vm-dropdown-menu(class="filters")
                        .heading.d-flex.justify-content-between
                          h4 \{{ $t('strings.filters') }}
                          vm-button(type="flat" size="small" @click="clearFilter") \{{ $t('strings.clear') }}
                        vm-select.filter(:placeholder="$t('strings.multiple')" multiple autocomplete label="Status" v-model="filters.whereIn.status")
                          vm-select-item(:key="index" :value="item.value" :text="item.text" v-for="(item,index) in status")
                        vm-date-picker.filter(type="daterange" :label="$t('customers.created_at')" :placeholder="$t('strings.select_date')" @on-change="handleChange" :value="filters.betweenDates.created_at")
                        .filter.d-flex
                          vm-button(@click="applyFilter(filters)") \{{ $t('strings.apply') }}
                  vm-tooltip(:text="$t('strings.display_list')" delay=".5s")
                    vm-button(type="default" size="small" icon="list")
                  vm-tooltip(:text="$t('strings.display_grid')" delay=".5s")
                    vm-button(type="default" size="small" icon="grid" color="rgba(var(--gray),1)")
            template(slot="thead")
              vm-th(:key="index" v-if="column !== 'id'" v-for="(column, index) in columns") \{{ $t('customers.' + column) }}
            template(slot-scope="{data}")
              vm-tr(:data="tr" :key="indextr" v-for="(tr, indextr) in data")
                vm-td(:data="data[indextr][column]" :key="index" v-if="column !== 'id'" v-for="(column, index) in columns")
                  slot(v-if="column == 'total' || column == 'unit_price'")  \{{data[indextr][column] | currency }}
                  slot(v-if="column != 'status' && column != 'total' && column != 'unit_price'") \{{data[indextr][column]}}
                  vm-chip(v-if="column == 'status'" :color="colorStatus(data[indextr][column])") \{{data[indextr]['status_display']}}
                vm-td
                vm-dropdown(vm-custom-content vm-trigger-click)
                  vm-button(type="flat" icon="more-horizotnal" color="#afbbc6")

                  vm-dropdown-menu
                    vm-dropdown-item.d-flex.justify-content-between(@click="editCustomer(data[indextr], tr)")
                      vm-icon(icon="edit-2-outline")
                      slot &nbsp;\{{ $t('strings.edit') }}
                    vm-dropdown-item.d-flex.justify-content-between(@click="deleteCustomerConfirm(data[indextr])")
                      vm-icon(icon="trash-2-outline")
                      slot &nbsp;\{{ $t('strings.delete') }}
          vm-pagination(:total="pagination.totalPages" v-model="currentPage" goto)
          transition(name="enter")
            .total-records(v-if="total>0") Total: \{{ total | currency }}
</template>

<script>
import ModalCustomers from '@/components/modals/ModalCustomers.vue'
import parseDeleteMany from '@/utils/parseDeleteMany'
import { createNamespacedHelpers } from 'vuex'
const { mapGetters, mapActions } = createNamespacedHelpers('Customers')

export default {
  name: 'Customers',
  components: {
    ModalCustomers
  },
  data: () => ({
    currentPage: 1,
    isModalAdd: true,
    form: {},
    selected: [],
    enabledDelete: false,
    columns: [
      'id',
      'contact',
      'email',
      'address',
      'state',
      'phone'
    ],
    status: [
      {
        text: 'Pendiente',
        value: 1,
        color: 'warning'
      },
      {
        text: 'Pagado',
        value: 2,
        color: 'warning'
      }
    ],
    filters: {
      where: {
        contact: '',
        email: '',
        param: ''
      },
      whereIn: {
        status: []
      },
      whereBetween: {
        priece: []
      },
      betweenDates: {
        created_at: []
      },
      orderBy: ''
    }
  }),
  async created () {
    this.currentPage = this.pagination.currentPage
    this.customers.length === 0 && await this.getCustomers(1)
    this.getCatalog()
  },
  methods: {
    ...mapActions([
      'deleteCustomer',
      'deleteCustomers',
      'loadCustomers',
      'loadCatalog',
      'actionCustomer',
      'setModalVisible',
      'printReport',
      'applyFilter',
      'clearFilter'
    ]),
    colorStatus (code) {
      return this.status.find(e => e.value === code)['color']
    },
    addCustomer () {
      this.isModalAdd = true
      this.setModalVisible(true)
      this.form = {}
    },
    editCustomer (customer, index) {
      this.isModalAdd = false
      this.setModalVisible(true)
      this.form = { ...customer }
    },
    async deleteCustomerConfirm (customer) {
      let t = this
      this.auxDeleteCustomer = () => {
        t.deleteCustomer(customer).then(() => { t.selected = [] })
      }
      this.$vm.dialog({
        color: 'danger',
        title: this.$t('front.delete_modal'),
        text: this.$t('front.delete_confirmation', { model: this.$t('strings.customer'), attribute: this.$t(customer.contact) }),
        accept: this.auxDeleteCustomer
      })
    },
    async deleteCustomersConfirm () {
      let t = this
      let customersMany = parseDeleteMany(this.selected, 'contact')
      this.auxDeleteCustomer = () => {
        t.deleteCustomers(customersMany).then(() => { t.selected = [] })
      }
      this.$vm.dialog({
        color: 'danger',
        title: this.$t('front.delete_modal'),
        text: this.$t('front.delete_confirmation', { model: this.$t('strings.customer'), attribute: customersMany.values }),
        accept: this.auxDeleteCustomer
      })
    },
    async setActionCustomer (record, action) {
      record.id && this.actionCustomer({ id: record.id, action })
    },
    async getCustomers (page) {
      let t = this
      this.loadCustomers({ page }).then(data => t.getProps(t.$route.params.id))
    },
    getProps (index) {
      let customer = this.customers.filter(customer => customer.id === parseInt(index))[0]
      customer && this.editCustomer(customer, index)
    },
    async getCatalog () {
      Object.keys(this.customersCatalog).forEach(e => this.loadCatalog({ url: e, filter: '' }))
    },
    autoCompleteFunc (value) {
      let payload = {}
      let column = value.target.parentElement.parentElement.getAttribute('column')
      let param = value.srcElement.value
      payload.url = value.target.parentElement.parentElement.getAttribute('url')
      payload.filter = `?${column}=${param}*&order_by=${column},asc`
      this.loadCatalog(payload)
    },
    newObjectFuncModal (value) {
      //
    },
    newObjectFuncView (value) {
      //
    },
    handleChange (date) {
      this.filters.betweenDates.created_at = date
    }
  },
  computed: {
    ...mapGetters([
      'customers',
      'customersCatalog',
      'pagination',
      'filterParams'
    ]),
    total () {
      return this.selected.reduce((prev, cur) => prev + parseFloat(cur.total), 0).toFixed(2)
    }
  },
  watch: {
    currentPage (currentPage) {
      this.getCustomers(currentPage)
    },
    filterParams (filter) {
      filter.length === 0 && (this.filters.betweenDates.created_at = [])
      filter.length === 0 && (this.filters.where.param = '')
      this.selected = []
      this.currentPage = 1
      this.getCustomers(this.currentPage)
    },
    selected (selected) {
      this.enabledDelete = selected.length > 0
    }
  }
}
</script>

<style lang="scss">
.filters {
  .filter {
    padding: 5px 10px;
    width: 250px;
  }
}
.con-vm-tooltip {
  display: inline-block;
  float: left;
  position: relative;
}
.vm-table--header {
  padding: 10px;
  span {
    width: 100%;
    .justify-content-between {
      div:last-child {
        .vm-button {
          margin: 0 3px;
        }
        .vm-con-dropdown {
          float: left;
        }
        .con-select {
          display: inline-block;
          input {
            height: 32px;
          }
        }
      }
    }
  }
}
</style>
