<template>
  <person-render-box
    render="bloc"
    v-if="resource.resource.type === 'person'"
    :person="resource.resource"
    :options="{
      addInfo: true,
      addId: false,
      addEntity: true,
      addLink: false,
      addAltNames: true,
      addAge: false,
      hLevel: 3,
      isConfidential: true,
    }"
  >
    <template #end-bloc>
      <div class="item-row separator">
        <ul class="record_actions">
          <li>
            <write-comment
              :resource="resource"
              @update-comment="updateComment"
            />
          </li>
          <li>
            <on-the-fly
              :parent="parent"
              :type="resource.resource.type"
              :id="resource.resource.id"
              action="show"
            />
          </li>
          <li>
            <on-the-fly
              :parent="parent"
              :type="resource.resource.type"
              :id="resource.resource.id"
              action="edit"
              @save-form-on-the-fly="saveFormOnTheFly"
              ref="onTheFly"
            />
          </li>
          <li>
            <button
              class="btn btn-sm btn-remove"
              :title="$t('action.remove')"
              @click.prevent="$emit('remove', resource)"
            />
          </li>
        </ul>
      </div>
    </template>
  </person-render-box>

  <third-party-render-box
    v-if="resource.resource.type === 'thirdparty'"
    :thirdparty="resource.resource"
    :options="{
      addLink: false,
      addId: false,
      addEntity: true,
      addInfo: false,
      hLevel: 3,
    }"
  >
    <template #end-bloc>
      <div class="item-row separator">
        <ul class="record_actions">
          <li>
            <write-comment
              :resource="resource"
              @update-comment="updateComment"
            />
          </li>
          <li>
            <on-the-fly
              :parent="parent"
              :type="resource.resource.type"
              :id="resource.resource.id"
              action="show"
            />
          </li>
          <li>
            <on-the-fly
              :parent="parent"
              :type="resource.resource.type"
              :id="resource.resource.id"
              action="edit"
              @save-form-on-the-fly="saveFormOnTheFly"
              ref="onTheFly"
            />
          </li>
          <li>
            <button
              class="btn btn-sm btn-remove"
              :title="$t('action.remove')"
              @click.prevent="$emit('remove', resource)"
            />
          </li>
        </ul>
      </div>
    </template>
  </third-party-render-box>
</template>

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

export default {
  name: "ResourceItem",
  components: {
    OnTheFly,
    PersonRenderBox,
    ThirdPartyRenderBox,
    WriteComment,
  },
  props: ["resource"],
  emits: ["remove"],
  computed: {
    parent() {
      return {
        type: this.resource.type,
        id: this.resource.id,
        comment: this.resource.comment,
        parent: {
          type: this.$store.state.accompanyingCourse.type,
          id: this.$store.state.accompanyingCourse.id,
        },
      };
    },
    hasCurrentHouseholdAddress() {
      if (this.resource.resource.current_household_address !== null) {
        return true;
      }
      return false;
    },
  },
  methods: {
    saveFormOnTheFly(payload) {
      // console.log('saveFormOnTheFly: type', payload.type, ', data', payload.data);
      payload.target = "resource";

      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") {
        // console.log('data', payload.data)
        body.firstname = payload.data.firstname;
        body.name = payload.data.name;
        body.email = payload.data.email;
        body.telephone = payload.data.telephone;
        body.telephone2 = payload.data.telephone2;
        body.address = payload.data.address
          ? { id: payload.data.address.address_id }
          : null;
        if (null !== payload.data.civility) {
          body.civility = {
            type: "chill_main_civility",
            id: payload.data.civility.id,
          };
        }
        if (null !== payload.data.profession) {
          body.profession = payload.data.profession;
        }
        // console.log('body', body);

        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" });
            }
          });
      }
    },
    updateComment(resource) {
      console.log("updateComment", resource);
      this.$store.commit("updateResource", resource);
    },
  },
};
</script>
