<template lang="pug">
  .crud
    modal-purchase-orders-detail(:detail='detail', :index='index', :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 \{{ getTitle() }}:
        vm-col(vm-type="flex" vm-align="center" vm-justify="flex-end" vm-lg=6 vm-sm=6)
          div
            vm-button#saveRecord.vm-con-loading__container(icon="save-outline" :disabled="!enabledSave && $v.newRecord.$invalid" @click="saveRecord") \{{ $t('strings.save') }}
            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="printReportRecord(newRecord)" :disabled="!enabledEdit")
                    vm-icon(icon="printer-outline")
                    slot &nbsp;\{{ $t('strings.print') }}
                  vm-dropdown-item.d-flex.justify-content-between(@click="deletePurchaseOrderConfirm(newRecord)" :disabled="!enabledEdit")
                    vm-icon(icon="trash-2-outline")
                    slot &nbsp;\{{ $t('strings.delete') }}
                  vm-dropdown-item.d-flex.justify-content-between(@click="setActionPurchaseOrder(newRecord, 'approved')" :disabled="!enabledEdit")
                    vm-icon(icon="checkmark-circle-outline")
                    slot &nbsp;\{{ $t('strings.approve') }}
                  //- More options
                      Agrega mas acciones para colecciones de datos
      vm-row(vm-w="12")
        vm-col.card(vm-sm=12)
          vm-row.form(vm-align="center" vm-type="flex" vm-justify="space-between" vm-w="12")
            vm-col(vm-justify="center", vm-align="center", vm-w=4)
              b-form-group
                vm-select(url="customers" column="contact" createObject @create-object="newObjectFuncView" autocomplete :placeholder='$t("purchase_orders.customer_id_placeholder")' :danger="!$v.newRecord.customer_id.numeric" :danger-text="'Name must have at least 4 ' + $v.newRecord.customer_id.$params.numeric + ' letters.'" v-model="newRecord.customer_id" :label='$t("purchase_orders.customer_id")' @input-change="autoCompleteFunc")
                  vm-select-item(:key="index" :value="item.id" :text="item.contact" v-for="(item,index) in purchaseOrdersCatalog.customers")
            vm-col(vm-justify="center", vm-align="center", vm-w=4)
              b-form-group
                vm-select(:placeholder="$t('strings.multiple')" label="Status" v-model="newRecord.status" disabled)
                  vm-select-item(:key="index" :value="item.value" :text="item.text" v-for="(item,index) in status")
          vm-tabs
            vm-tab(vm-label="Details" vm-alignment="fixed")
              vm-table(multiple v-model="selected"  max-height="350px" :data="newRecord.details")
                template(slot="header")
                  .d-flex.justify-content-between
                    div
                    div
                      vm-tooltip(:text="$t('strings.addDetail')" delay=".5s")
                        vm-button(size="small" icon="plus" @click="addPurchaseOrderDetail")
                template(slot="thead")
                  vm-th(:key="index" v-if="column !== 'id'" v-for="(column, index) in columns") \{{ $t('purchase_orders.' + column) }}
                  vm-th
                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]}}
                      slot(v-if="column == 'status'") \{{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="editPurchaseOrderDetail(data[indextr], indextr)")
                          vm-icon(icon="edit-2-outline")
                          slot &nbsp;\{{ $t('strings.edit') }}
                        vm-dropdown-item.d-flex.justify-content-between(@click="deletePurchaseOrderDetailConfirm(data[indextr], indextr)")
                          vm-icon(icon="trash-2-outline")
                          slot &nbsp;\{{ $t('strings.delete') }}
                        //- More actions
              vm-row(vm-align="flex-end" vm-type="flex" vm-justify="flex-end" vm-w="12")
                vm-col(vm-w=6)
                  vm-row(vm-align="flex-end" vm-type="flex" vm-justify="flex-end" style="text-align: right;")
                    vm-col
                      b Subtotal:&nbsp;&nbsp;
                      span(style="font-size: 1.4rem;") \{{ subtotal | currency }}
                  vm-row(vm-align="flex-end" vm-type="flex" vm-justify="flex-end" style="text-align: right;")
                    vm-col
                      b Total:&nbsp;&nbsp;
                      span(style="font-size: 1.4rem;") \{{ total | currency }}
    transition(name="enter")
      .footer(v-if="enabledSave && !$v.newRecord.$invalid")
        vm-button(type="flat" text-color="#fff" color="rgb(190, 142, 241)" @click="cancel") \{{ $t('strings.cancel') }}
        vm-button(type="default" @click="saveRecord") \{{ $t('strings.save') }}
</template>

<script>
// import ModalPurchaseOrdersProp from '@/components/modals/ModalPurchaseOrdersProp.vue'
import ModalPurchaseOrdersDetail from '@/components/modals/ModalPurchaseOrdersDetail.vue'
import { required, numeric } from 'vuelidate/lib/validators' // Ver documentacion
import parseDeleteMany from '@/utils/parseDeleteMany'
import { createNamespacedHelpers } from 'vuex'
const { mapGetters, mapActions } = createNamespacedHelpers('PurchaseOrders')

export default {
  name: 'PurchaseOrdersDetail',
  components: {
    ModalPurchaseOrdersDetail
  },
  props: {
    isAdd: {
      default: false,
      type: Boolean
    }
  },
  data: () => ({
    newRecord: {
      status: 1,
      details: []
    },
    isModalAdd: true,
    detail: {},
    index: 0,
    selected: [],
    enabledSave: false,
    columns: [
      'id',
      'quantity',
      'unit_price',
      'total'
    ],
    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'
      }
    ]
  }),
  validations: {
    newRecord: {
      customer_id: {
        required,
        numeric
      }
    }
  },
  async created () {
    this.initPurchaseOrder(this.newRecord)
    this.getCatalog()
    this.$route.params.id && await this.getPurchaseOrder()
  },
  methods: {
    ...mapActions([
      'initPurchaseOrder',
      'addPurchaseOrder',
      'editPurchaseOrder',
      'deletePurchaseOrder',
      'deletePurchaseOrderDetail',
      'deletePurchaseOrderDetails',
      'actionPurchaseOrder',
      'loadPurchaseOrder',
      'loadCatalog',
      'loadCatalogAux',
      'setModalVisible',
      'printReportRecord'
    ]),
    colorStatus (code) {
      return this.status.find(e => e.value === code)['color']
    },
    getTitle () {
      return this.isAdd ? this.$t('purchase_orders.add') : this.$t('purchase_orders.edit')
    },
    addPurchaseOrderDetail () {
      this.isModalAdd = true
      this.setModalVisible(true)
      this.detail = {}
    },
    editPurchaseOrderDetail (detail, index) {
      this.isModalAdd = false
      this.setModalVisible(true)
      this.detail = { ...detail }
      this.index = index
    },
    async saveRecord () {
      if (!this.enabledSave) return
      this.enabledSave = false
      let t = this
      this.$vm.loading({
        background: 'primary',
        color: '#fff',
        container: '#saveRecord',
        scale: 0.45
      })
      await this.isAdd ? this.addPurchaseOrder(this.newRecord).then(() => { t.$router.push({ name: 'purchaseOrders' }) }) : this.editPurchaseOrder(this.newRecord).then(() => { t.$router.push({ name: 'purchaseOrders' }) })
    },
    async deletePurchaseOrderConfirm (purchaseOrder) {
      let t = this
      this.auxDeletePurchaseOrder = () => {
        t.deletePurchaseOrder(purchaseOrder).then(() => {
          t.$router.push({ name: 'purchaseOrders' })
        })
      }
      this.$vm.dialog({
        color: 'danger',
        title: this.$t('front.delete_modal'),
        text: this.$t('front.delete_confirmation', { model: this.$t('strings.purchase_order'), attribute: this.$t(purchaseOrder.folio) }),
        accept: this.auxDeletePurchaseOrder
      })
    },
    async deletePurchaseOrderDetailConfirm (detail, index) {
      let t = this
      this.auxDeletePurchaseOrderDetail = () => {
        t.deletePurchaseOrderDetail({ detail, index }).then(() => { t.selected = [] })
      }
      this.$vm.dialog({
        color: 'danger',
        title: this.$t('front.delete_modal'),
        text: this.$t('front.delete_confirmation', { model: this.$t('strings.purchase_order'), attribute: detail.id ? detail.id : index }),
        accept: this.auxDeletePurchaseOrderDetail
      })
    },
    async deletePurchaseOrderDetailsConfirm () {
      let t = this
      let purchaseOrdersMany = parseDeleteMany(this.selected, 'id')
      this.auxDeletePurchaseOrderDetail = () => {
        t.deletePurchaseOrderDetails(purchaseOrdersMany).then(() => { t.selected = [] })
      }
      this.$vm.dialog({
        color: 'danger',
        title: this.$t('front.delete_modal'),
        text: this.$t('front.delete_confirmation', { model: this.$t('strings.purchase_order'), attribute: purchaseOrdersMany.indexes }),
        accept: this.auxDeletePurchaseOrderDetail
      })
    },
    async setActionPurchaseOrder (record, action) {
      let t = this
      this.auxActionPurchaseOrder = () => {
        t.actionPurchaseOrder({ id: record.id, action })
      }
      this.$vm.dialog({
        color: 'warning',
        title: this.$t('strings.purchase_order'),
        text: this.$t('front.action_confirmation', { model: this.$t('strings.purchase_order'), action: this.$t('purchase_orders.' + action) }),
        accept: this.auxActionPurchaseOrder
      })
    },
    async getPurchaseOrder () {
      this.loadPurchaseOrder(this.$route.params)
    },
    async getCatalog () {
      Object.keys(this.purchaseOrdersCatalog).forEach(e => this.loadCatalog({ url: e, filter: '' }))
    },
    getCatalogAux () {
      Object.keys(this.purchaseOrdersCatalog).forEach(e => {
        let arr = []
        Object.keys(this.newRecord).forEach(d => {
          if (e === d) {
            arr.push({ ...this.newRecord[d] })
            this.loadCatalogAux({ url: e, data: arr })
          }
        })
        arr = []
        this.newRecord.details.map(d => {
          let dd = { ...d }
          Object.keys(dd).forEach(f => {
            let concat = `${f}s`
            if (e === concat) {
              arr.push({ ...dd[f] })
              this.loadCatalogAux({ url: e, data: arr })
            }
          })
        })
      })
    },
    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
    },
    cancel () {
      this.$router.push({ name: 'purchaseOrders' })
    }
  },
  computed: {
    ...mapGetters([
      'purchaseOrder',
      'purchaseOrdersCatalog'
    ]),
    detailsList () {
      // let t = this
      return this.newRecord.details.map(detail => {
        return detail
      })
    },
    detailsLength () {
      return this.newRecord.details.length
    },
    enabledEdit () {
      return this.newRecord.id
    },
    subtotal () {
      return this.newRecord.details.reduce((prev, cur) => prev + parseFloat(cur.total), 0).toFixed(2)
    },
    total () {
      let iva = parseFloat(this.subtotal) * 0.16
      return (parseFloat(this.subtotal) + iva).toFixed(2)
    }
  },
  watch: {
    newRecord (record) {
      Object.keys(record).length > 2 ? this.enabledSave = true : this.enabledSave = false
    },
    purchaseOrder (purchaseOrder) {
      this.newRecord = { ...purchaseOrder }
      this.getCatalogAux()
    },
    'purchaseOrder.details' (details) {
      this.newRecord.details = []
      details.map(e => this.newRecord.details.push({ ...e }))
    }
  }
}
</script>

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