<template>
    <LoadingComponent :props="loading" />

    <div class="db-card">
        <div class="db-card-header">
            <h3 class="db-card-title">{{ $t("label.address") }}</h3>
        </div>
        <div class="db-card-body">
            <form @submit.prevent="save">
                <div class="form-row">

                    <div class="form-col-12 sm:form-col-6">
                        <label for="name" class="db-field-title required">{{
                            $t('label.house_office_name')
                            }}</label>
                        <input v-model="address.form.name" v-bind:class="errors.name ? 'invalid' : ''" type="text"
                            id="name" class="db-field-control" />
                        <small class="db-field-alert" v-if="errors.name">{{
                            errors.name[0]
                            }}</small>
                    </div>

                    <div class="form-col-12 sm:form-col-6">
                        <label for="address" class="db-field-title required">{{
                            $t('label.full_address')
                            }}</label>
                        <input v-model="address.form.address" v-bind:class="errors.address ? 'invalid' : ''" type="text"
                            id="address" class="db-field-control" />
                        <small class="db-field-alert" v-if="errors.address">{{
                            errors.address[0]
                            }}</small>
                    </div>

                    <div class="form-col-12 sm:form-col-6">
                        <label for="area" class="db-field-title required">{{
                            $t('label.area')
                            }}</label>
                        <vue-select class="db-field-control f-b-custom-select" id="area" v-model="address.form.area_id"
                            :options="areas" label-by="name" value-by="id" :closeOnSelect="true" :searchable="true"
                            :clearOnClose="true" placeholder="--" search-placeholder="--"
                            :class="{ invalid: errors.area_id }" />
                        <small class="db-field-alert" v-if="errors.area_id">{{ errors.area_id[0] }}</small>
                    </div>

                    <div class="form-col-12 sm:form-col-6">
                        <label for="phone" class="db-field-title required">{{ $t('label.phone') }}</label>
                        <div :class="errors.phone ? 'invalid' : ''" class="db-field-control flex items-center">
                            <div class="w-fit flex-shrink-0 dropdown-group">
                                <button type="button" class="flex items-center gap-1 dropdown-btn">
                                    {{ address.flag }}
                                    <span class="whitespace-nowrap flex-shrink-0 text-xs">
                                        {{ address.form.country_code }}
                                    </span>
                                    <input type="hidden" v-model="address.form.country_code">
                                </button>
                            </div>
                            <input v-model="address.form.phone" v-on:keypress="phoneNumber($event)" v-bind:class="errors.phone
                                ? 'invalid' : ''" type="text" id="phone" class="pl-2 text-sm w-full h-full" />
                        </div>
                        <small class="db-field-alert" v-if="errors.phone">
                            {{ errors.phone[0] }}
                        </small>
                    </div>

                    <div class="form-col-12">
                        <div class="flex flex-wrap gap-3">
                            <button type="submit" class="db-btn py-2 text-white bg-primary">
                                <i class="lab lab-save"></i>
                                <span>{{ $t("label.save") }}</span>
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</template>
<script>
import LoadingComponent from "../../components/LoadingComponent.vue";
import appService from "../../../../services/appService";
import alertService from "../../../../services/alertService";
import statusEnum from "../../../../enums/modules/statusEnum";
import { useCompanyStore } from '../../../../stores/company';
import { useCountryCodeStore } from '../../../../stores/countryCode';
import { useDeliveryAreaStore } from "../../../../stores/deliveryArea";
import { useEmployeeAddressStore } from "../../../../stores/employeeAddress";

export default {
    name: "EmployeeAddressCreateComponent",
    components: { LoadingComponent },
    data() {
        return {
            loading: {
                isActive: false,
            },
            address: {
                form: {
                    name: "",
                    address: "",
                    area_id: null,
                    phone: "",
                    country_code: "",
                    user_id: null
                },
            },
            errors: {},
            flag: "",
            country_code: "",
            companyStore: useCompanyStore(),
            countryCodeStore: useCountryCodeStore(),
            deliveryAreaStore: useDeliveryAreaStore(),
            employeeAddressStore: useEmployeeAddressStore(),
        };
    },
    mounted() {
        this.deliveryAreaStore.fetchLists({
            order_column: 'id',
            order_type: 'asc',
            status: statusEnum.ACTIVE,
        }).then((res) => {
            this.loading.isActive = false;
        }).catch((err) => {
            this.loading.isActive = false;
        });

        this.loading.isActive = true;

        this.companyStore.fetchLists()
            .then(companyRes => {
                this.countryCodeStore.fetchShow(companyRes.data.data.company_country_code)
                    .then(res => {
                        this.address.form.country_code = res.data.data.calling_code;
                        this.address.flag = res.data.data.flag_emoji;
                        this.loading.isActive = false;
                    })
                    .catch(() => {
                        this.loading.isActive = false;
                    });
            })
            .catch(() => {
                this.loading.isActive = false;
            });
        this.address.form.user_id = parseInt(this.$route.params.id);
        this.employeeAddressStore.resetTemp();
        this.employeeAddressStore.fetchLists({ user_id: this.$route.params.id })
            .then((res) => {
                if (res.data.data.id) {
                    this.address.form.name = res.data.data.name;
                    this.address.form.address = res.data.data.address;
                    this.address.form.phone = res.data.data.phone;
                    this.address.form.area_id = res.data.data.area_id;
                    this.employeeAddressStore.setTemp(res.data.data.id);
                }
                this.loading.isActive = false;
            })
            .catch(() => {
                this.loading.isActive = false;
            });
    },
    computed: {
        addButton: function () {
            return { title: this.$t('button.add_address') };
        },
        areas: function () {
            return this.deliveryAreaStore.lists;
        },
    },
    methods: {
        phoneNumber(e) {
            return appService.phoneNumber(e);
        },
        save: function () {
            try {
                this.loading.isActive = true;
                const tempId = this.employeeAddressStore.temp.temp_id;
                this.employeeAddressStore.save(this.address.form).then((res) => {
                    this.loading.isActive = false;
                    alertService.successFlip(tempId === null ? 0 : 1, this.$t("label.address"));
                    this.address.form.name = res.data.data.name;
                    this.address.form.address = res.data.data.address;
                    this.address.form.phone = res.data.data.phone;
                    this.address.form.area_id = res.data.data.area_id;
                    this.employeeAddressStore.setTemp(res.data.data.id);
                    this.errors = {};
                }).catch((err) => {
                    this.loading.isActive = false;
                    this.errors = err.response.data.errors;
                });
            } catch (err) {
                this.loading.isActive = false;
                alertService.error(err);
            }
        },
    },
};
</script>