<template lang="pug">
  .crud
    modal-users(: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=6)
          div
            h2 \{{ $t('strings.users') }}:
            span \{{ $t('strings.description', {attribute: $t('strings.users')}) }}
          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="addUser") \{{ $t('strings.add') }}
            vm-tooltip(:text="$t('strings.options')" delay=".5s")
              vm-dropdown(vm-custom-content vm-trigger-click vm-trigger-outside-click)
                vm-button(type="border" icon="more-horizotnal" color="#afbbc6")

                vm-dropdown-menu
                  vm-dropdown-item.d-flex.justify-content-between(v-if="$auth.check('Admin')" @click="printReport")
                    vm-icon(icon="printer-outline")
                    slot &nbsp;\{{ $t('strings.print') }}
                  vm-dropdown-item.d-flex.justify-content-between(@click="deleteUsersConfirm" :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="users")
            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" width="200px")
                    div(v-for="(item,index) in columns")
                      vm-select-item(:key="item + ',asc'" v-if="item !== '' && item !== 'role'" :value="item + ',asc'" :text="$t('users.'+ item) + ', asc'")
                      vm-select-item(:key="item + ',desc'" v-if="item !== '' && item !== 'role'" :value="item + ',desc'" :text="$t('users.'+ item) + ', desc'")
                  vm-tooltip(:text="$t('strings.filters')" delay=".5s")
                    vm-dropdown(ref="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-date-picker.filter(type="daterange" :label="$t('users.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")

                            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" style="display: none;")
                  vm-tooltip(:text="$t('strings.display_grid')" delay=".5s")
                    vm-button(type="default" size="small" icon="grid" color="rgba(var(--gray),1)" style="display: none;")
            template(slot="thead")
              vm-th(:key="index" v-if="column !== 'id'" v-for="(column, index) in columns") \{{ $t('users.' + 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 != 'role' && column != 'total' && column != 'unit_price'") \{{data[indextr][column]}}
                  vm-chip(v-if="column == 'role'" :color="colorRole(data[indextr]['view_permissions'][0])") \{{data[indextr]['view_permissions'][0]}}
                  vm-chip(v-if="column == 'status'" :color="colorStatus(data[indextr]['status'])") \{{data[indextr]['status']}}
                vm-td
                vm-dropdown(vm-custom-content vm-trigger-click vm-trigger-outside-click)
                  vm-button(type="flat" icon="more-horizotnal" color="#afbbc6")

                  vm-dropdown-menu
                    vm-dropdown-item.d-flex.justify-content-between(@click="editUser(data[indextr], tr)")
                      vm-icon(icon="edit-2-outline")
                      slot &nbsp;\{{ $t('strings.edit') }}
                    vm-dropdown-item.d-flex.justify-content-between(v-if="data[indextr]['status'] == 'Inactivo'" @click="setActionUser(data[indextr], 'actived')")
                      vm-icon(icon="person-done-outline")
                      slot &nbsp;\{{ $t('strings.action_active') }}
                    vm-dropdown-item.d-flex.justify-content-between(v-if="data[indextr]['status'] == 'Activo'" @click="setActionUser(data[indextr], 'inactived')")
                      vm-icon(icon="person-delete-outline")
                      slot &nbsp;\{{ $t('strings.action_inactive') }}
                    vm-dropdown-item.d-flex.justify-content-between(v-if="data[indextr]['status'] === 'Inactivo'" @click="deleteUserConfirm(data[indextr])")
                      vm-icon(icon="trash-2-outline")
                      slot &nbsp;\{{ $t('strings.delete') }}
                    //- 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 ModalUsers from '@/components/modals/ModalUsers.vue'
import parseDeleteMany from '@/utils/parseDeleteMany'
import { createNamespacedHelpers } from 'vuex'
const { mapGetters, mapActions } = createNamespacedHelpers('Users')

export default {
  name: 'Users',
  components: {
    ModalUsers
  },
  data: () => ({
    currentPage: 1,
    isModalAdd: true,
    form: {},
    selected: [],
    columns: [
      'name',
      'email',
      'role',
      'status'
    ],
    status: [
    ],
    filters: {
      // Nota: Estos campos se parsearan en el v-model de los filtros. Ver linea 60
      where: {
        name: '',
        email: '',
        param: ''
      },
      whereIn: {
        // Agrega las columnas que se filtraran con mas de una opcion ejemplo: status: []
      },
      whereBetween: {
        // Agrega las columnas que se filtraran entre paramentros ejemplo: priece: []
      },
      betweenDates: {
        created_at: []
      },
      orderBy: ''
    }
  }),
  async created () {
    this.currentPage = this.pagination.currentPage
    await this.getUsers(this.currentPage)
    this.getCatalog()
  },
  methods: {
    ...mapActions([
      'deleteUser',
      'deleteUsers',
      'loadUsers',
      'loadCatalog',
      'actionUser',
      'setModalVisible',
      'printReport',
      'applyFilter',
      'clearFilter'
    ]),
    colorRole (code) {
      return code === 'Admin' ? 'danger' : 'success'
    },
    colorStatus (code) {
      return code.trim() === 'Activo' ? 'success' : 'dark'
    },
    addUser () {
      this.isModalAdd = true
      this.setModalVisible(true)
      this.form = {}
    },
    editUser (user, index) {
      this.isModalAdd = false
      this.setModalVisible(true)
      this.form = { ...user }
    },
    async deleteUserConfirm (user) {
      let t = this
      this.auxDeleteUser = () => {
        t.deleteUser(user).then(() => { t.selected = [] })
      }
      this.$vm.dialog({
        color: 'danger',
        title: this.$t('front.delete_modal'),
        text: this.$t('front.delete_confirmation2', { model: this.$t('strings.user'), attribute: this.$t(user.name) }),
        accept: this.auxDeleteUser
      })
    },
    async deleteUsersConfirm () {
      let t = this
      let usersMany = parseDeleteMany(this.selected, 'name')
      this.auxDeleteUser = () => {
        t.deleteUsers(usersMany).then(() => { t.selected = [] })
      }
      this.$vm.dialog({
        color: 'danger',
        title: this.$t('front.delete_modal'),
        text: this.$t('front.delete_confirmation', { model: this.$t('strings.user'), attribute: usersMany.values }),
        accept: this.auxDeleteUser
      })
    },
    async setActionUser (record, action) {
      record.id && this.actionUser({ id: record.id, action })
    },
    async getUsers (page) {
      let t = this
      this.loadUsers({ page }).then(data => t.getProps(t.$route.params.id))
    },
    getProps (index) {
      let user = this.users.filter(user => user.id === parseInt(index))[0]
      user && this.editUser(user, index)
    },
    async getCatalog () {
      Object.keys(this.usersCatalog).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)
    },
    handleChange (date) {
      this.filters.betweenDates.created_at = date
    },
    hiddeDrop () {
      let [dropdownMenu] = this.$refs.dropdown.$children.filter((item) => {
        return item.hasOwnProperty('dropdownVisible')
      })
      dropdownMenu.dropdownVisible = false
    }
  },
  computed: {
    ...mapGetters([
      'users',
      'usersCatalog',
      'pagination',
      'filterParams'
    ]),
    enabledDelete () {
      return this.selected.length > 0 && this.selected.every(el => el.deleted_at)
    },
    total () {
      return this.selected.reduce((prev, cur) => prev + parseFloat(cur.total), 0).toFixed(2)
    }
  },
  watch: {
    currentPage (currentPage) {
      this.getUsers(currentPage)
    },
    filterParams (filter) {
      this.hiddeDrop()
      filter.length === 0 && (this.filters = {
        where: {
          name: '',
          email: '',
          param: ''
        },
        whereIn: {},
        whereBetween: {},
        betweenDates: {
          created_at: []
        },
        orderBy: ''
      })
      this.selected = []
      this.currentPage = 1
      this.getUsers(this.currentPage)
    }
  }
}
</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>
