<template>
  <div v-if="action === 'show'">
    <div class="flex-table">
      <person-render-box
        render="bloc"
        :person="person"
        :options="{
          addInfo: true,
          addEntity: false,
          addAltNames: true,
          addAge: true,
          addId: true,
          addLink: false,
          hLevel: 3,
          addCenter: true,
          addNoData: true,
          isMultiline: true,
        }"
        :show-residential-addresses="true"
      ></person-render-box>
    </div>
  </div>

  <div v-else-if="action === 'edit' || action === 'create'">
    <div class="form-floating mb-3">
      <input
        class="form-control form-control-lg"
        id="lastname"
        v-model="lastName"
        :placeholder="$t('person.lastname')"
        @change="checkErrors"
      />
      <label for="lastname">{{ $t("person.lastname") }}</label>
    </div>

    <div v-if="queryItems">
      <ul class="list-suggest add-items inline">
        <li
          v-for="(qi, i) in queryItems"
          :key="i"
          @click="addQueryItem('lastName', qi)"
        >
          <span class="person-text">{{ qi }}</span>
        </li>
      </ul>
    </div>

    <div class="form-floating mb-3">
      <input
        class="form-control form-control-lg"
        id="firstname"
        v-model="firstName"
        :placeholder="$t('person.firstname')"
        @change="checkErrors"
      />
      <label for="firstname">{{ $t("person.firstname") }}</label>
    </div>

    <div v-if="queryItems">
      <ul class="list-suggest add-items inline">
        <li
          v-for="(qi, i) in queryItems"
          :key="i"
          @click="addQueryItem('firstName', qi)"
        >
          <span class="person-text">{{ qi }}</span>
        </li>
      </ul>
    </div>

    <div
      v-for="(a, i) in config.altNames"
      :key="a.key"
      class="form-floating mb-3"
    >
      <input
        class="form-control form-control-lg"
        :id="a.key"
        :value="personAltNamesLabels[i]"
        @input="onAltNameInput"
      />
      <label :for="a.key">{{ a.labels.fr }}</label>
    </div>

    <!--  TODO fix placeholder if undefined
   -->
    <div class="form-floating mb-3">
      <select class="form-select form-select-lg" id="gender" v-model="gender">
        <option selected disabled>{{ $t("person.gender.placeholder") }}</option>
        <option v-for="g in config.genders" :value="g.id" :key="g.id">
          {{ g.label }}
        </option>
      </select>
      <label>{{ $t("person.gender.title") }}</label>
    </div>

    <div
      class="form-floating mb-3"
      v-if="showCenters && config.centers.length > 1"
    >
      <select class="form-select form-select-lg" id="center" v-model="center">
        <option selected disabled>{{ $t("person.center.placeholder") }}</option>
        <option v-for="c in config.centers" :value="c" :key="c.id">
          {{ c.name }}
        </option>
      </select>
      <label>{{ $t("person.center.title") }}</label>
    </div>

    <div class="form-floating mb-3">
      <select
        class="form-select form-select-lg"
        id="civility"
        v-model="civility"
      >
        <option selected disabled>
          {{ $t("person.civility.placeholder") }}
        </option>
        <option v-for="c in config.civilities" :value="c.id" :key="c.id">
          {{ c.name.fr }}
        </option>
      </select>
      <label>{{ $t("person.civility.title") }}</label>
    </div>

    <div class="input-group mb-3">
      <span class="input-group-text" id="birthdate"
        ><i class="fa fa-fw fa-birthday-cake"></i
      ></span>
      <input
        type="date"
        class="form-control form-control-lg"
        id="chill_personbundle_person_birthdate"
        name="chill_personbundle_person[birthdate]"
        v-model="birthDate"
        aria-describedby="birthdate"
      />
    </div>

    <div class="input-group mb-3">
      <span class="input-group-text" id="phonenumber"
        ><i class="fa fa-fw fa-phone"></i
      ></span>
      <input
        class="form-control form-control-lg"
        v-model="phonenumber"
        :placeholder="$t('person.phonenumber')"
        :aria-label="$t('person.phonenumber')"
        aria-describedby="phonenumber"
      />
    </div>

    <div class="input-group mb-3">
      <span class="input-group-text" id="mobilenumber"
        ><i class="fa fa-fw fa-mobile"></i
      ></span>
      <input
        class="form-control form-control-lg"
        v-model="mobilenumber"
        :placeholder="$t('person.mobilenumber')"
        :aria-label="$t('person.mobilenumber')"
        aria-describedby="mobilenumber"
      />
    </div>

    <div class="input-group mb-3">
      <span class="input-group-text" id="email"
        ><i class="fa fa-fw fa-at"></i
      ></span>
      <input
        class="form-control form-control-lg"
        v-model="email"
        :placeholder="$t('person.email')"
        :aria-label="$t('person.email')"
        aria-describedby="email"
      />
    </div>

    <div v-if="action === 'create'" class="input-group mb-3 form-check">
      <input
        class="form-check-input"
        type="checkbox"
        v-model="showAddressForm"
        name="showAddressForm"
      />
      <label class="form-check-label">{{
        $t("person.address.show_address_form")
      }}</label>
    </div>
    <div
      v-if="action === 'create' && showAddressFormValue"
      class="form-floating mb-3"
    >
      <p>{{ $t("person.address.warning") }}</p>
      <add-address
        :context="addAddress.context"
        :options="addAddress.options"
        :addressChangedCallback="submitNewAddress"
        ref="addAddress"
      >
      </add-address>
    </div>

    <div class="alert alert-warning" v-if="errors.length">
      <ul>
        <li v-for="(e, i) in errors" :key="i">{{ e }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
import {
  getCentersForPersonCreation,
  getCivilities,
  getGenders,
  getPerson,
  getPersonAltNames,
} from "../../_api/OnTheFly";
import PersonRenderBox from "../Entity/PersonRenderBox.vue";
import AddAddress from "ChillMainAssets/vuejs/Address/components/AddAddress.vue";

export default {
  name: "OnTheFlyPerson",
  props: ["id", "type", "action", "query"],
  //emits: ['createAction'],
  components: {
    PersonRenderBox,
    AddAddress,
  },
  data() {
    return {
      person: {
        type: "person",
        lastName: "",
        firstName: "",
        altNames: [],
        addressId: null,
        center: null,
      },
      config: {
        altNames: [],
        civilities: [],
        centers: [],
        genders: [],
      },
      showCenters: false, // NOTE: must remains false if the form is not in create mode
      showAddressFormValue: false,
      addAddress: {
        options: {
          button: {
            text: { create: "person.address.create_address" },
            size: "btn-sm",
          },
          title: { create: "person.address.create_address" },
        },
        context: {
          target: {}, // boilerplate for getting the address id
          edit: false,
          addressId: null,
          defaults: window.addaddress,
        },
      },
      errors: [],
    };
  },
  computed: {
    firstName: {
      set(value) {
        this.person.firstName = value;
      },
      get() {
        return this.person.firstName;
      },
    },
    lastName: {
      set(value) {
        this.person.lastName = value;
      },
      get() {
        return this.person.lastName;
      },
    },
    gender: {
      set(value) {
        this.person.gender = { id: value, type: "chill_main_gender" };
      },
      get() {
        return this.person.gender ? this.person.gender.id : null;
      },
    },
    civility: {
      set(value) {
        this.person.civility = { id: value, type: "chill_main_civility" };
      },
      get() {
        return this.person.civility ? this.person.civility.id : null;
      },
    },
    birthDate: {
      set(value) {
        if (this.person.birthdate) {
          this.person.birthdate.datetime = value + "T00:00:00+0100";
        } else {
          this.person.birthdate = { datetime: value + "T00:00:00+0100" };
        }
      },
      get() {
        return this.person.birthdate
          ? this.person.birthdate.datetime.split("T")[0]
          : "";
      },
    },
    phonenumber: {
      set(value) {
        this.person.phonenumber = value;
      },
      get() {
        return this.person.phonenumber;
      },
    },
    mobilenumber: {
      set(value) {
        this.person.mobilenumber = value;
      },
      get() {
        return this.person.mobilenumber;
      },
    },
    email: {
      set(value) {
        this.person.email = value;
      },
      get() {
        return this.person.email;
      },
    },
    showAddressForm: {
      set(value) {
        this.showAddressFormValue = value;
      },
      get() {
        return this.showAddressFormValue;
      },
    },
    center: {
      set(value) {
        console.log("will set center", value);
        this.person.center = { id: value.id, type: value.type };
      },
      get() {
        const center = this.config.centers.find(
          (c) => this.person.center !== null && this.person.center.id === c.id,
        );

        console.log("center get", center);

        return typeof center === "undefined" ? null : center;
      },
    },
    genderClass() {
      switch (this.person.gender) {
        case "woman":
          return "fa-venus";
        case "man":
          return "fa-mars";
        case "both":
          return "fa-neuter";
        case "unknown":
          return "fa-genderless";
        default:
          return "fa-genderless";
      }
    },
    genderTranslation() {
      switch (this.person.gender.genderTranslation) {
        case "woman":
          return "person.gender.woman";
        case "man":
          return "person.gender.man";
        case "neutral":
          return "person.gender.neutral";
        case "unknown":
          return "person.gender.unknown";
        default:
          return "person.gender.unknown";
      }
    },
    feminized() {
      return this.person.gender === "woman" ? "e" : "";
    },
    personAltNamesLabels() {
      return this.person.altNames.map((a) => (a ? a.label : ""));
    },
    queryItems() {
      return this.query ? this.query.split(" ") : null;
    },
  },
  mounted() {
    getPersonAltNames().then((altNames) => {
      this.config.altNames = altNames;
    });
    getCivilities().then((civilities) => {
      if ("results" in civilities) {
        this.config.civilities = civilities.results;
      }
    });
    getGenders().then((genders) => {
      if ("results" in genders) {
        console.log("genders", genders.results);
        this.config.genders = genders.results;
      }
    });
    if (this.action !== "create") {
      this.loadData();
    } else {
      // console.log('show centers', this.showCenters);
      getCentersForPersonCreation().then((params) => {
        this.config.centers = params.centers.filter((c) => c.isActive);
        this.showCenters = params.showCenters;
        // console.log('centers', this.config.centers)
        // console.log('show centers inside', this.showCenters);
        if (this.showCenters && this.config.centers.length === 1) {
          this.person.center = this.config.centers[0];
        }
      });
    }
  },
  methods: {
    checkErrors(e) {
      this.errors = [];
      if (this.person.lastName === "") {
        this.errors.push("Le nom ne doit pas être vide.");
      }
      if (this.person.firstName === "") {
        this.errors.push("Le prénom ne doit pas être vide.");
      }
      if (!this.person.gender) {
        this.errors.push("Le genre doit être renseigné");
      }
      if (this.showCenters && this.person.center === null) {
        this.errors.push("Le centre doit être renseigné");
      }
    },
    loadData() {
      getPerson(this.id).then(
        (person) =>
          new Promise((resolve, reject) => {
            this.person = person;
            //console.log('get person', this.person);
            resolve();
          }),
      );
    },
    onAltNameInput(event) {
      const key = event.target.id;
      const label = event.target.value;
      let updateAltNames = this.person.altNames.filter((a) => a.key !== key);
      updateAltNames.push({ key: key, label: label });
      this.person.altNames = updateAltNames;
    },
    addQueryItem(field, queryItem) {
      switch (field) {
        case "lastName":
          this.person.lastName = this.person.lastName
            ? (this.person.lastName += ` ${queryItem}`)
            : queryItem;
          break;
        case "firstName":
          this.person.firstName = this.person.firstName
            ? (this.person.firstName += ` ${queryItem}`)
            : queryItem;
          break;
      }
    },
    submitNewAddress(payload) {
      this.person.addressId = payload.addressId;
    },
  },
};
</script>

<style lang="scss" scoped>
div.flex-table {
  div.item-bloc {
    div.item-row {
      div.item-col:last-child {
        justify-content: flex-start;
      }
    }
  }
}
dl {
  dd {
    margin-left: 1em;
  }
}
div.form-check {
  label {
    margin-left: 0.5em !important;
  }
}
</style>
