<template lang="pug">
  .crud
    .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.purchase_orders') }}:
            span \{{ $t('strings.description', {attribute: $t('strings.purchase_orders')}) }}
          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="addPurchaseOrder") \{{ $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="deletePurchaseOrdersConfirm" :disabled="!enabledDelete")
                    vm-icon(icon="trash-2-outline")
                    slot &nbsp;\{{ $t('strings.delete') }}
                  //- More options
                      Agrega mas acciones para colecciones de datos
      vm-row(vm-w="12")
        vm-col.card(vm-sm=12)
          vm-table(multiple v-model="selected"  max-height="350px" :data="purchaseOrders")
            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('purchase_orders.'+ item) + ', asc'")
                      vm-select-item(:key="item + ',desc'" v-if="item !== ''" :value="item + ',desc'" :text="$t('purchase_orders.'+ 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")
                        //- Add filters
                            Agrega los filtros que prefieras por ejemplo:
                            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('purchase_orders.created_at')" :placeholder="$t('strings.select_date')" @on-change="handleChange" :value="filters.betweenDates.created_at")

                            NOTA: (agregar clase .filter)
                        .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('purchase_orders.' + 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="editPurchaseOrder(data[indextr], tr)")
                      vm-icon(icon="edit-2-outline")
                      slot &nbsp;\{{ $t('strings.edit') }}
                    vm-dropdown-item.d-flex.justify-content-between(@click="deletePurchaseOrderConfirm(data[indextr])")
                      vm-icon(icon="trash-2-outline")
                      slot &nbsp;\{{ $t('strings.delete') }}
                    vm-dropdown-item.d-flex.justify-content-between(@click="setActionPurchaseOrder(data[indextr], 'approved')")
                      vm-icon(icon="checkmark-circle-outline")
                      slot &nbsp;\{{ $t('strings.approve') }}
                    //- More actions
          vm-pagination(:total="pagination.totalPages" v-model="currentPage" goto)
          transition(name="enter")
            .total-records(v-if="total>0") Total: \{{ total | currency }}
</template>

<script>
import parseDeleteMany from '@/utils/parseDeleteMany'
import { createNamespacedHelpers } from 'vuex'
const { mapGetters, mapActions } = createNamespacedHelpers('PurchaseOrders')

export default {
  name: 'PurchaseOrders',
  data: () => ({
    currentPage: 1,
    selected: [],
    enabledDelete: false,
    columns: [
      'id',
      'folio',
      'subtotal',
      'total',
      'status'
    ],
    status: [
      {
        text: 'Pendiente',
        value: 1,
        color: 'warning'
      },
      {
        text: 'Aprobado',
        value: 2,
        color: 'primary'
      },
      {
        text: 'Cancelado',
        value: 3,
        color: 'danger'
      },
      {
        text: 'Pagado',
        value: 4,
        color: 'success'
      }
    ],
    filters: {
      // Nota: Estos campos se parsearan en el v-model de los filtros. Ver linea 60
      where: {
        folio: '',
        param: ''
      },
      whereIn: {
        status: []
      },
      whereBetween: {
        // Agrega las columnas que se filtraran entre paramentros ejemplo: priece: []
      },
      betweenDates: {
        created_at: []
      },
      orderBy: ''
    }
  }),
  async created () {
    this.currentPage = this.pagination.currentPage
    this.purchaseOrders.length === 0 && await this.getPurchaseOrders(1)
    this.getCatalog()
  },
  methods: {
    ...mapActions([
      'deletePurchaseOrder',
      'deletePurchaseOrders',
      'loadPurchaseOrders',
      'loadCatalog',
      'actionPurchaseOrder',
      'printReport',
      'applyFilter',
      'clearFilter'
    ]),
    colorStatus (code) {
      return this.status.find(e => e.value === code)['color']
    },
    addPurchaseOrder () {
      this.$router.push({ name: 'newPurchaseOrder', params: { isAdd: true } })
    },
    editPurchaseOrder (purchaseOrder, index) {
      let id = purchaseOrder.id
      this.$router.push({ name: 'editPurchaseOrder', params: { id } })
    },
    async deletePurchaseOrderConfirm (purchaseOrder) {
      let t = this
      this.auxDeletePurchaseOrder = () => {
        t.deletePurchaseOrder(purchaseOrder).then(() => { t.selected = [] })
      }
      this.$vm.dialog({
        color: 'danger',
        title: this.$t('front.delete_modal'),
        text: this.$t('front.delete_confirmation', { attribute: this.$t(purchaseOrder.folio) }),
        accept: this.auxDeletePurchaseOrder
      })
    },
    async deletePurchaseOrdersConfirm () {
      let t = this
      let purchaseOrdersMany = parseDeleteMany(this.selected, 'folio')
      this.auxDeletePurchaseOrder = () => {
        t.deletePurchaseOrders(purchaseOrdersMany).then(() => { t.selected = [] })
      }
      this.$vm.dialog({
        color: 'danger',
        title: this.$t('front.delete_modal'),
        text: this.$t('front.delete_confirmation', { attribute: purchaseOrdersMany.values }),
        accept: this.auxDeletePurchaseOrder
      })
    },
    async setActionPurchaseOrder (record, action) {
      record.id && this.actionPurchaseOrder({ id: record.id, action })
    },
    async getPurchaseOrders (page) {
      this.loadPurchaseOrders({ page })
    },
    async getCatalog () {
      let t = this
      Object.keys(this.purchaseOrdersCatalog).forEach(e => t.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([
      'purchaseOrders',
      'purchaseOrdersCatalog',
      'pagination',
      'filterParams'
    ]),
    total () {
      return this.selected.reduce((prev, cur) => prev + parseFloat(cur.total), 0).toFixed(2)
    }
  },
  watch: {
    currentPage (currentPage) {
      this.getPurchaseOrders(currentPage)
    },
    filterParams (filter) {
      filter.length === 0 && (this.filters.whereIn.status = [])
      filter.length === 0 && (this.filters.where.param = '')
      this.selected = []
      this.currentPage = 1
      this.getPurchaseOrders(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>
