<template>
    <div v-if="action === 'show'">
        <div class="flex-table">
            <third-party-render-box
                :thirdparty="thirdparty"
                :options="{
                    addInfo: true,
                    addEntity: true,
                    entityDisplayLong: true,
                    addAltNames: true,
                    addId: true,
                    addLink: false,
                    addAge: false,
                    hLevel: 3,
                    addCenter: true,
                    addNoData: true,
                    isMultiline: true,
                }"
            />
        </div>
    </div>
    <div
        v-else-if="
            action === 'edit' || action === 'create' || action === 'addContact'
        "
    >
        <div v-if="parent">
            <div class="parent-info">
                <i class="fa fa-li fa-hand-o-right" />
                <b class="me-2">{{ $t("child_of") }}</b>
                <span class="chill-entity badge-thirdparty">{{
                    parent.text
                }}</span>
            </div>
        </div>
        <div class="form-floating mb-3" v-else-if="kind !== 'child'">
            <div class="form-check">
                <input
                    class="form-check-input mt-0"
                    type="radio"
                    v-model="kind"
                    value="company"
                    id="tpartyKindInstitution"
                />
                <label for="tpartyKindInstitution" class="required">
                    <badge-entity
                        :entity="{ type: 'thirdparty', kind: 'company' }"
                        :options="{ displayLong: true }"
                    />
                </label>
            </div>
            <div class="form-check">
                <input
                    class="form-check-input mt-0"
                    type="radio"
                    v-model="kind"
                    value="contact"
                    id="tpartyKindContact"
                />
                <label for="tpartyKindContact" class="required">
                    <badge-entity
                        :entity="{ type: 'thirdparty', kind: 'contact' }"
                        :options="{ displayLong: true }"
                    />
                </label>
            </div>
        </div>
        <div v-else>
            <p>Contact de&nbsp;:</p>
            <third-party-render-box
                :thirdparty="thirdparty.parent"
                :options="{
                    addInfo: true,
                    addEntity: false,
                    addAltNames: true,
                    addId: false,
                    addLink: false,
                    addAge: false,
                    hLevel: 4,
                    addCenter: false,
                    addNoData: true,
                    isMultiline: false,
                }"
            />
        </div>

        <div
            v-if="thirdparty.kind === 'child' || thirdparty.kind === 'contact'"
        >
            <div class="child-info">
                <div class="input-group mb-3 input-section">
                    <select
                        class="form-select form-select-lg"
                        id="civility"
                        v-model="thirdparty.civility"
                    >
                        <option selected disabled :value="null">
                            {{ $t("thirdparty.civility") }}
                        </option>
                        <option
                            v-for="civility in civilities"
                            :key="civility.id"
                            :value="civility"
                        >
                            {{ civility.name.fr }}
                        </option>
                    </select>
                </div>
                <div class="input-group mb-3 input-section">
                    <input
                        class="form-control form-control-lg"
                        v-model="thirdparty.profession"
                        :placeholder="$t('thirdparty.profession')"
                        :aria-label="$t('thirdparty.profession')"
                        aria-describedby="profession"
                    />
                </div>
            </div>
            <div class="child-info">
                <div class="input-section">
                    <div class="form-floating mb-3">
                        <input
                            class="form-control form-control-lg"
                            id="firstname"
                            v-model="thirdparty.firstname"
                            :placeholder="$t('thirdparty.firstname')"
                        />
                        <label for="firstname">{{
                            $t("thirdparty.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>
                <div class="input-section">
                    <div class="form-floating mb-3">
                        <input
                            class="form-control form-control-lg"
                            id="name"
                            v-model="thirdparty.name"
                            :placeholder="$t('thirdparty.lastname')"
                        />
                        <label for="name">{{
                            $t("thirdparty.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('name', qi)"
                            >
                                <span class="person-text">{{ qi }}</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div v-if="thirdparty.kind === 'company'">
            <div class="form-floating mb-3">
                <input
                    class="form-control form-control-lg"
                    id="name"
                    v-model="thirdparty.name"
                    :placeholder="$t('thirdparty.name')"
                />
                <label for="name">{{ $t("thirdparty.name") }}</label>
            </div>
            <div v-if="query">
                <ul class="list-suggest add-items inline">
                    <li @click="addQuery(query)">
                        <span class="person-text">{{ query }}</span>
                    </li>
                </ul>
            </div>
        </div>

        <template v-if="thirdparty.kind !== 'child'">
            <add-address
                key="thirdparty"
                :context="context"
                :options="addAddress.options"
                :address-changed-callback="submitAddress"
                ref="addAddress"
            />
        </template>

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

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

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

        <div v-if="parent">
            <div class="input-group mb-3">
                <span class="input-group-text" id="comment"
                    ><i class="fa fa-fw fa-pencil"
                /></span>
                <textarea
                    class="form-control form-control-lg"
                    :placeholder="$t('thirdparty.comment')"
                    v-model="thirdparty.comment"
                />
            </div>
        </div>
    </div>
</template>

<script>
import ThirdPartyRenderBox from "../Entity/ThirdPartyRenderBox.vue";
import AddAddress from "ChillMainAssets/vuejs/Address/components/AddAddress";
import { getThirdparty } from "../../_api/OnTheFly";
import BadgeEntity from "ChillMainAssets/vuejs/_components/BadgeEntity.vue";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";

export default {
    name: "OnTheFlyThirdParty",
    props: ["id", "type", "action", "query", "parent"],
    components: {
        ThirdPartyRenderBox,
        AddAddress,
        BadgeEntity,
    },
    data() {
        return {
            //context: {}, <--
            thirdparty: {
                type: "thirdparty",
                address: null,
                kind: "company",
                firstname: "",
                name: "",
                telephone: "",
                telephone2: "",
                civility: null,
                profession: "",
            },
            civilities: [],
            addAddress: {
                options: {
                    openPanesInModal: true,
                    onlyButton: false,
                    button: {
                        size: "btn-sm",
                    },
                    title: {
                        create: "add_an_address_title",
                        edit: "edit_address",
                    },
                },
            },
        };
    },
    computed: {
        kind: {
            get() {
                // note: there are also default to 'institution' set in the "mounted" method
                if (this.$data.thirdparty.kind !== undefined) {
                    return this.$data.thirdparty.kind;
                } else {
                    return "company";
                }
            },
            set(v) {
                this.$data.thirdparty.kind = v;
            },
        },
        context() {
            let context = {
                target: {
                    name: this.type,
                    id: this.id,
                },
                edit: false,
                addressId: null,
                defaults: window.addaddress,
            };
            if (
                !(
                    this.thirdparty.address === undefined ||
                    this.thirdparty.address === null
                ) &&
                this.thirdparty.address.address_id !== null
            ) {
                // to complete
                context.addressId = this.thirdparty.address.address_id;
                context.edit = true;
            }
            //this.context = context; <--
            return context;
        },
        queryItems() {
            return this.query ? this.query.split(" ") : null;
        },
    },
    methods: {
        loadData() {
            return getThirdparty(this.id).then(
                (thirdparty) =>
                    new Promise((resolve) => {
                        this.thirdparty = thirdparty;
                        this.thirdparty.kind = thirdparty.kind;
                        if (this.action !== "show") {
                            if (thirdparty.address !== null) {
                                // bof! we force getInitialAddress because addressId not available when mounted
                                this.$refs.addAddress.getInitialAddress(
                                    thirdparty.address.address_id,
                                );
                            }
                        }
                        resolve();
                    }),
            );
        },
        loadCivilities() {
            const url = `/api/1.0/main/civility.json`;
            return makeFetch("GET", url)
                .then((response) => {
                    this.$data.civilities = response.results;
                    return Promise.resolve();
                })
                .catch((error) => {
                    console.log(error);
                    this.$toast.open({ message: error.body });
                });
        },
        submitAddress(payload) {
            console.log("submitAddress", payload);
            if (typeof payload.addressId !== "undefined") {
                // <--
                this.context.edit = true;
                this.context.addressId = payload.addressId; // bof! use legacy and not legacy in payload
                this.thirdparty.address = payload.address; // <--
                console.log("switch address to edit mode", this.context);
            }
        },
        addQueryItem(field, queryItem) {
            switch (field) {
                case "name":
                    if (this.thirdparty.name) {
                        this.thirdparty.name += ` ${queryItem}`;
                    } else {
                        this.thirdparty.name = queryItem;
                    }
                    break;
                case "firstName":
                    this.thirdparty.firstname = queryItem;
                    break;
            }
        },
        addQuery(query) {
            this.thirdparty.name = query;
        },
    },
    mounted() {
        let dependencies = [];
        dependencies.push(this.loadCivilities());
        if (this.action !== "create") {
            if (this.id) {
                dependencies.push(this.loadData());
                // here we can do something when all promises are resolve, with
                // Promise.all(dependencies).then(() => { /* do something */ });
            }
            if (this.action === "addContact") {
                this.$data.thirdparty.kind = "child";
                // this.$data.thirdparty.parent = this.parent.id
                this.$data.thirdparty.address = null;
            }
        } else {
            this.thirdparty.kind = "company";
        }
    },
};
</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;
    }
}
.parent-info {
    margin-bottom: 1rem;
}

.child-info {
    display: flex;
    justify-content: space-between;
    .input-section {
        width: 49%;
    }
}
</style>
