<template>
    <div>
        <ul class="record_actions">
            <li>
                <a class="btn btn-sm btn-create" @click="openModal">
                    {{ trans(ACTIVITY_CREATE_NEW_LOCATION) }}
                </a>
            </li>
        </ul>

        <teleport to="body">
            <modal
                v-if="modal.showModal"
                :modalDialogClass="modal.modalDialogClass"
                @close="modal.showModal = false"
            >
                <template #header>
                    <h3 class="modal-title">
                        {{ trans(ACTIVITY_CREATE_NEW_LOCATION) }}
                    </h3>
                </template>
                <template #body>
                    <form>
                        <div class="alert alert-warning" v-if="errors.length">
                            <ul>
                                <li v-for="(e, i) in errors" :key="i">
                                    {{ e }}
                                </li>
                            </ul>
                        </div>

                        <div class="form-floating mb-3">
                            <select
                                class="form-select form-select-lg"
                                id="type"
                                required
                                v-model="selectType"
                            >
                                <option selected disabled value="">
                                    {{ trans(ACTIVITY_CHOOSE_LOCATION_TYPE) }}
                                </option>
                                <option
                                    v-for="t in locationTypes"
                                    :value="t"
                                    :key="t.id"
                                >
                                    {{ localizeString(t.title) }}
                                </option>
                            </select>
                            <label>{{
                                trans(ACTIVITY_LOCATION_FIELDS_TYPE)
                            }}</label>
                        </div>

                        <div class="form-floating mb-3">
                            <input
                                class="form-control form-control-lg"
                                id="name"
                                v-model="inputName"
                                placeholder
                            />
                            <label for="name">{{
                                trans(ACTIVITY_LOCATION_FIELDS_NAME)
                            }}</label>
                        </div>

                        <add-address
                            :context="addAddress.context"
                            :options="addAddress.options"
                            :addressChangedCallback="submitNewAddress"
                            v-if="showAddAddress"
                            ref="addAddress"
                        />

                        <div class="form-floating mb-3" v-if="showContactData">
                            <input
                                class="form-control form-control-lg"
                                id="phonenumber1"
                                v-model="inputPhonenumber1"
                                placeholder
                            />
                            <label for="phonenumber1">{{
                                trans(ACTIVITY_LOCATION_FIELDS_PHONENUMBER1)
                            }}</label>
                        </div>
                        <div class="form-floating mb-3" v-if="hasPhonenumber1">
                            <input
                                class="form-control form-control-lg"
                                id="phonenumber2"
                                v-model="inputPhonenumber2"
                                placeholder
                            />
                            <label for="phonenumber2">{{
                                trans(ACTIVITY_LOCATION_FIELDS_PHONENUMBER2)
                            }}</label>
                        </div>
                        <div class="form-floating mb-3" v-if="showContactData">
                            <input
                                class="form-control form-control-lg"
                                id="email"
                                v-model="inputEmail"
                                placeholder
                            />
                            <label for="email">{{
                                trans(ACTIVITY_LOCATION_FIELDS_EMAIL)
                            }}</label>
                        </div>
                    </form>
                </template>
                <template #footer>
                    <button
                        class="btn btn-save"
                        @click.prevent="saveNewLocation"
                    >
                        {{ trans(SAVE) }}
                    </button>
                </template>
            </modal>
        </teleport>
    </div>
</template>

<script>
import Modal from "ChillMainAssets/vuejs/_components/Modal.vue";
import AddAddress from "ChillMainAssets/vuejs/Address/components/AddAddress.vue";
import { mapState } from "vuex";
import { getLocationTypes } from "../../api";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";
import { localizeString } from "ChillMainAssets/lib/localizationHelper/localizationHelper";
import {
    SAVE,
    ACTIVITY_LOCATION_FIELDS_EMAIL,
    ACTIVITY_LOCATION_FIELDS_PHONENUMBER1,
    ACTIVITY_LOCATION_FIELDS_PHONENUMBER2,
    ACTIVITY_LOCATION_FIELDS_NAME,
    ACTIVITY_LOCATION_FIELDS_TYPE,
    ACTIVITY_CHOOSE_LOCATION_TYPE,
    ACTIVITY_CREATE_NEW_LOCATION,
    ACTIVITY_EDIT_ADDRESS,
    ACTIVITY_CREATE_ADDRESS,
    trans,
} from "translator";

export default {
    name: "NewLocation",
    components: {
        Modal,
        AddAddress,
    },
    setup() {
        return {
            trans,
            SAVE,
            ACTIVITY_LOCATION_FIELDS_EMAIL,
            ACTIVITY_LOCATION_FIELDS_PHONENUMBER1,
            ACTIVITY_LOCATION_FIELDS_PHONENUMBER2,
            ACTIVITY_LOCATION_FIELDS_NAME,
            ACTIVITY_LOCATION_FIELDS_TYPE,
            ACTIVITY_CHOOSE_LOCATION_TYPE,
            ACTIVITY_CREATE_NEW_LOCATION,
            ACTIVITY_EDIT_ADDRESS,
            ACTIVITY_CREATE_ADDRESS,
        };
    },
    props: ["availableLocations"],
    data() {
        return {
            errors: [],
            selected: {
                type: null,
                name: null,
                addressId: null,
                phonenumber1: null,
                phonenumber2: null,
                email: null,
            },
            locationTypes: [],
            modal: {
                showModal: false,
                modalDialogClass: "modal-dialog-scrollable modal-xl",
            },
            addAddress: {
                options: {
                    button: {
                        text: {
                            create: ACTIVITY_CREATE_ADDRESS,
                            edit: ACTIVITY_EDIT_ADDRESS,
                        },
                        size: "btn-sm",
                    },
                    title: {
                        create: ACTIVITY_CREATE_ADDRESS,
                        edit: ACTIVITY_EDIT_ADDRESS,
                    },
                },
                context: {
                    target: {
                        //name, id
                    },
                    edit: false,
                    addressId: null,
                    defaults: window.addaddress,
                },
            },
        };
    },
    computed: {
        ...mapState(["activity"]),
        selectType: {
            get() {
                return this.selected.type;
            },
            set(value) {
                this.selected.type = value;
            },
        },
        inputName: {
            get() {
                return this.selected.name;
            },
            set(value) {
                this.selected.name = value;
            },
        },
        inputEmail: {
            get() {
                return this.selected.email;
            },
            set(value) {
                this.selected.email = value;
            },
        },
        inputPhonenumber1: {
            get() {
                return this.selected.phonenumber1;
            },
            set(value) {
                this.selected.phonenumber1 = value;
            },
        },
        inputPhonenumber2: {
            get() {
                return this.selected.phonenumber2;
            },
            set(value) {
                this.selected.phonenumber2 = value;
            },
        },
        hasPhonenumber1() {
            return (
                this.selected.phonenumber1 !== null &&
                this.selected.phonenumber1 !== ""
            );
        },
        showAddAddress() {
            let cond = false;
            if (this.selected.type) {
                if (this.selected.type.addressRequired !== "never") {
                    cond = true;
                }
            }
            return cond;
        },
        showContactData() {
            let cond = false;
            if (this.selected.type) {
                if (this.selected.type.contactData !== "never") {
                    cond = true;
                }
            }
            return cond;
        },
    },
    mounted() {
        this.getLocationTypesList();
    },
    methods: {
        localizeString,
        checkForm() {
            let cond = true;
            this.errors = [];
            if (!this.selected.type) {
                this.errors.push("Type de localisation requis");
                cond = false;
            } else {
                if (
                    this.selected.type.addressRequired === "required" &&
                    !this.selected.addressId
                ) {
                    this.errors.push("Adresse requise");
                    cond = false;
                }
                if (
                    this.selected.type.contactData === "required" &&
                    !this.selected.phonenumber1
                ) {
                    this.errors.push("Numéro de téléphone requis");
                    cond = false;
                }
                if (
                    this.selected.type.contactData === "required" &&
                    !this.selected.email
                ) {
                    this.errors.push("Adresse email requise");
                    cond = false;
                }
            }
            return cond;
        },
        getLocationTypesList() {
            getLocationTypes().then((results) => {
                this.locationTypes = results.filter(
                    (t) => t.availableForUsers === true,
                );
            });
        },
        openModal() {
            this.modal.showModal = true;
        },
        saveNewLocation() {
            if (this.checkForm()) {
                let body = {
                    type: "location",
                    name: this.selected.name,
                    locationType: {
                        id: this.selected.type.id,
                        type: "location-type",
                    },
                    phonenumber1: this.selected.phonenumber1,
                    phonenumber2: this.selected.phonenumber2,
                    email: this.selected.email,
                };
                if (this.selected.addressId) {
                    body = Object.assign(body, {
                        address: {
                            id: this.selected.addressId,
                        },
                    });
                }

                makeFetch("POST", "/api/1.0/main/location.json", body)
                    .then((response) => {
                        this.$store.dispatch("addAvailableLocationGroup", {
                            locationGroup: "Localisations nouvellement créées",
                            locations: [response],
                        });
                        this.$store.dispatch("updateLocation", response);
                        this.modal.showModal = false;
                    })
                    .catch((error) => {
                        if (error.name === "ValidationException") {
                            for (let v of error.violations) {
                                this.errors.push(v);
                            }
                        } else {
                            this.errors.push("An error occurred");
                        }
                    });
            }
        },
        submitNewAddress(payload) {
            this.selected.addressId = payload.addressId;
            this.addAddress.context.addressId = payload.addressId;
            this.addAddress.context.edit = true;
        },
    },
};
</script>
