<template>
  <person-render-box
    render="bloc"
    :options="{
      addInfo: true,
      addId: false,
      addEntity: false,
      addLink: false,
      addHouseholdLink: false,
      addAltNames: true,
      addAge: true,
      hLevel: 3,
      isConfidential: false,
      isMultiline: true,
    }"
    :person="participation.person"
    :return-path="getAccompanyingCourseReturnPath"
  >
    <template #end-bloc>
      <div class="item-row separator">
        <ul class="record_actions">
          <button-location
            v-if="
              hasCurrentHouseholdAddress &&
              !isPersonLocatingCourse(participation.person)
            "
            :person="participation.person"
          />
          <li v-if="participation.person.current_household_id">
            <a
              class="btn btn-sm btn-chill-beige"
              :href="getCurrentHouseholdUrl"
              :title="
                $t('persons_associated.show_household_number', {
                  id: participation.person.current_household_id,
                })
              "
            >
              <i class="fa fa-fw fa-home" />
            </a>
          </li>
          <li>
            <on-the-fly
              :type="participation.person.type"
              :id="participation.person.id"
              action="show"
            />
          </li>
          <li>
            <on-the-fly
              :type="participation.person.type"
              :id="participation.person.id"
              action="edit"
              @save-form-on-the-fly="saveFormOnTheFly"
              ref="onTheFly"
            />
          </li>
          <li>
            <button
              v-if="!participation.endDate"
              class="btn btn-sm btn-remove"
              :title="$t('persons_associated.leave_course')"
              @click="modal.showModal = true"
            />
          </li>
        </ul>
      </div>
    </template>
  </person-render-box>

  <teleport to="body">
    <modal
      v-if="modal.showModal"
      :modal-dialog-class="modal.modalDialogClass"
      @close="modal.showModal = false"
    >
      <template #header>
        <h2 class="modal-title">
          {{ $t("persons_associated.sure") }}
        </h2>
      </template>
      <template #body>
        <p>{{ $t("persons_associated.sure_description") }}</p>
      </template>
      <template #footer>
        <button
          class="btn btn-danger"
          @click.prevent="$emit('close', participation)"
        >
          {{ $t("persons_associated.ok") }}
        </button>
      </template>
    </modal>
  </teleport>
</template>

<script>
import OnTheFly from "ChillMainAssets/vuejs/OnTheFly/components/OnTheFly.vue";
import ButtonLocation from "../ButtonLocation.vue";
import PersonRenderBox from "ChillPersonAssets/vuejs/_components/Entity/PersonRenderBox.vue";
import Modal from "ChillMainAssets/vuejs/_components/Modal";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";

export default {
  name: "ParticipationItem",
  components: {
    OnTheFly,
    ButtonLocation,
    PersonRenderBox,
    Modal,
  },
  props: ["participation"],
  emits: ["remove", "close"],
  data() {
    return {
      modal: {
        showModal: false,
        modalDialogClass: "modal-dialog-centered modal-md",
      },
      PersonRenderBox: {
        participation: "participation",
        options: {
          addInfo: false,
          addId: true,
          addAge: false,
          hLevel: 1,
        },
      },
    };
  },
  computed: {
    hasCurrentHouseholdAddress() {
      if (
        !this.participation.endDate &&
        this.participation.person.current_household_address !== null
      ) {
        return true;
      }
      return false;
    },
    getAccompanyingCourseReturnPath() {
      return `fr/parcours/${this.$store.state.accompanyingCourse.id}/edit#section-10`;
    },
    getCurrentHouseholdUrl() {
      return `/fr/person/household/${this.participation.person.current_household_id}/summary?returnPath=${this.getAccompanyingCourseReturnPath}`;
    },
  },
  methods: {
    isPersonLocatingCourse(person) {
      return this.$store.getters.isPersonLocatingCourse(person);
    },
    saveFormOnTheFly(payload) {
      console.log(
        "saveFormOnTheFly: type",
        payload.type,
        ", data",
        payload.data,
      );
      payload.target = "participation";

      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 = {
          id: payload.data.gender.id,
          type: payload.data.gender.type,
        };
        if (payload.data.civility !== null) {
          body.civility = {
            id: payload.data.civility.id,
            type: payload.data.civility.type,
          };
        }

        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;
        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" });
            }
          });
      }
    },
  },
};
</script>
