<template>
  <div class="vue-component">
     <h2><a name="section-50"></a>{{ $t('social_issue.title') }}</h2>

     <div class="my-4">
        <!--label for="field">{{ $t('social_issue.label') }}</label
        -->
        <VueMultiselect
           name="field"
           :close-on-select="false"
           :allow-empty="true"
           :show-labels="false"
           track-by="id"
           label="text"
           :multiple="true"
           :searchable="true"
           :placeholder="$t('social_issue.label')"
           @update:model-value="updateSocialIssues"
           :model-value="value"
           :options="options">
        </VueMultiselect>
     </div>

  </div>
</template>

<script>
import VueMultiselect from 'vue-multiselect';
import { getSocialIssues } from '../api';
import { mapState } from 'vuex';

export default {
   name: "SocialIssue",
   components: { VueMultiselect },
   data() {
      return {
         options: []
      }
   },
   computed: {
      ...mapState({
         value: state => state.accompanyingCourse.socialIssues,
      }),
   },
   mounted() {
      this.getOptions();
   },
   methods: {
      getOptions() {
         getSocialIssues().then(response => new Promise((resolve, reject) => {
            //console.log('get socialIssues', response.results);
            this.options = response.results;
            resolve();
         })).catch(error => this.$store.commit('catchError', error));
      },
      updateSocialIssues(value) {
         this.$store.dispatch('updateSocialIssues', this.transformValue(value));
      },
      transformValue(updated) {
         let stored = this.value;
         let added = updated.filter(x => stored.indexOf(x) === -1).shift();
         let removed = stored.filter(x => updated.indexOf(x) === -1).shift();
         let method = (typeof removed === 'undefined') ? 'POST' : 'DELETE';
         let changed = (typeof removed === 'undefined') ? added : removed;
         let body = { type: "social_issue", id: changed.id };
         //console.log('body', body);
         //console.log('@@@', method, changed.text);
         let payload = updated;
         return { payload, body, method };
      }
   }
}
</script>

<style src="vue-multiselect/dist/vue-multiselect.css"></style>
<style lang="scss">
   span.multiselect__tag {
      background: var(--bs-chill-orange);
   }
   span.multiselect__option--highlight {
      &::after {
         background: var(--bs-chill-green);
      }
      &.multiselect__option--selected::after {
         background: var(--bs-chill-red);
      }
   }
</style>
