<template>
  <div id="pageActionscomponent" class="row q-col-gutter-y-sm full-width items-center justify-between">
    <!--Title-->
    <div :class="`row text-primary text-weight-bold ellipsis title-content items-center`">
      <q-icon v-if="icon" :name="icon" size="22px" class="q-mr-sm"/>
      <label id="titleCrudTable" v-if="title">{{ title }}</label>
      <!--Help Text: Page documentation-->
      <help-text v-if="pageDocumentation && title" v-bind="pageDocumentation"/>
    </div>
    <!--Actions-->
    <div :class="`actions-content row q-gutter-${gutter} items-center justify-end items-start`">
      <!--Search-->
      <q-input v-model="search" bg-color="white" debounce="800" rounded outlined dense clearable
               :placeholder="$tr('isite.cms.label.search')" class="page-input-search"
               v-if="extraActions && extraActions.includes('search') && searchAction"
               @input="$emit('search', $clone(search))">
        <template v-slot:prepend>
          <q-icon color="tertiary" size="xs" name="fa-duotone fa-magnifying-glass"/>
        </template>
      </q-input>
      <!--Button Actions-->
      <div v-for="(btn, keyAction) in actions" :key="keyAction">
        <!-- if the button is dropdown -->
        <q-btn-dropdown split v-bind="{...buttonProps}"
                        v-if="btn.type == 'btn-dropdown'" outline
        >
          <template v-slot:label>
            <div class="row items-center no-wrap" @click="refreshByTime(timeRefresh)">
              <q-icon left :name="btn.props.icon"/>
              <div class="text-center" v-if="multipleRefresh">
                {{ titleRefresh }}
              </div>
            </div>
          </template>
          <q-list>
            <q-item v-for="(item, index) in btn.items" :key="index" clickable v-close-popup
                    @click="item.action != undefined ? item.action() : null" class="tw-px-4">
              <q-item-section avatar v-if="item.icon">
                <q-avatar :icon="item.icon"/>
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ item.label }}</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>
        <q-btn v-else-if="btn.type === 'recommendation'" class="animated" v-bind="{...buttonProps, ...btn.props}"
               @click="btn.action !=    undefined ? btn.action() : null">
          <q-tooltip v-if="btn.label">{{ btn.label }}</q-tooltip>
        </q-btn>
        <q-btn v-else v-bind="{...buttonProps, ...btn.props}" @click="btn.action != undefined ? btn.action() : null">
          <q-tooltip v-if="btn.label">{{ btn.label }}</q-tooltip>
        </q-btn>
      </div>
    </div>
    <!--Description-->
    <div v-if="description" class="ellipsis-2-lines col-12 description-content">{{ description }}</div>
    <!--Filter data-->
    <div class="col-12 tw-mt-3" v-if="filter.hasValues || Object.keys(quickFilters).length">
      <!--<q-separator class="q-mb-sm"/>-->
      <div class="text-blue-grey ellipsis text-caption items-center row">
        <q-icon name="fa-light fa-filter" class="q-mr-xs" color="amber" size="18px"/>
        <b>{{ $trp('isite.cms.label.filter') }}:</b>
        <label
            v-for="(item, itemKey) in filter.readValues"
            :key="itemKey"
            v-if="item.value && item.label !== ''"
            class="q-ml-xs text-grey-7">
          {{ item.label }} {{ item.value }},
        </label>
      </div>
      <!-- Quick Filters-->
      <div v-if="Object.keys(quickFilters).length" class="row q-col-gutter-md q-pt-sm">
        <dynamic-field v-for="(field, keyField) in quickFilters" :key="keyField" :field="field"
                       v-model="filterData[keyField]"
                       :class="field.colClass"
                       @input="emitFilter"
                       :keyField="keyField"
        />
      </div>
    </div>
    <!-- Export Component -->
    <master-export v-model="exportParams" ref="exportComponent"/>
  </div>
</template>
<script>
//Components
import masterExport from "@imagina/qsite/_components/master/masterExport"

export default {
  beforeDestroy() {
    this.clearInterval();
    this.$root.$off('page.data.filter.read')
  },
  props: {
    title: {type: String},
    description: {type: String},
    icon: {type: String},
    gutter: {type: String, default: 'sm'},
    size: {type: String, default: 'small'},
    extraActions: {type: Array},
    excludeActions: {default: false},
    searchAction: {default: true},
    multipleRefresh: {
      type: Boolean,
      default: () => false,
    },
    tourName: {default: null}
  },
  components: {masterExport},
  watch: {},
  mounted() {
    this.$nextTick(function () {
      this.init()
    })
  },
  data() {
    return {
      exportParams: false,
      search: null,
      filterData: {},
      refreshIntervalId: null,
      titleRefresh: this.$tr('isite.cms.label.refreshAtOnce'),
      timeRefresh: 0
    }
  },
  computed: {
    //Return filter data
    filter() {
      this.filterData = this.$clone(this.$filter.values)
      return this.$filter
    },
    //Return params of subHeader
    params() {
      return this.$clone(this.$route.meta.subHeader || {})
    },
    //Button default props
    buttonProps() {
      return {
        round: false,
        rounded: true,
        dense: true,
        unelevated: true,
        color: "primary",
        class: `btn-${this.size}`,
        outline: true,
        noCaps: true,
      }
    },
    //Page Actions
    actions() {
      //Instance excludeActions prop
      let excludeActions = this.$clone(Array.isArray(this.excludeActions) ? this.excludeActions : [])

      let response = [
        //Export
        {
          label: this.$tr('isite.cms.label.export'),
          vIf: (this.exportParams && !excludeActions.includes('export')),
          props: {
            icon: 'fa-duotone fa-file-arrow-down'
          },
          action: () => this.$refs.exportComponent.showReport()
        },
        //Tour
        {
          label: 'Tour',
          vIf: (this.tourName && !config("app.disableTours")),
          props: {
            icon: 'fa-duotone fa-shoe-prints',
            id: 'actionStartTour'
          },
          action: () => this.startTour(true)
        },
        //recommendations
        {
          type: 'recommendation',
          label: this.$trp('isite.cms.label.recommendation'),
          vIf: (this.params.recommendations && !excludeActions.includes('recommendations')) ? true : false,
          props: {
            icon: 'fas fa-hat-wizard'
          },
          action: () => this.$eventBus.$emit('toggleMasterDrawer', 'recommendation')
        },
        //Filter
        {
          label: this.$tr('isite.cms.label.filter'),
          vIf: (this.filter.load && !excludeActions.includes('filter')),
          props: {
            icon: 'fa-duotone fa-filter',
            id: 'filter-button-crud',
          },
          action: () => this.$eventBus.$emit('toggleMasterDrawer', 'filter')
        },
        //Refresh
        {
          label: this.$trp('isite.cms.label.refresh'),
          type: this.multipleRefresh ? 'btn-dropdown' : '',
          vIf: (this.params.refresh && !excludeActions.includes('refresh')),
          props: {
            icon: 'fa-duotone fa-rotate-right',
            id: 'refresh-button-crud'
          },
          items: [
            {
              label: this.$tr('isite.cms.label.refreshAtOnce'),
              action: () => this.refreshByTime(0)
            },
            {
              label: this.$tr('isite.cms.label.refreshEveryMinutes', {min: 1}),
              action: () => this.refreshByTime(1)
            },
            {
              label: this.$tr('isite.cms.label.refreshEveryMinutes', {min: 5}),
              action: () => this.refreshByTime(5)
            },
            {
              label: this.$tr('isite.cms.label.refreshEveryMinutes', {min: 10}),
              action: () => this.refreshByTime(10)
            },
            {
              label: this.$tr('isite.cms.label.refreshEveryMinutes', {min: 15}),
              action: () => this.refreshByTime(5)
            }
          ],
          action: this.emitRefresh,
        }
      ]

      //Validate extra actions
      if (this.extraActions) {
        //Prepend actions
        response = [...this.extraActions.filter(action => typeof action != 'string'), ...response]
        //New button action
        if (this.extraActions.includes('new'))
          response.unshift({
            vIf: this.params.create && this.params.hasPermission.create,
            props: {
              label: this.$tr(`isite.cms.label.new`),
              icon: 'fa-duotone fa-plus',
              color: "primary",
              round: false,
              rounded: true,
              padding: '3px 15px',
              id: 'new-button-crud'
            },
            action: () => this.$emit('new')
          })
      }

      //Response
      return response.filter(item => item.vIf !== undefined ? item.vIf : true)
    },
    //Quick filters
    quickFilters() {
      var response = {}
      //Get quick filters
      if (this.$q.platform.is.desktop) {
        Object.keys(this.filter.fields).forEach(fieldName => {
          var fieldfilter = this.filter.fields[fieldName]
          if (fieldfilter.quickFilter) {
            response[fieldName] = {
              ...fieldfilter,
              colClass: "col-12 col-md-4 col-xl-3"
            }
            if (!this.filterData[fieldName]) this.$set(this.filterData, fieldName, fieldfilter.value || null)
          }
        })
      }
      //Response
      return response
    },
    //Page Documentation
    pageDocumentation() {
      let response = null
      //Get params from page permission
      let params = this.$helper.getInfoFromPermission(this.$route.meta.permission)
      if (params) {
        //instance the config name
        let configName = `${params.module}.documentation.${params.entity}`
        //Search the config
        response = this.$store.getters['qsiteApp/getConfigApp'](configName)
      }
      //Response
      return !response ? null : {
        title: this.title,
        description: response,
        icon: this.$route.meta.icon,
        class: 'q-ml-sm'
      }
    }
  },
  methods: {
    init() {
      this.$root.$on('page.data.filter.read', (readValues) => {
        this.$set(this.filter, 'readValues', readValues)
      })
    },
    refreshByTime(time) {
      this.timeRefresh = time;
      this.titleRefresh = time === 0
          ? this.$tr('isite.cms.label.refreshAtOnce')
          : this.$tr('isite.cms.label.refreshEveryMinutes', {min: time});
      this.clearInterval();
      const interval = 1000 * 60 * time;
      this.emitRefresh();
      if (time > 0) {
        this.refreshIntervalId = setInterval(() => {
          this.emitRefresh();
        }, interval);
      }
    },
    //Emit refresh
    emitRefresh() {
      this.$emit('refresh')
      this.$root.$emit('page.data.refresh')
      this.$root.$emit('crud.data.refresh')
      this.$root.$emit('export.data.refresh')
    },
    //Emit filter
    emitFilter() {
      //Add Values
      this.$filter.addValues(this.filterData)
      //Call back
      if (this.filter && this.filter.callBack) this.filter.callBack(this.filter)
    },
    clearInterval() {
      if (this.refreshIntervalId) {
        clearInterval(this.refreshIntervalId);
        this.refreshIntervalId = null;
      }
    },
    //Handle start tour
    startTour(forceStart) {
      this.$tour.start(this.tourName, {
        forceStart,
        extraSteps: [
          {
            icon: 'fa-duotone fa-shoe-prints',
            title: this.$tr('igamification.cms.activities.repeatAction'),
            content: this.$tr('igamification.cms.activities.repeatActionDescription'),
            element: '#actionStartTour',
            position: 'top',
          }
        ]
      })
    }
  }
}
</script>
<style lang="stylus">
#pageActionscomponent
  #titleCrudTable
    font-size 20px

  .animated {
    animation: ring 10s .7s ease-in-out infinite;
  }

  .title-content
    @media screen and (max-width: $breakpoint-md)
      text-align center
      width 100%

  .actions-content
    .q-field__append .q-icon
      color: $tertiary
    @media screen and (max-width: $breakpoint-md)
      width 100%

  .description-content
    line-height 1
    color $grey-8
    font-size 14px

  .page-input-search
    @media screen and (max-width: $breakpoint-md)
      width 100%

    .q-field__control, .q-field__control:after, .q-field__control-container, .q-field__append
      //min-height 34px
      //max-height 34px
    .q-field__control, .q-field__prepend, .q-field__append
      height: 34px

  #dynamicFieldComponent
    .q-field.q-field--float .q-field__label
      color: $primary

    .q-field__control
      .q-field__append .q-icon
        color: $tertiary

      .q-field__append:last-child .q-icon
        color: $primary

.q-menu
  .q-list
    .q-item
      padding: 3px 10px 3px 3px;

      .q-item__section--avatar
        min-width: 50px;
        padding-right 10px
        color $primary

        i
          font-size 16px

@keyframes ring {
  0% {
    transform: rotate(0);
  }
  1% {
    transform: rotate(30deg);
  }
  3% {
    transform: rotate(-28deg);
  }
  5% {
    transform: rotate(34deg);
  }
  7% {
    transform: rotate(-32deg);
  }
  9% {
    transform: rotate(30deg);
  }
  11% {
    transform: rotate(-28deg);
  }
  13% {
    transform: rotate(26deg);
  }
  15% {
    transform: rotate(-24deg);
  }
  17% {
    transform: rotate(22deg);
  }
  19% {
    transform: rotate(-20deg);
  }
  21% {
    transform: rotate(18deg);
  }
  23% {
    transform: rotate(-16deg);
  }
  25% {
    transform: rotate(14deg);
  }
  27% {
    transform: rotate(-12deg);
  }
  29% {
    transform: rotate(10deg);
  }
  31% {
    transform: rotate(-8deg);
  }
  33% {
    transform: rotate(6deg);
  }
  35% {
    transform: rotate(-4deg);
  }
  37% {
    transform: rotate(2deg);
  }
  39% {
    transform: rotate(-1deg);
  }
  41% {
    transform: rotate(1deg);
  }

  43% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(0);
  }
}
</style>
