<template>
  <div class="vue-component">
    <h2><a id="section-80" />{{ $t("referrer.title") }}</h2>

    <teleport to="body">
      <modal
        v-if="modal.showModal"
        :modal-dialog-class="modal.modalDialogClass"
        @close="cancelChange"
      >
        <template #header>
          <h3 class="modal-title">
            {{ $t("confirm.title") }}
          </h3>
        </template>

        <template #body-head>
          <div class="modal-body">
            <p
              v-html="
                $t('confirm.sure_referrer', {
                  referrer: this.value.text,
                })
              "
            />
          </div>
        </template>

        <template #footer>
          <button class="btn btn-save" @click.prevent="this.confirmReferrer">
            {{ $t("confirm.ok_referrer") }}
          </button>
        </template>
      </modal>
    </teleport>

    <div>
      <label class="col-form-label" for="selectJob">
        {{ $t("job.label") }}
      </label>

      <VueMultiselect
        name="selectJob"
        label="text"
        :custom-label="customJobLabel"
        track-by="id"
        :multiple="false"
        :searchable="true"
        :placeholder="$t('job.placeholder')"
        v-model="valueJob"
        :options="jobs"
        :select-label="$t('multiselect.select_label')"
        :deselect-label="$t('multiselect.deselect_label')"
        :selected-label="$t('multiselect.selected_label')"
      />

      <label class="col-form-label" for="selectReferrer">
        {{ $t("referrer.label") }}
      </label>

      <VueMultiselect
        name="selectReferrer"
        label="text"
        track-by="id"
        :multiple="false"
        :searchable="true"
        :placeholder="$t('referrer.placeholder')"
        v-model="value"
        @select="updateReferrer"
        @remove="removeReferrer"
        :options="users"
        :select-label="$t('multiselect.select_label')"
        :deselect-label="$t('multiselect.deselect_label')"
        :selected-label="$t('multiselect.selected_label')"
      />

      <template v-if="usersSuggestedFilteredByJob.length > 0">
        <ul class="list-suggest add-items inline">
          <li
            v-for="(u, i) in usersSuggestedFilteredByJob"
            @click="updateReferrer(u)"
            :key="`referrer-${i}`"
          >
            <span>
              <user-render-box-badge :user="u" />
            </span>
          </li>
        </ul>
      </template>
    </div>

    <div>
      <ul class="record_actions">
        <li>
          <button
            class="btn btn-create"
            type="button"
            name="button"
            @click="assignMe"
          >
            {{ $t("referrer.assign_me") }}
          </button>
        </li>
      </ul>
    </div>

    <div v-if="!isJobValid" class="alert alert-warning to-confirm">
      {{ $t("job.not_valid") }}
    </div>
  </div>
</template>

<script>
import VueMultiselect from "vue-multiselect";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";
import { mapState, mapGetters } from "vuex";
import UserRenderBoxBadge from "ChillMainAssets/vuejs/_components/Entity/UserRenderBoxBadge";
import Modal from "ChillMainAssets/vuejs/_components/Modal";

export default {
  name: "Referrer",
  components: {
    UserRenderBoxBadge,
    VueMultiselect,
    Modal,
  },
  data() {
    return {
      jobs: [],
      modal: {
        showModal: false,
        modalDialogClass: "modal-dialog-scrollable modal-xl",
      },
      value: this.$store.state.accompanyingCourse.user,
      confirmed: false,
    };
  },
  computed: {
    ...mapState({
      valueJob: (state) => state.accompanyingCourse.job,
    }),
    ...mapGetters(["isJobValid", "usersSuggestedFilteredByJob"]),
    users: function () {
      let users = this.$store.getters.usersFilteredByJob;
      // ensure that the selected user is in the list. add it if necessary
      if (
        this.$store.state.accompanyingCourse.user !== null &&
        users.find(
          (u) => this.$store.state.accompanyingCourse.user.id === u.id,
        ) === undefined
      ) {
        users.push(this.$store.state.accompanyingCourse.user);
      }
      return users;
    },
    valueJob: {
      get() {
        return this.$store.state.accompanyingCourse.job;
      },
      set(value) {
        this.$store
          .dispatch("updateJob", value)
          .catch(({ name, violations }) => {
            if (name === "ValidationException" || name === "AccessException") {
              violations.forEach((violation) =>
                this.$toast.open({ message: violation }),
              );
            } else {
              this.$toast.open({ message: "An error occurred" });
            }
          });
      },
    },
  },
  mounted() {
    this.getJobs();
  },
  methods: {
    updateReferrer(value) {
      this.value = value;
      this.toggleModal();
    },
    getJobs() {
      const url = "/api/1.0/main/user-job.json";
      makeFetch("GET", url)
        .then((response) => {
          this.jobs = response.results;
        })
        .catch((error) => {
          this.$toast.open({ message: error.txt });
        });
    },
    customJobLabel(value) {
      return value.label.fr;
    },
    assignMe() {
      const url = `/api/1.0/main/whoami.json`;
      makeFetch("GET", url).then((user) => {
        // this.value = user
        this.updateReferrer(user);
      });
    },
    toggleModal() {
      this.modal.showModal = !this.modal.showModal;
    },
    confirmReferrer() {
      this.$store
        .dispatch("updateReferrer", this.value)
        .catch(({ name, violations }) => {
          if (name === "ValidationException" || name === "AccessException") {
            violations.forEach((violation) =>
              this.$toast.open({ message: violation }),
            );
          } else {
            this.$toast.open({ message: "An error occurred" });
          }
        });
      this.toggleModal();
    },
    removeReferrer() {
      console.log("remove option");
      this.$store
        .dispatch("updateReferrer", null)
        .catch(({ name, violations }) => {
          if (name === "ValidationException" || name === "AccessException") {
            violations.forEach((violation) =>
              this.$toast.open({ message: violation }),
            );
          } else {
            this.$toast.open({ message: "An error occurred" });
          }
        });
    },
    cancelChange() {
      this.value = this.$store.state.accompanyingCourse.user;
      this.toggleModal();
    },
  },
};
</script>

<style src="vue-multiselect/dist/vue-multiselect.css"></style>
