<template>
  <div :class="$style.dropdownAeros" :style="'width: ' + width">
    <div
      :class="[
        $style.headerSelect,
        { errorNotice: errorValid, disabledStyle: disabled }
      ]"
      @click="toogleVisible"
    >
      <div :class="[$style.nameAero, { disabledStyle: disabled }]">
        <div v-text="value ? value[label] || value : ''"></div>
        <div
          :class="$style.placeholder"
          v-if="value == null || value === ''"
          v-html="placeholderHeading"
        ></div>
      </div>
      <div :class="$style.iconsDinamic">
        <i class="icon-arrow-up22" v-if="visible === true"></i>
        <i v-else class="icon-arrow-down22"></i>
      </div>
    </div>
    <transition name="fadeHeight" mode="out-in">
      <div :class="$style.listsAbsolute" v-show="visible">
        <div
          :class="$style.search"
          v-if="searchVisible && loadDataServer == false"
        >
          <div :class="$style.iconSearch">
            <i class="saglan-icon-search"></i>
          </div>
          <input
            ref="input"
            type="text"
            v-model="searchQuery"
            :placeholder="placeholderSearch"
            :class="$style.inputSearch"
            @click.stop
          />
        </div>
        <div :class="$style.search" v-if="searchVisible && loadDataServer">
          <div :class="$style.iconSearch">
            <i
              :class="[
                loadElementsServer
                  ? 'icon-spinner3 spinner position-left'
                  : 'saglan-icon-search'
              ]"
            ></i>
          </div>
          <input
            ref="input"
            type="text"
            v-model="valueServerText"
            :placeholder="placeholderSearch"
            :class="$style.inputSearch"
            @click.stop
            @input="textoTimer"
          />
        </div>
        <ul
          :class="[
            $style.listsItems,
            { scrollCondition: countItems.length >= limitItemsScroll }
          ]"
        >
          <li
            v-for="(element, index) in (elements, resultQuery)"
            :key="index"
            @click="itemCliked(index)"
            :class="{ isActive: element === value }"
            v-html="element[label] || element"
          ></li>
        </ul>
      </div>
    </transition>
  </div>
</template>
<script>
export default {
  props: {
    elements: {
      type: [Object, Array]
    },
    placeholderHeading: {
      type: String,
      default: "Título"
    },
    placeholderSearch: {
      type: String,
      default: "Búsqueda"
    },
    label: {
      type: String,
      default: "name"
    },
    value_select: {
      type: String,
      default: "value"
    },
    filterby: {
      type: String,
      default: "name"
    },
    searchVisible: {
      type: Boolean,
      default: true
    },
    limitItemsScroll: {
      type: Number,
      default: 8
    },
    indexSelected: {
      type: Number,
      default: null
    },
    value: {
      type: [Object, Array, String, Number],
      default: null
    },
    errorValid: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: "100%"
    },
    loadDataServer: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectedItem: null,
      visible: false,
      searchQuery: "",
      countItems: 0,
      valueServerText: "",
      timer: null,
      loadElementsServer: false
    };
  },
  watch: {
    value(antes, ahora) {
      if (antes == ahora) {
        console.log(antes, ahora);
        this.buscarItem();
      }
    },
    elements(array) {
      if (this.loadDataServer) {
        console.log(array, "elements");
        this.loadElementsServer = false;
      }
    }
  },
  mounted() {
    if (this.elements != null) {
      this.countItems = this.elements;
    }
    if (this.indexSelected != null) {
      this.itemCliked(this.indexSelected);
    }
    this.buscarItem();
  },
  methods: {
    textoTimer() {
      this.loadElementsServer = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(this.buscarItemServer, 1000);
    },
    buscarItemServer() {
      this.$emit("inputServer", this.valueServerText);
    },
    buscarItem() {
      let these = this;
      if (this.value != null) {
        this.elements.forEach((item, i) => {
          let keys = Object.keys(item);
          keys.forEach(key => {
            if (these.filterby != key) {
              if (
                item[key] == these.value ||
                item[key] == these.value[these.value_select]
              ) {
                these.itemCliked(i);
              }
            }
          });
        });
      }
    },
    toogleVisible() {
      if (!this.disabled) {
        this.visible = !this.visible;
        if (this.searchVisible !== false) {
          setTimeout(() => {
            this.$refs.input.focus();
          }, 50);
        }
        setTimeout(
          () => document.addEventListener("click", this.hideToogle),
          0
        );
      }
    },
    itemCliked(index) {
      this.selected = index;
      this.selectItem();
    },
    selectItem() {
      if (!this.resultQuery.length) {
        return;
      }
      //this.selectedItem = this.resultQuery[this.selected];
      //this.value = this.resultQuery[this.selected]
      this.$emit("input", this.resultQuery[this.selected]);
      this.visible = false;
      if (this.shouldReset) {
        this.query = "";
        this.selected = 0;
      }
    },
    hideToogle() {
      this.visible = false;
      setTimeout(() => document.removeEventListener("click", this.hideToogle));
    }
  },
  computed: {
    resultQuery() {
      if (this.searchQuery) {
        return this.elements.filter(elm => {
          return this.searchQuery
            .toLowerCase()
            .split(" ")
            .every(v => elm[this.filterby].toLowerCase().includes(v));
        });
      } else {
        return this.elements;
      }
    }
  }
};
</script>

<style lang="css">
.fadeHeight-enter-active,
.fadeHeight-leave-active {
  transition: all 0.2s;
}
.fadeHeight-enter,
.fadeHeight-leave-to {
  opacity: 0;
}

.isActive {
  background-color: #f2f2f2;
}

.scrollCondition {
  overflow: hidden !important;
  overflow-y: scroll !important;
}

.errorNotice {
  border: solid 1px #f79483 !important;
}

.disabledStyle {
  color: #b0b0b0 !important;
  cursor: not-allowed !important;
}
</style>

<style lang="scss" module>
.dropdownAeros {
  position: relative;
  .headerSelect {
    width: 100%;
    height: 36px;
    border-radius: 3px;
    border: solid 1px #dddddd;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-direction: row;
    &:hover {
      cursor: pointer;
    }

    .nameAero {
      padding: 7px 10px;
      /*font-size: 13px;*/
      width: 100%;

      .placeholder {
        color: #aaaaaa;
        /*font-size: 13px;*/
      }
    }
    .iconsDinamic {
      padding: 6px 10px;
      text-align: center;
      & i {
        font-size: 16px;
        position: relative;
      }
      &:hover {
        cursor: pointer;
      }
    }
  }
  .listsAbsolute {
    position: absolute;
    background-color: #ffffff;
    border: solid 1px #dddddd;
    border-bottom-left-radius: 3px;
    border-bottom-right-radius: 3px;
    box-shadow: 0 15px 30px 10px rgba(0, 0, 0, 0.08);
    width: 100%;
    z-index: 2;
    top: 35px;

    .search {
      position: relative;
      display: flex;
      align-items: inherit;
      justify-content: space-between;
      flex-direction: column;
      border-bottom: solid 1px #dddddd;
      .iconSearch {
        position: absolute;
        left: 20px;
        top: 15px;
        & i {
          font-size: 13px;
          color: #666666;
        }
      }
      .inputSearch {
        border: solid 1px #dddddd;
        border-radius: 3px;
        padding: 7px 10px 7px 25px;
        outline: none;
        margin: 10px 13px;
      }
    }

    .listsItems {
      list-style: none;
      padding: 0;
      margin: 0;
      max-height: 320px;
      overflow: scroll;
      li {
        padding: 10px;
        border-bottom: solid 1px #dddddd;
        transition: all ease 0.3s;
        font-size: 13px;
        &:hover {
          background-color: #f2f2f2;
          cursor: pointer;
        }
        &:last-child {
          border-bottom: none;
        }
      }
    }
  }
}
</style>
