<template>
  <teleport to="#social-issues-acc">
    <div class="mb-3 row">
      <div class="col-4">
        <label :class="socialIssuesClassList">{{
          trans(ACTIVITY_SOCIAL_ISSUES)
        }}</label>
      </div>
      <div class="col-8">
        <check-social-issue
          v-for="issue in socialIssuesList"
          :key="issue.id"
          :issue="issue"
          :selection="socialIssuesSelected"
          @updateSelected="updateIssuesSelected"
        >
        </check-social-issue>

        <div class="my-3">
          <VueMultiselect
            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="trans(ACTIVITY_CHOOSE_OTHER_SOCIAL_ISSUE)"
            :options="socialIssuesOther"
            @select="addIssueInList"
          >
          </VueMultiselect>
        </div>
      </div>
    </div>

    <div class="mb-3 row">
      <div class="col-4">
        <label :class="socialActionsClassList">{{
          trans(ACTIVITY_SOCIAL_ACTIONS)
        }}</label>
      </div>
      <div class="col-8">
        <div v-if="actionIsLoading === true">
          <i class="chill-green fa fa-circle-o-notch fa-spin fa-lg"></i>
        </div>

        <span
          v-else-if="socialIssuesSelected.length === 0"
          class="inline-choice chill-no-data-statement mt-3"
        >
          {{ trans(ACTIVITY_SELECT_FIRST_A_SOCIAL_ISSUE) }}
        </span>

        <template
          v-else-if="
            socialActionsList.length > 0 &&
            (socialIssuesSelected.length || socialActionsSelected.length)
          "
        >
          <div
            id="actionsList"
            v-for="group in socialActionsList"
            :key="group.issue"
          >
            <span class="badge bg-chill-l-gray text-dark">{{
              group.issue
            }}</span>
            <check-social-action
              v-for="action in group.actions"
              :key="action.id"
              :action="action"
              :selection="socialActionsSelected"
              @updateSelected="updateActionsSelected"
            >
            </check-social-action>
          </div>
        </template>

        <span
          v-else-if="actionAreLoaded && socialActionsList.length === 0"
          class="inline-choice chill-no-data-statement mt-3"
        >
          {{ trans(ACTIVITY_SOCIAL_ACTION_LIST_EMPTY) }}
        </span>
      </div>
    </div>
  </teleport>
</template>

<script>
import VueMultiselect from "vue-multiselect";
import CheckSocialIssue from "./SocialIssuesAcc/CheckSocialIssue.vue";
import CheckSocialAction from "./SocialIssuesAcc/CheckSocialAction.vue";
import { getSocialIssues, getSocialActionByIssue } from "../api.js";
import {
  ACTIVITY_SOCIAL_ACTION_LIST_EMPTY,
  ACTIVITY_SELECT_FIRST_A_SOCIAL_ISSUE,
  ACTIVITY_SOCIAL_ACTIONS,
  ACTIVITY_SOCIAL_ISSUES,
  ACTIVITY_CHOOSE_OTHER_SOCIAL_ISSUE,
  trans,
} from "translator";

export default {
  name: "SocialIssuesAcc",
  components: {
    CheckSocialIssue,
    CheckSocialAction,
    VueMultiselect,
  },
  setup() {
    return {
      trans,
      ACTIVITY_SOCIAL_ACTION_LIST_EMPTY,
      ACTIVITY_SELECT_FIRST_A_SOCIAL_ISSUE,
      ACTIVITY_SOCIAL_ACTIONS,
      ACTIVITY_SOCIAL_ISSUES,
      ACTIVITY_CHOOSE_OTHER_SOCIAL_ISSUE,
    };
  },
  data() {
    return {
      issueIsLoading: false,
      actionIsLoading: false,
      actionAreLoaded: false,
      socialIssuesClassList: {
        "col-form-label": true,
        required: false,
      },
      socialActionsClassList: {
        "col-form-label": true,
        required: false,
      },
    };
  },
  computed: {
    socialIssuesList() {
      return this.$store.state.activity.accompanyingPeriod.socialIssues;
    },
    socialIssuesSelected() {
      return this.$store.state.activity.socialIssues;
    },
    socialIssuesOther() {
      return this.$store.state.socialIssuesOther;
    },
    socialActionsList() {
      return this.$store.getters.socialActionsListSorted;
    },
    socialActionsSelected() {
      return this.$store.state.activity.socialActions;
    },
  },
  mounted() {
    /* Load classNames after element is present */
    const socialActionsEl = document.querySelector(
      "input#chill_activitybundle_activity_socialActions",
    );
    if (socialActionsEl && socialActionsEl.hasAttribute("required")) {
      this.socialActionsClassList.required = true;
    }

    const socialIssuesEl = document.querySelector(
      "input#chill_activitybundle_activity_socialIssues",
    );
    if (socialIssuesEl && socialIssuesEl.hasAttribute("required")) {
      this.socialIssuesClassList.required = true;
    }

    /* Load other issues in multiselect */
    this.issueIsLoading = true;
    this.actionAreLoaded = false;

    getSocialIssues().then((response) => {
      /* Add issues to the store */
      this.$store.commit("updateIssuesOther", response);

      /* Add in list the issues already associated (if not yet listed) */
      this.socialIssuesSelected.forEach((issue) => {
        if (
          this.socialIssuesList.filter((i) => i.id === issue.id).length !== 1
        ) {
          this.$store.commit("addIssueInList", issue);
        }
      });

      /* Remove from multiselect the issues that are not yet in the checkbox list */
      this.socialIssuesList.forEach((issue) => {
        this.$store.commit("removeIssueInOther", issue);
      });

      /* Filter issues */
      this.$store.commit("filterList", "issues");

      /* Add in list the actions already associated (if not yet listed) */
      this.socialActionsSelected.forEach((action) => {
        this.$store.commit("addActionInList", action);
      });

      /* Filter actions */
      this.$store.commit("filterList", "actions");

      this.issueIsLoading = false;
      this.actionAreLoaded = true;
      this.updateActionsList();
    });
  },
  methods: {
    /* When choosing an issue in multiselect, add it in checkboxes (as selected),
         remove it from multiselect, and add socialActions concerned
      */
    addIssueInList(value) {
      //console.log('addIssueInList', value);
      this.$store.commit("addIssueInList", value);
      this.$store.commit("removeIssueInOther", value);
      this.$store.dispatch("addIssueSelected", value);
      this.updateActionsList();
    },
    /* Update value for selected issues checkboxes
     */
    updateIssuesSelected(issues) {
      //console.log('updateIssuesSelected', issues);
      this.$store.dispatch("updateIssuesSelected", issues);
      this.updateActionsList();
    },
    /* Update value for selected actions checkboxes
     */
    updateActionsSelected(actions) {
      //console.log('updateActionsSelected', actions);
      this.$store.dispatch("updateActionsSelected", actions);
    },
    /* Add socialActions concerned: after reset, loop on each issue selected
         to get social actions concerned
      */
    updateActionsList() {
      this.resetActionsList();
      this.socialIssuesSelected.forEach((item) => {
        this.actionIsLoading = true;
        getSocialActionByIssue(item.id).then(
          (actions) =>
            new Promise((resolve) => {
              actions.results.forEach((action) => {
                this.$store.commit("addActionInList", action);
              }, this);

              this.$store.commit("filterList", "actions");

              this.actionIsLoading = false;
              this.actionAreLoaded = true;
              resolve();
            }),
        );
      }, this);
    },
    /* Reset socialActions List: flush list and restore selected actions
     */
    resetActionsList() {
      this.$store.commit("resetActionsList");
      this.actionAreLoaded = false;
      this.socialActionsSelected.forEach((item) => {
        this.$store.commit("addActionInList", item);
      }, this);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "ChillMainAssets/module/bootstrap/shared";
@import "ChillPersonAssets/chill/scss/mixins";
@import "ChillMainAssets/chill/scss/chill_variables";

span.multiselect__single {
  display: none !important;
}

#actionsList {
  border-radius: 0.5rem;
  padding: 1rem;
  margin: 0.5rem;
  background-color: whitesmoke;
}

span.badge {
  margin-bottom: 0.5rem;
  @include badge_social($social-issue-color);
}
</style>
