<template>
    <div>
        <Form v-if="!loading" @submit="submit" :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="model.Name" name="Name" type="text" class="form-control" placeholder="Họ và tên"
                        :class="{ 'is-invalid': errors.Name }" />
                    <div class="invalid-feedback">{{ errors.Name }}</div>
                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Số điện thoại</label>
                    <Field v-model="model.PhoneNumber1" name="PhoneNumber1" type="text" class="form-control"
                        placeholder="Số điện thoại" :class="{ 'is-invalid': errors.PhoneNumber1 }" />
                    <div class="invalid-feedback">{{ errors.PhoneNumber1 }}</div>
                </div>
            </div>
            <div class="col-12 mb-3">
                <CityDistrictWard ref="cityDistrictWardRef"
                    :key="model.CityId + '-' + model.DistrictId + '-' + model.WardId" v-model:cityId="model.CityId"
                    v-model:districtId="model.DistrictId" v-model:wardId="model.WardId" />
            </div>
            <div class="col-12">
                <div class="form-group mb-3">
                    <label>Địa chỉ</label>
                    <Field v-model="model.Address1" name="Address1" type="text" class="form-control"
                        placeholder="Địa chỉ" :class="{ 'is-invalid': errors.Address1 }" />
                    <div class="invalid-feedback">{{ errors.Address1 }}</div>
                </div>
            </div>
            <div class="col-12">
                <div class="form-group mb-3">
                    <label>Ghi chú</label>
                    <Field v-model="model.Note" name="Note" type="text" class="form-control" placeholder="Ghi chú" />
                </div>
            </div>
            <div class="col-12">
                <div class="form-check mb-3">
                    <input v-model="saveAddressChecked" class="form-check-input" type="checkbox" id="saveAddressCheck">
                    <label class="form-check-label" for="saveAddressCheck">
                        Lưu địa chỉ này
                    </label>
                </div>
                <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>
                        {{ model.Id ? 'Cập nhật' : 'Xác nhận' }}
                    </button>
                </div>
            </div>
        </Form>
    </div>
</template>
<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';



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

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

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

const props = defineProps({
    addType: Number,
    customerId: Number,
    editData: Object,
});
const emit = defineEmits(['cancel', 'submit']);

const loading = ref(false);
const model = reactive({
    Id: 0,
    Name: '',
    PhoneNumber1: '',
    Address1: '',
    CityId: null,
    DistrictId: null,
    WardId: null,
    CustomerId: props.customerId,
    AddressType: props.addType,
    Note: ''
});
const saveAddressChecked = ref(true);
const cityDistrictWardRef = ref(null);

//#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')
        .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ự'),
    Address1: Yup.string().required('Địa chỉ không để trống'),
});
//#endregion

function resetModel() {
    model.Id = 0;
    model.Name = '';
    model.PhoneNumber1 = '';
    model.Address1 = '';
    model.CityId = null;
    model.DistrictId = null;
    model.WardId = null;
    model.CustomerId = props.customerId;
    model.AddressType = props.addType;
    model.Note = '';
}

function mapApiToModel(apiData) {
    model.Id = apiData.Id || 0;
    model.Name = apiData.ContactName || '';
    model.PhoneNumber1 = apiData.ContactPhoneNumber || '';
    model.Address1 = apiData.Address || '';
    model.CityId = apiData.CityId || null;
    model.DistrictId = apiData.DistrictId || null;
    model.WardId = apiData.WardId || null;
    model.CustomerId = apiData.CustomerId || props.customerId;
    model.AddressType = apiData.AddressType || props.addType;
    model.Note = apiData.Note || '';
}

onMounted(() => {
    if (props.editData) {
        mapApiToModel(props.editData);
    } else {
        resetModel();
    }
});

watch(() => props.editData, (val) => {
    if (val) {
        mapApiToModel(val);
    } else {
        resetModel();
    }
});

async function getFullAddress() {
    if (!model.WardId) return model.Address1;
    const full = await locationService.getFullAddressByWard(model.WardId);
    return [model.Address1, full].filter(Boolean).join(', ');
}

async function submit() {
    loading.value = true;
    try {
        // Lấy giá trị địa danh đang chọn từ CityDistrictWard
        const currentSelection = cityDistrictWardRef.value?.getCurrentSelection?.();
        let fullAddress = await getFullAddress();
        let resultModel = { ...model, FullAddress: fullAddress };
        if (saveAddressChecked.value) {
            // Gọi API lưu/cập nhật địa chỉ
            let apiModel = {
                Id: model.Id || 0,
                Address: model.Address1,
                FullAddress: fullAddress,
                CityId: currentSelection.cityId,
                DistrictId: currentSelection.districtId,
                WardId: currentSelection.wardId,
                ContactPhoneNumber: model.PhoneNumber1,
                ContactName: model.Name,
                Note: model.Note,
                CustomerId: props.customerId,
                AddressType: props.addType,
                // Các trường khác nếu cần
            };
            const result = await customerAddressService.createOrUpdate(apiModel);
            if (result && result.Result === 1) {
                toast.success('Thành công!');
            } else {
                toast.error('Thất bại: ' + (result?.Message || 'Có lỗi xảy ra'));
            }
        }
        emit('submit', resultModel);
    } catch (error) {
        console.error('Lỗi khi submit:', error);
        toast.error('Có lỗi xảy ra khi xử lý yêu cầu');
    } finally {
        loading.value = false;
    }
}
function cancel() {
    emit('cancel');
}
//#endregion

</script>