<template>
  <div class="row form-group" :key="$attrs.key">
    <label :for="localFormElement.key" :class="$attrs.labelClass ?? 'col-md-3'"
      >{{ localFormElement.label }}:</label
    >

    <label>{{ tagSelected }}</label>
    <multiselect
    class="multiselect-tag-list"
    v-model="textValue"
    :id="localFormElement.key"
    :placeholder="localFormElement.placeholder"
    :options="listOptions"
    :searchable="true"
    :close-on-select="true"
    :clear-on-select="false"
    :max-height="600"
    :preserve-search="true"
    :multiple="localFormElement?.multi_select ? localFormElement?.multi_select : false"
    selectLabel="✓"
    deselectLabel="✖"
    selectedLabel="اتخاب شد"
    :class="[$attrs.inputClass ?? ' col-md-9', { error: hasError }]"
  >
  </multiselect>
  </div>
</template>

<script>
import formBuilderMixin from "@mixins/formBuilderMixin";
import HttpService from "@services/httpService";

export default {
  mixins: [formBuilderMixin],
  beforeMount() {
    this.httpService = new HttpService();
  },

  mounted() {
    setTimeout(() => {
      this.setOptions();
    }, 1000);
    
  },
  watch: {
    localFormElement: {
      handler(newValue) {
        this.setOptions(newValue);
      }
    },
  },
  data() {
    return {
      httpService: undefined,
      listOptions: [],
      tagSelected: "",
    };
  },

  methods: {
    setOptions(formatEl = undefined) {
      formatEl = formatEl ? formatEl : this.localFormElement;

      //console.log(formatEl)
      if (formatEl?.options) 
          this.listOptions = formatEl?.options;
      else if (formatEl.url_GET) {
        let url = formatEl.url_GET;
        //console.log(this.httpService)

        let vm = this
        this.httpService.getRequest(url).then((res) => {
           //console.log(res)

          vm.listOptions = [];
          res.data.forEach(el => {
            vm.listOptions.push({
                value : el.id,
                title: el.title
            })
          });
           vm.textValue = vm.listOptions.length > 0 ? vm.listOptions[0].title : "";
           vm.objectValue = vm.listOptions.length > 0 ? vm.listOptions[0] : {};
        });
      } else  
        this.listOptions = [];
    },
  },

  components: {
    Multiselect: () =>
      import( "vue-multiselect"),
  },

};
</script>
