<template>
    <div>
        <loader class="m-3" v-if="loading"></loader>
        <Form ref="frmAddress" @submit="onSubmit" v-show="!loading" :validation-schema="schema"
            v-slot="{ errors, isSubmitting }" class="row">

            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Họ và tên</label>
                    <Field v-model="addressModel.Name" name="Name" type="text" class="form-control"
                        placeholder="Họ và tên" :class="{ 'is-invalid': errors.Name }" />
                    <ErrorMessage class="invalid-error" name="Name" />
                </div>
            </div>

            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Số điện thoại</label>
                    <Field v-model="addressModel.PhoneNumber1" name="PhoneNumber1" type="text" class="form-control"
                        placeholder="số điện thoại" :class="{ 'is-invalid': errors.PhoneNumber1 }" />
                    <ErrorMessage class="invalid-error" name="PhoneNumber1" />

                </div>
            </div>

            <div class="col-12 mb-3">
                <CityDistrictWard ref="locationRef" v-model:cityId="addressModel.CityId"
                    v-model:districtId="addressModel.DistrictId" v-model:wardId="addressModel.WardId">
                </CityDistrictWard>
                <ErrorMessage class="invalid-error" name="WardId" />
            </div>
            <div class="col-12">
                <div class="form-group mb-3">
                    <label>Địa chỉ</label>
                    <Field v-model="addressModel.Address1" name="Address1" type="text" class="form-control"
                        placeholder="địa chỉ" :class="{ 'is-invalid': errors.Address1 }" />
                    <ErrorMessage class="invalid-error" name="Address1" />

                </div>
            </div>
            <div class="col-12">
                <div class="form-group mb-3">
                    <label>Ghi chú</label>
                    <Field v-model="addressModel.Note" name="Note" type="text" class="form-control"
                        placeholder="ghi chú" :class="{ 'is-invalid': errors.Note }" />
                    <ErrorMessage class="invalid-error" name="Note" />

                </div>
            </div>
            <div class="col-12">
                <div class="form-group mb-3">
                    <label>Hẹn lịch</label>
                    <VueDatePicker ref="scheduledDatePicker" v-model="addressModel.ScheduledTime"
                        :enable-time-picker="true" auto-apply :format="datetimeFormat">
                    </VueDatePicker>



                </div>
            </div>
            <div class="col-12 ">
                <div class="d-flex">
                    <button @click="cancel" type="button" class="btn btn-main-default">
                        Bỏ qua
                    </button>
                    <button type="submit" class="btn ms-auto btn-main-primary" :disabled="isSubmitting">
                        <span v-show="isSubmitting" class="spinner-border spinner-border-sm"></span>
                        Xác nhận
                    </button>
                </div>
            </div>
        </Form>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';
import DatepickerInstance from "@vuepic/vue-datepicker";
const datetimeFormat = 'dd/MM/yyyy HH:mm';

const scheduledDatePicker = ref(DatepickerInstance);


//#region Components
import CityDistrictWard from "@/components/locations/CityDistrictWard.vue";

//#endregion

//#region Services
import orderAddressService from "@/services/orderAddressService";
//#endregion

//#region Toast
import { useToast } from "vue-toastification";
const toast = useToast();
//#endregion

const locationRef = ref(null);



const props = defineProps({
    addressId: Number
});
const emit = defineEmits(['cancel']);

//#region DATA

const loading = ref(false);

let addressModel = reactive({
    Id: 0,
    Name: '',
    PhoneNumber1: '',
    Address1: '',
    CityId: null,
    DistrictId: null,
    WardId: null,
    CustomerId: props.customerId,
    AddressType: props.addType,
    Note: '',
    ScheduledTime: getDefaultDueDate()
});
//#endregion


//#region Validations
const schema = Yup.object().shape({
    Name: Yup.string().required('Họ và tên không để trống'),
    PhoneNumber1: Yup.string().required('Số điện thoại không để trống'),
    Address1: Yup.string().required('Địa chỉ không để trống'),
    //WardId: Yup.string().required('Vui lòng nhập đầy đủ tỉnh, quận, phường'),
});
//#endregion

//#region methods
const frmAddress = ref(null);

function getDefaultDueDate() {
    const now = new Date();
    let defaultDueDate;

    if (now.getHours() < 15) {
        defaultDueDate = new Date(now.getTime());
        defaultDueDate.setHours(now.getHours() + 3);
    } else if (now.getHours() >= 17) {
        defaultDueDate = new Date(now.getTime());
        defaultDueDate.setDate(now.getDate() + 1);
        defaultDueDate.setHours(10, 0, 0, 0);
    } else {
        defaultDueDate = new Date(now.getTime());
        defaultDueDate.setHours(now.getHours() + 12);
    }

    const minutes = defaultDueDate.getMinutes();
    if (minutes >= 30) {
        defaultDueDate.setMinutes(30);
    } else {
        defaultDueDate.setMinutes(0);
    }

    return defaultDueDate;
}

async function onSubmit() {
    loading.value = true;


    var now = new Date();
    var isoString = now.toISOString();



    console.log(isoString);
    console.log(addressModel.ScheduledTime);
    if (addressModel.ScheduledTime !== null) {
        addressModel.ScheduledTime = new Date(addressModel.ScheduledTime).toISOString();
    }

    if (addressModel.WardId == null || addressModel.WardId <= 0) {
        var wardError = {
            WardId: "Vui lòng chọn tỉnh, quận, phường"
        };
        frmAddress.value.setErrors(wardError)
        loading.value = false;
    } else {
        var result = await orderAddressService.update(addressModel);
        if (result != null && result.Result === 1) {
            toast.success('Thành công!');
            cancel();

        } else {
            toast.error('Thất bại: ' + result.Message);
        }
        loading.value = false;
    }



}
async function getAddress() {
    loading.value = true;
    var result = await orderAddressService.getById(props.addressId);
    Object.assign(addressModel, result);
    if (addressModel.ScheduledTime == null) {
        addressModel.ScheduledTime = getDefaultDueDate();
    }

    // Đảm bảo CityDistrictWard component đã được mount
    if (locationRef.value) {
        var city = { Id: result.CityId, Name: result.CityName };
        var district = { Id: result.DistrictId, Name: result.DistrictName };
        var ward = { Id: result.WardId, Name: result.WardName };
        await locationRef.value.init(city, district, ward);
    }

    console.log(addressModel);
    loading.value = false;
}

function cancel() {
    emit('cancel');
}

//#endregion

//#region Events
onMounted(async () => {
    console.log(props.addressId);
    if (props.addressId != null && props.addressId > 0) {
        await getAddress();
    } else {
        alert("Địa chỉ yêu cầu không hợp lệ");
        cancel();
    }
})
//#endregion

</script>