<template>
    <div>
        <div v-if="loading" class="row">
            <div class="col-12 tx-semibold text-center text-default">
                <span class="spinner-border spinner-border-sm"></span>
            </div>
        </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>Tên {{ entityName }}</label>
                    <Field v-model="locationModel.Name" name="Name" type="text" class="form-control"
                        :placeholder="'tên ' + entityName" :class="{ 'is-invalid': errors.Name }" />
                    <div class="invalid-feedback">{{ errors.Name }}</div>
                </div>
            </div>
            <div class="col-6" v-if="props.level === 2 || props.level === 3">
                <div class="form-group mb-3">
                    <label>Tỉnh / thành phố</label>
                    <v-select v-if="props.level === 2" v-model="locationModel.ParentId" :reduce="(option) => option.Id"
                        label="Name" :filterable="false" :options="parents" @search="getCities">
                        <template slot="no-options">
                            gõ để tìm....
                        </template>
                    </v-select>
                    <v-select v-if="props.level === 3" v-model="selectedCityId" :reduce="(option) => option.Id"
                        label="Name" :filterable="false" :options="cities" @search="getCities">
                        <template slot="no-options">
                            gõ để tìm....
                        </template>
                    </v-select>
                </div>
            </div>
            <div class="col-6" v-if="props.level === 3">
                <div class="form-group mb-3">
                    <label>Quận / huyện</label>
                    <v-select v-model="locationModel.ParentId" :reduce="(option) => option.Id" label="Name"
                        :options="parents">
                        <template slot="no-options">
                            gõ để tìm....
                        </template>
                    </v-select>
                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Mô tả</label>
                    <Field v-model="locationModel.Description" name="Description" type="text" class="form-control"
                        placeholder="mô tả" />
                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Tiền tố</label>
                    <Field v-model="locationModel.Prefix" name="Prefix" type="text" class="form-control"
                        placeholder="tiền tố" :class="{ 'is-invalid': errors.Prefix }" />
                    <div class="invalid-feedback">{{ errors.Prefix }}</div>
                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Loại khu vực</label>
                    <Field as="select" v-model="locationModel.Type" name="Type" class="form-control">
                        <option :value="1">Nội thành</option>
                        <option :value="2">Ngoại thành</option>
                        <option :value="3">Chưa phục vụ</option>
                    </Field>
                </div>
            </div>

            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Thứ tự hiển thị</label>
                    <Field v-model="locationModel.DisplayOrder" name="DisplayOrder" type="number" class="form-control"
                        placeholder="thứ tự hiển thị" :class="{ 'is-invalid': errors.DisplayOrder }" />
                    <ErrorMessage class="invalid-error" name="DisplayOrder" />

                </div>
            </div>

            <div class="col-12 ">
                <div class="d-flex flex-row-reverse">
                    <button @click="cancel" type="button" class="btn btn-main-default mg-l-15">
                        Bỏ qua
                    </button>
                    <button type="submit" class="btn 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>

//#region Imports....
import { ref, onMounted, reactive, watch } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';
import _ from 'lodash';
//#endregion

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


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


//#region props
const props = defineProps({
    id: Number,
    level: Number
});
//#endregion

//#region props
//#endregion


const emit = defineEmits(['cancel']);


//#region Models
const loading = ref(false);

const entityName = ref('tỉnh / thành phố');

const parents = reactive([]);
const cities = reactive([]);
async function getCities(keyword, loading) {
    if (keyword.length) {
        loading(true);
        await loSugCities(loading, keyword);
    }
}

const selectedCityId = ref();
watch(selectedCityId, async (newCityId) => {
    if (newCityId != null && newCityId > 0) {
        parents.splice(0, parents.length);
        var parentResult = await locationService.loSug("", 1, newCityId);
        if (parentResult != null && parentResult.length > 0) {
            parentResult.forEach(district => {
                parents.push(district);
            });
        }
    } else {
        parents.splice(0, parents.length);
    }
})


let loSugCities = _.debounce(async (loading, keyword) => {
    if (props.level === 2) {
        parents.splice(0, parents.length);
        var parentResult = await locationService.loSug(keyword, 3, 0);
        if (parentResult != null && parentResult.length > 0) {
            parentResult.forEach(city => {
                parents.push(city);
            });
        }
    } else {
        cities.splice(0, parents.length);
        var parentResult = await locationService.loSug(keyword, 3, 0);
        if (parentResult != null && parentResult.length > 0) {
            parentResult.forEach(city => {
                cities.push(city);
            });
        }
    }
    loading(false);

}, 300);


let locationModel = reactive({
    Id: 0,
    Name: '',
    Description: '',
    Prefix: '',
    Level: props.level,
    DisplayOrder: 0,
    ParentId: null,
    Type: 1 // mặc định Urban
});

//#endregion

//#region Validations
const schema = Yup.object().shape({
    Name: Yup.string().required('Tên tỉnh / thành phố không để trống')

});
//#endregion

//#region Methods
async function getById(id) {

    var locationResult = await locationService.getById(id);
    locationModel.Id = locationResult.Id;
    locationModel.Name = locationResult.Name;
    locationModel.Description = locationResult.Description;
    locationModel.Prefix = locationResult.Prefix;
    locationModel.DisplayOrder = locationResult.DisplayOrder;
    locationModel.ParentId = locationResult.ParentId;
    locationModel.Type = locationResult.Type; // cập nhật Type

    if (locationModel.Level == 2) {
        parents.push({ Id: locationModel.ParentId, Name: locationResult.ParentName });
        locationModel.ParentId = locationModel.ParentId;
    }

    if (locationModel.Level == 3) {
        parents.push({ Id: locationModel.ParentId, Name: locationResult.ParentName });
        locationModel.ParentId = locationModel.ParentId;

        cities.push({ Id: locationModel.CityId, Name: locationResult.CityName });
        locationModel.selectedCityId = locationModel.CityId;
    }

}
async function onSubmit() {
    var paramModel = locationModel;
    if (paramModel.ParentId == null) {
        paramModel.ParentId = 0;
    }
    var cityResult = await locationService.createOrUpdate(paramModel);
    if (cityResult != null && cityResult.Result === 1) {
        toast.success('Thành công!');
        cancel();
    } else {
        toast.error('Thất bại: ' + cityResult.Message);
    }

}

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

//#endregion



//#region Events
onMounted(async () => {

    if (props.id > 0) {
        loading.value = true;
        await getById(props.id);
        loading.value = false;
    }

    if (props.level === 1) {
        entityName.value = 'tỉnh/thành phố';
    } else if (props.level === 2) {
        entityName.value = 'quận/huyện';
    } else if (props.level === 3) {
        entityName.value = 'phường/xã';
    }

})
//#endregion










</script>