<template>
  <div :class="$style.dropdownContent">
    <div
      :class="[$style.inputSearch, disabled ? $style.disabledStyle : '']"
      @click="openLists"
    >
      <input
        type="text"
        v-bind:readonly="isReadOnly"
        autocomplete="off"
        :class="[
          { errorNotice: noticeError },
          disabled ? $style.disabledStyle : ''
        ]"
        :placeholder="placeholderHeading"
        v-model="selectedName"
      />
      <div
        :class="[
          $style.iconRotate,
          disabled ? $style.disabledStyle : '',
          { errorNotice: noticeError }
        ]"
      >
        <i class="saglan-icon-up" v-if="showListsSearch"></i>
        <i v-else class="saglan-icon-down"></i>
      </div>
    </div>
    <transition name="fadeHeight">
      <div :class="$style.optionsLists" v-if="showListsSearch" @click.stop>
        <ul>
          <div v-if="searchVisible" :class="$style.inputFilter">
            <div :class="$style.iconSearch">
              <i class="saglan-icon-search"></i>
            </div>
            <input
              ref="input"
              type="text"
              autocomplete="off"
              :placeholder="placeholderSearch"
              v-model="searchQuery"
              :class="$style.input"
            />
          </div>
          <div
            v-if="resultQuery.length > 0 && showAll"
            :class="$style.optionAll"
          >
            <input
              type="checkbox"
              id="todos"
              value="todos"
              name="todos"
              @click="checkAll()"
              v-model="isCheckAll"
              @change="dispatchListsSelected"
            />
            <label for="todos">Todos</label>
          </div>
          <li v-for="(element, index) in (elements, resultQuery)" :key="index">
            <input
              type="checkbox"
              :id="element[filterBy]"
              :value="element"
              :name="element[filterBy]"
              v-model="selected"
              @change="dispatchListsSelected"
            />
            <label :for="element[filterBy]" v-html="element[filterBy]"></label>
          </li>
          <div :class="$style.disclaimer" v-if="resultQuery.length <= 0">
            <small v-html="noItems"></small>
          </div>
        </ul>
        <div
          @click="showListsSearch = !true"
          v-if="resultQuery.length > 0"
          :class="$style.returnTop"
        >
          <i class="saglan-icon-up"></i>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: "DropdownMultiSelect",
  props: {
    elements: {
      type: Array,
      required: true
    },
    filterBy: {
      type: String,
      default: "name"
    },
    searchVisible: {
      type: Boolean,
      default: true
    },
    placeholderHeading: {
      type: String,
      default: "Ingresar Texto"
    },
    placeholderSearch: {
      type: String,
      default: "Buscar..."
    },
    noItems: {
      type: String,
      default: "Sin resultados"
    },
    allSelect: {
      type: Boolean,
      default: true
    },
    showAll: {
      type: Boolean,
      default: true
    },
    value: {
      type: [Number, String, Array],
      default: null
    },
    noticeError: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isReadOnly: true,
      selected: [],
      selectedName: "",
      isCheckAll: false,
      searchQuery: "",
      showListsSearch: false
    };
  },
  watch: {
    value(val) {
      // console.log(val);
      if (val != null) {
        this.selected = val;
        this.dispatchListsSelected();
      }
    }
  },
  mounted() {
    if (this.allSelect == true) {
      const self = this;
      setTimeout(function() {
        self.checkAll();
        self.dispatchListsSelected();
      }, 1000);
    }

    if (this.value != null) {
      this.selected = this.value;
      this.dispatchListsSelected();
    }
  },
  methods: {
    openLists() {
      console.log("openLists", this.disabled);
      if (!this.disabled) {
        this.showListsSearch = !this.showListsSearch;
        if (this.showListsSearch === true) {
          if (this.searchVisible !== false) {
            setTimeout(() => {
              this.$refs.input.focus();
            }, 100);
          }
        }
        setTimeout(
          () => document.addEventListener("click", this.hideToogle),
          0
        );
      }
    },
    dispatchListsSelected() {
      this.selectedName = "";
      const listSlugAero = [];

      // console.log(this.selected);

      this.selected.forEach(item => {
        listSlugAero.push(item.label);
      });

      if (this.selected.length === 0) {
        this.isCheckAll = false;
      }
      // 07/12/2020: @Andres: Se modifica para agregar una coma y espacio como separador.
      let selectedNameArray = [];
      this.selected.forEach(element => {
        selectedNameArray.push(element[this.filterBy]);
      });
      if (selectedNameArray.length > 0) {
        //console.log(this.elements.length, selectedNameArray.length);
        if (this.elements.length == selectedNameArray.length) {
          this.selectedName = "Todos";
        } else {
          this.selectedName = selectedNameArray.join(", ");
        }
      } else {
        this.selectedName = "";
      }

      this.$emit("input", this.selected);
    },
    checkAll() {
      this.isCheckAll = !this.isCheckAll;
      this.selected = [];
      this.selectedName = "";
      if (this.isCheckAll) {
        for (let key in this.elements) {
          this.selected.push(this.elements[key]);
        }
      }

      this.$emit("input", this.selected);
    },
    hideToogle() {
      this.showListsSearch = 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">
.errorNotice {
  border: solid 1px #f79483 !important;
}
</style>

<style lang="scss" module>
.disabledStyle {
  /*opacity: 0.7;*/
  color: #b0b0b0 !important;
  cursor: not-allowed !important;
}
.dropdownContent {
  height: 36px;
  position: relative;

  .inputSearch {
    position: relative;
    width: 100%;
    input {
      outline: none;
      width: 100%;
      /*font-size: 13px;*/
      border-radius: 3px;
      padding: 7px 10px;
      border: solid 1px #dddddd;
      color: #333333;
      height: 36px;
      padding-right: 40px;
      &:hover {
        cursor: pointer;
      }
    }
    .iconRotate {
      height: 100%;
      position: absolute;
      right: 0;
      top: 0;
      padding: 9px 11px 5px 11px;
      background-color: transparent;
      border-top-right-radius: 3px;
      border-left: 1px solid #dddddd;
      &:hover {
        cursor: pointer;
      }
      i {
        font-size: 11px;
      }
    }
  }

  .optionsLists {
    background-color: #ffffff;
    border: solid 1px #dddddd;
    border-bottom-left-radius: 3px;
    border-bottom-right-radius: 3px;
    border-top: none;
    box-shadow: 0 15px 30px 10px rgba(0, 0, 0, 0.08);
    z-index: 2;
    position: relative;

    .optionAll {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex-direction: row;

      label {
        margin-left: 10px;
        margin-bottom: 0;
        &:hover {
          cursor: pointer;
        }
      }
      @extend .classListsDropdopwn;
      @extend .classCheck;
    }
    ul {
      list-style: none;
      padding: 0;
      margin: 0;
      max-height: 320px;
      overflow: hidden;
      overflow-y: scroll;
      li {
        @extend .classListsDropdopwn;
        display: flex;
        align-items: center;
        label {
          font-size: 13px;
          margin-left: 10px;
          width: 100%;
          margin-bottom: 0;
          &:hover {
            cursor: pointer;
          }
        }

        @extend .classCheck;
      }

      .inputFilter {
        padding: 10px;
        border-bottom: solid 1px #dddddd;
        position: relative;
        input {
          width: 100%;
          font-size: 13px;
          border: solid 1px #dddddd;
          outline: none;
          padding: 7px 10px 7px 30px;
          border-radius: 3px;
        }
        .iconSearch {
          position: absolute;
          left: 20px;
          top: 15px;
          & i {
            font-size: 13px;
            color: #666666;
          }
        }
      }

      .disclaimer {
        padding: 10px;
        text-align: center;
        small {
          font-size: 12px;
        }
      }
    }
    .returnTop {
      background-color: #336b87;
      position: absolute;
      right: 20px;

      bottom: 11px;
      padding: 2px 10px 4px 10px;
      border-radius: 3px;
      i {
        font-size: 10px;
        color: #ffffff;
      }
      &:hover {
        cursor: pointer;
      }
    }
  }
}

.classListsDropdopwn {
  padding: 10px;
  border-bottom: solid 1px #dddddd;
  transition: all ease 0.3s;
  font-size: 13px;
  &:hover {
    background-color: #f2f2f2;
    cursor: pointer;
  }
}

.classCheck {
  input[type="checkbox"] {
    position: relative;
    width: 1.5em;
    height: 1.5em;
    color: #000;
    border: 1px solid #dddddd;
    border-radius: 3px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    outline: 0;
    cursor: pointer;
    margin: 0;
    transition: background 175ms cubic-bezier(0.1, 0.1, 0.25, 1);
    &:checked {
      color: #fff;
      border-color: #336b87;
      background: #336b87;
      outline: none;

      &:before {
        opacity: 1;
      }
    }

    &:before {
      outline: none;
      position: absolute;
      content: "";
      display: block;
      top: 4px;
      left: 6px;
      width: 5px;
      height: 9px;
      border-style: solid;
      border-color: #fff;
      border-width: 0 2px 2px 0;
      transform: rotate(45deg);
      opacity: 0;
    }
  }
}
</style>

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