<template>

  <h2>{{ $t('pick_social_issue') }}</h2>


  <div id="awc_create_form">

      <div id="picking">
          <p>{{ $t('pick_social_issue_linked_with_action') }}</p>
          <div v-for="si in socialIssues" :key="si.id">
            <input type="radio" v-bind:value="si.id" name="socialIssue" v-model="socialIssuePicked"><span class="badge bg-chill-l-gray text-dark">{{ si.text }}</span>
          </div>
      <div class="my-3">
        <div class="col-11">
          <vue-multiselect
              name="otherIssues"
              label="text"
              track-by="id"
              open-direction="bottom"
              :close-on-select="true"
              :preserve-search="false"
              :reset-after="true"
              :hide-selected="true"
              :taggable="false"
              :multiple="false"
              :searchable="true"
              :allow-empty="true"
              :show-labels="false"
              :loading="issueIsLoading"
              :placeholder="$t('choose_other_social_issue')"
              :options="socialIssuesOther"
              @select="addIssueInList">
          </vue-multiselect>
        </div>
      </div>
      <div v-if="hasSocialIssuePicked">
        <h2>{{ $t('pick_an_action') }}</h2>
        <div class="col-11">
          <vue-multiselect
            v-model="socialActionPicked"
            label="text"
            :options="socialActionsReachables"
            :searchable="true"
            :close-on-select="true"
            :show-labels="true"
            track-by="id"
          ></vue-multiselect>
        </div>
      </div>

      <div v-if="isLoadingSocialActions">
        <i class="fa fa-circle-o-notch fa-spin fa-fw"></i>
      </div>

      <div v-if="hasSocialActionPicked" id="persons">
        <h2>{{ $t('persons_involved') }}</h2>

        <ul>
          <li v-for="p in personsReachables" :key="p.id">
            <input type="checkbox" :value="p.id" v-model="personsPicked">
            <person-render-box render="badge" :options="{}" :person="p"></person-render-box>
          </li>
        </ul>
      </div>

    </div>
    <div v-if="hasSocialActionPicked" id="start_date">
      <p><label>{{ $t('startDate') }}</label> <input type="date" v-model="startDate" /></p>
    </div>

    <div v-if="hasSocialActionPicked" id="end_date">
      <p><label>{{ $t('endDate') }}</label> <input type="date" v-model="endDate" /></p>
    </div>

    <div id="confirm">
      <div v-if="hasErrors">
        <p>{{ $t('form_has_errors') }}</p>

        <ul>
          <li v-for="e in errors" :key="e.id">
            {{ e }}
          </li>
        </ul>
      </div>

      <div>
        <ul class="record_actions">
          <li class="cancel">
            <button class="btn btn-cancel" @click="goToPrevious">
              {{ $t('action.cancel') }}
            </button>
          </li>
          <li v-if="hasSocialActionPicked">
            <button class="btn btn-save" v-show="!isPostingWork" @click="submit">
              {{ $t('action.save') }}
            </button>
            <button class="btn btn-save" v-show="isPostingWork" disabled>
              {{ $t('action.save') }}
            </button>
          </li>
        </ul>
      </div>
    </div>
  </div>

</template>



<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import VueMultiselect from 'vue-multiselect';
import { dateToISO, ISOToDate } from 'ChillMainAssets/chill/js/date.js';
import PersonRenderBox from 'ChillPersonAssets/vuejs/_components/Entity/PersonRenderBox.vue';

const i18n = {
  messages: {
    fr: {
      startDate: "Date de début",
      endDate: "Date de fin",
      form_has_errors: "Le formulaire comporte des erreurs",
      pick_social_issue: "Choisir une problématique sociale",
      pick_other_social_issue: "Veuillez choisir un autre problématique",
      pick_an_action: "Choisir une action d'accompagnement",
      pick_social_issue_linked_with_action: "Indiquez la problématique sociale liée à l'action d'accompagnement",
      persons_involved: "Usagers concernés",
      choose_other_social_issue: "Veuillez choisir un autre problématique",
    }
  }
}

export default {
  name: 'App',
  components: {
    VueMultiselect,
    PersonRenderBox,
  },
  methods: {
    submit() {
      this.$store.dispatch('submit')
          .catch(({name, violations}) => {
          if (name === 'ValidationException' || name === 'AccessException') {
            violations.forEach((violation) => this.$toast.open({message: violation}));
          } else {
            this.$toast.open({message: 'An error occurred'})
          }
      });
    },
    addIssueInList(value) {
      this.$store.commit('addIssueInList', value);
      this.$store.commit('removeIssueInOther', value);
      this.$store.dispatch('pickSocialIssue', value.id);
    },
    goToPrevious() {
      let params = new URLSearchParams(window.location.search);
      if (params.has('returnPath')) {
        window.location.replace(params.get('returnPath'));
      } else {
        return;
      }
    },
  },
  i18n,
  computed: {
    ...mapState([
      'socialIssues',
      'socialIssuesOther',
      'socialActionsReachables',
      'errors',
      'personsReachables',
    ]),
    ...mapGetters([
      'hasSocialIssuePicked',
      'hasSocialActionPicked',
      'isLoadingSocialActions',
      'isPostingWork',
      'hasErrors',
    ]),
    personsPicked: {
      get() {
        let s = this.$store.state.personsPicked.map(p => p.id);

        return s;
      },
      set(v) {
        this.$store.commit('setPersonsPickedIds', v);
      }
    },
    socialIssuePicked: {
      get() {
        let s = this.$store.state.socialIssuePicked;

        if (s === null) {
          return null;
        }

        return s.id;
      },
      set(value) {
        this.$store.dispatch('pickSocialIssue', value);
      }
    },
    socialActionPicked: {
      get() {
        return this.$store.state.socialActionPicked;
      },
      set(value) {
        this.$store.commit('setSocialAction', value);
      }
    },
    startDate: {
      get() {
        let d = this.$store.state.startDate;
        return dateToISO(d);
      },
      set(value) {
        this.$store.commit('setStartDate', ISOToDate(value));
      }
    },
    endDate: {
      get() {
        return dateToISO(this.$store.state.endDate);
      },
      set(value) {
        this.$store.commit('setEndDate', ISOToDate(value));
      }
    },
    setSocialIssue: {
      set() {
        this.$store.dispatch('setSocialIssue', socialIssues[socialIssues.length - 1])
      }
    }
  }
}

</script>

<style lang="scss" scoped>
@import 'ChillMainAssets/module/bootstrap/shared';
@import 'ChillPersonAssets/chill/scss/mixins';
@import 'ChillMainAssets/chill/scss/chill_variables';
span.badge {
  @include badge_social($social-issue-color);
  font-size: 95%;
  margin-bottom: 5px;
  margin-right: 1em;
  margin-left: 1em;
}
</style>

<style lang="scss">

#awc_create_form {
  display: grid;
  grid-template-areas:
    "picking picking"
    "start_date end_date"
    "confirm confirm"
    ;
  grid-template-columns: 50% 50%;
  column-gap: 1.5rem;

  #picking {
    grid-area: picking;

    #persons {
      ul {
        padding: 0;

        list-style-type: none;
      }
    }
  }

  #start_date {
    grid-area: start_date;
  }

  #end_date {
    grid-area: end_date;
  }

  #confirm {
    grid-area: confirm;
  }
}
</style>
