<template>
    <div>
        <Form v-if="!loading" @submit="onSubmit" :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.ContactName" name="ContactName" type="text" class="form-control"
                        placeholder="Họ và tên" :class="{ 'is-invalid': errors.ContactName }" />
                    <div class="invalid-feedback">{{ errors.ContactName }}</div>
                </div>
            </div>

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

                </div>
            </div>

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

                </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="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';


const cityDistrictWardRef = ref(null);

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

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

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

const props = defineProps({
    id: Number,
    addType: {
        type: String,
        default: ''
    },
    customerId: {
        type: String,
        default: ''
    },
});
const emit = defineEmits(['cancel']);

//#region DATA

const loading = ref(false);
let addressModel = reactive({
    Id: props.id,
    ContactName: '',
    ContactPhoneNumber: '',
    Address: '',
    CityId: null,
    DistrictId: null,
    WardId: null,
    CustomerId: props.customerId,
    AddressType: props.addType,
    Note: ''
});
//#endregion


//#region Validations
const schema = Yup.object().shape({
    ContactName: Yup.string().required('Họ và tên không để trống'),
    ContactPhoneNumber: Yup.string()
        .required('Số điện thoại không để trống')
        .matches(/^[0-9]+$/, 'Số điện thoại chỉ được chứa số')
        .length(10, 'Số điện thoại phải có đúng 10 ký tự'),
    Address: Yup.string().required('Địa chỉ không để trống'),
});
//#endregion

//#region methods

async function onSubmit() {
    var addrModel = addressModel;
    console.log(addrModel);
    const currentSelection = cityDistrictWardRef.value?.getCurrentSelection?.();
    addrModel.CityId = currentSelection.cityId;
    addrModel.DistrictId = currentSelection.districtId;
    addrModel.WardId = currentSelection.wardId;

    addrModel.UpdatedByUserName = "";
    addrModel.UpdatedBy = 0;
    var addrResult = await customerAddressService.createOrUpdate(addrModel);
    if (addrResult != null && addrResult.Result === 1) {
        toast.success('Thành công!');
        cancel();
    } else {
        toast.error('Thất bại: ' + addrResult.Message);
    }

}

async function getById(id) {

    var customerAddressResult = await customerAddressService.getById(id);
    addressModel.Id = customerAddressResult.Id;
    addressModel.ContactName = customerAddressResult.ContactName;
    addressModel.ContactPhoneNumber = customerAddressResult.ContactPhoneNumber;
    addressModel.Address = customerAddressResult.Address;
    addressModel.CityId = customerAddressResult.CityId;
    addressModel.DistrictId = customerAddressResult.DistrictId;
    addressModel.WardId = customerAddressResult.WardId;
    addressModel.CustomerId = props.customerId;
    addressModel.AddressType = props.addType;
    addressModel.Note = customerAddressResult.Note != null ? customerAddressResult.Note : '';
    console.log(addressModel.WardId);
    console.log(customerAddressResult);
}

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

//#endregion

//#region Events
onMounted(async () => {
    if (props.id > 0) {
        loading.value = true;
        await getById(props.id);
        loading.value = false;
    }

})
//#endregion

</script>