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

    <div v-if="accompanyingCourse.requestor && isAnonymous" class="flex-table">
      <label>
        <input type="checkbox" v-model="requestorIsAnonymous" class="me-2" />
        {{ $t("requestor.is_anonymous") }}
      </label>
      <confidential v-if="accompanyingCourse.requestor.type === 'thirdparty'">
        <template #confidential-content>
          <third-party-render-box
            :thirdparty="accompanyingCourse.requestor"
            :options="{
              addLink: false,
              addId: false,
              addEntity: true,
              addInfo: false,
              hLevel: 3,
              isMultiline: true,
              isConfidential: true,
            }"
          >
            <template #record-actions>
              <ul class="record_actions">
                <li>
                  <on-the-fly
                    :type="accompanyingCourse.requestor.type"
                    :id="accompanyingCourse.requestor.id"
                    action="show"
                  />
                </li>
                <li>
                  <on-the-fly
                    :type="accompanyingCourse.requestor.type"
                    :id="accompanyingCourse.requestor.id"
                    action="edit"
                    @save-form-on-the-fly="saveFormOnTheFly"
                    ref="onTheFly"
                  />
                </li>
              </ul>
            </template>
          </third-party-render-box>
        </template>
      </confidential>

      <confidential v-else-if="accompanyingCourse.requestor.type === 'person'">
        <template #confidential-content>
          <person-render-box
            render="bloc"
            :person="accompanyingCourse.requestor"
            :options="{
              addLink: false,
              addId: false,
              addAltNames: false,
              addEntity: true,
              addInfo: true,
              hLevel: 3,
              isMultiline: true,
              isConfidential: false,
              addAge: true,
            }"
          >
            <template #record-actions>
              <ul class="record_actions">
                <li>
                  <on-the-fly
                    :type="accompanyingCourse.requestor.type"
                    :id="accompanyingCourse.requestor.id"
                    action="show"
                  />
                </li>
                <li>
                  <on-the-fly
                    :type="accompanyingCourse.requestor.type"
                    :id="accompanyingCourse.requestor.id"
                    action="edit"
                    @save-form-on-the-fly="saveFormOnTheFly"
                    ref="onTheFly"
                  />
                </li>
              </ul>
            </template>
          </person-render-box>
        </template>
      </confidential>

      <ul class="record_actions">
        <li>
          <button
            class="btn btn-remove"
            :title="$t('action.remove')"
            @click="removeRequestor"
          >
            {{ $t("action.remove") }}
          </button>
        </li>
      </ul>
    </div>

    <div
      v-else-if="accompanyingCourse.requestor && !isAnonymous"
      class="flex-table"
    >
      <label>
        <input type="checkbox" v-model="requestorIsAnonymous" class="me-2" />
        {{ $t("requestor.is_anonymous") }}
      </label>

      <third-party-render-box
        v-if="accompanyingCourse.requestor.type === 'thirdparty'"
        :thirdparty="accompanyingCourse.requestor"
        :options="{
          addLink: false,
          addId: false,
          addEntity: true,
          addInfo: false,
          hLevel: 3,
          isMultiline: true,
          isConfidential: true,
        }"
      >
        <template #record-actions>
          <ul class="record_actions">
            <li>
              <on-the-fly
                :type="accompanyingCourse.requestor.type"
                :id="accompanyingCourse.requestor.id"
                action="show"
              />
            </li>
            <li>
              <on-the-fly
                :type="accompanyingCourse.requestor.type"
                :id="accompanyingCourse.requestor.id"
                action="edit"
                @save-form-on-the-fly="saveFormOnTheFly"
                ref="onTheFly"
              />
            </li>
          </ul>
        </template>
      </third-party-render-box>

      <person-render-box
        render="bloc"
        v-if="accompanyingCourse.requestor.type === 'person'"
        :person="accompanyingCourse.requestor"
        :options="{
          addLink: false,
          addId: false,
          addAltNames: false,
          addEntity: true,
          addInfo: true,
          hLevel: 3,
          isMultiline: true,
          isConfidential: false,
        }"
      >
        <template #record-actions>
          <ul class="record_actions">
            <li>
              <on-the-fly
                :type="accompanyingCourse.requestor.type"
                :id="accompanyingCourse.requestor.id"
                action="show"
              />
            </li>
            <li>
              <on-the-fly
                :type="accompanyingCourse.requestor.type"
                :id="accompanyingCourse.requestor.id"
                action="edit"
                @save-form-on-the-fly="saveFormOnTheFly"
                ref="onTheFly"
              />
            </li>
          </ul>
        </template>
      </person-render-box>

      <ul class="record_actions">
        <li>
          <button
            class="btn btn-remove"
            :title="$t('action.remove')"
            @click="removeRequestor"
          >
            {{ $t("action.remove") }}
          </button>
        </li>
      </ul>
    </div>

    <div v-else>
      <label class="chill-no-data-statement">{{
        $t("requestor.counter")
      }}</label>
    </div>

    <div
      v-if="
        accompanyingCourse.requestor === null && suggestedEntities.length > 0
      "
    >
      <ul class="list-suggest add-items inline">
        <li
          v-for="p in suggestedEntities"
          :key="uniqueId(p)"
          @click="addSuggestedEntity(p)"
        >
          <person-text v-if="p.type === 'person'" :person="p" />
          <span v-else>{{ p.text }}</span>
        </li>
      </ul>
    </div>

    <div>
      <ul class="record_actions">
        <li class="add-persons">
          <add-persons
            v-if="accompanyingCourse.requestor === null"
            :button-title="trans(ACCOMPANYING_COURSE_REQUESTOR_ADD)"
            :modal-title="trans(ACCOMPANYING_COURSE_REQUESTOR_ADD)"
            :key="addPersons.key"
            :options="addPersons.options"
            @add-new-persons="addNewPersons"
            ref="addPersons"
          >
            <!-- to cast child method -->
          </add-persons>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import AddPersons from "ChillPersonAssets/vuejs/_components/AddPersons.vue";
import OnTheFly from "ChillMainAssets/vuejs/OnTheFly/components/OnTheFly.vue";
import PersonRenderBox from "../../_components/Entity/PersonRenderBox.vue";
import ThirdPartyRenderBox from "ChillThirdPartyAssets/vuejs/_components/Entity/ThirdPartyRenderBox.vue";
import Confidential from "ChillMainAssets/vuejs/_components/Confidential.vue";
import { mapState } from "vuex";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";
import PersonText from "ChillPersonAssets/vuejs/_components/Entity/PersonText.vue";
import { ACCOMPANYING_COURSE_REQUESTOR_ADD, trans } from "translator";

export default {
  name: "Requestor",
  components: {
    AddPersons,
    OnTheFly,
    PersonRenderBox,
    ThirdPartyRenderBox,
    Confidential,
    PersonText,
  },
  props: ["isAnonymous"],
  data() {
    return {
      ACCOMPANYING_COURSE_REQUESTOR_ADD,
      addPersons: {
        key: "requestor",
        options: {
          type: ["person", "thirdparty"],
          priority: null,
          uniq: true,
        },
      },
    };
  },
  computed: {
    ...mapState({
      suggestedEntities: (state) => {
        return (
          [
            ...state.accompanyingCourse.participations
              .filter((p) => p.endDate === null)
              .map((p) => p.person),
            ...state.accompanyingCourse.resources.map((r) => r.resource),
          ]
            .filter((e) => e !== null)
            // filter for same entity appearing twice
            .filter((e, index, suggested) => {
              for (let i = 0; i < suggested.length; i = i + 1) {
                if (
                  i < index &&
                  e.id === suggested[i].id &&
                  e.type === suggested[i].type
                ) {
                  return false;
                }
              }

              return true;
            })
        );
      },
    }),
    accompanyingCourse() {
      return this.$store.state.accompanyingCourse;
    },
    requestorIsAnonymous: {
      set(value) {
        this.$store.dispatch("requestorIsAnonymous", value);
      },
      get() {
        return this.$store.state.accompanyingCourse.requestorAnonymous;
      },
    },
  },
  methods: {
    trans,
    removeRequestor() {
      //console.log('@@ CLICK remove requestor: item');
      this.$store.dispatch("removeRequestor").catch(({ name, violations }) => {
        if (name === "ValidationException" || name === "AccessException") {
          violations.forEach((violation) =>
            this.$toast.open({ message: violation }),
          );
        } else {
          this.$toast.open({ message: "An error occurred" });
        }
      });
    },
    addNewPersons({ selected }) {
      //console.log('@@@ CLICK button addNewPersons', selected);
      this.$store
        .dispatch("addRequestor", selected.shift())
        .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.$refs.addPersons.resetSearch(); // to cast child method
    },
    saveFormOnTheFly(payload) {
      console.log(
        "saveFormOnTheFly: type",
        payload.type,
        ", data",
        payload.data,
      );
      payload.target = "requestor";

      let body = { type: payload.type };
      if (payload.type === "person") {
        body.firstName = payload.data.firstName;
        body.lastName = payload.data.lastName;
        if (payload.data.birthdate !== null) {
          body.birthdate = payload.data.birthdate;
        }
        body.phonenumber = payload.data.phonenumber;
        body.mobilenumber = payload.data.mobilenumber;
        body.email = payload.data.email;
        body.altNames = payload.data.altNames;
        body.gender = payload.data.gender;

        makeFetch(
          "PATCH",
          `/api/1.0/person/person/${payload.data.id}.json`,
          body,
        )
          .then((response) => {
            this.$store.dispatch("addPerson", {
              target: payload.target,
              body: response,
            });
            this.$refs.onTheFly.closeModal();
          })
          .catch((error) => {
            if (error.name === "ValidationException") {
              for (let v of error.violations) {
                this.$toast.open({ message: v });
              }
            } else {
              this.$toast.open({ message: "An error occurred" });
            }
          });
      } else if (payload.type === "thirdparty") {
        body.name = payload.data.text;
        body.email = payload.data.email;
        body.telephone = payload.data.telephone;
        body.telephone2 = payload.data.telephone2;
        if (payload.data.address) {
          body.address = { id: payload.data.address.address_id };
        }

        makeFetch(
          "PATCH",
          `/api/1.0/thirdparty/thirdparty/${payload.data.id}.json`,
          body,
        )
          .then((response) => {
            this.$store.dispatch("addThirdparty", {
              target: payload.target,
              body: response,
            });
            this.$refs.onTheFly.closeModal();
          })
          .catch((error) => {
            if (error.name === "ValidationException") {
              for (let v of error.violations) {
                this.$toast.open({ message: v });
              }
            } else {
              this.$toast.open({ message: "An error occurred" });
            }
          });
      }
    },
    addSuggestedEntity(e) {
      this.$store
        .dispatch("addRequestor", { result: e, type: e.type })
        .catch(({ name, violations }) => {
          if (name === "ValidationException" || name === "AccessException") {
            violations.forEach((violation) =>
              this.$toast.open({ message: violation }),
            );
          } else {
            this.$toast.open({ message: "An error occurred" });
          }
        });
    },
    uniqueId(e) {
      return `${e.type}-${e.id}`;
    },
  },
};
</script>

<style lang="scss" scoped>
div.flex-table {
  margin: 1em 0 0 !important;
  & > label,
  & > ul.record_actions {
    margin: 1em 3em 0 !important;
  }
  div.item-bloc {
    background-color: white !important;
    margin-top: 1em;
  }
}

.confidential {
  display: block;
  margin-right: 0px !important;
}
</style>
