
<template>
    <div>
        <div class="card card-search shadow-none">
            <form class="card-body pd-b-0" @submit.prevent="search">
                <div class="row">

                    <div class="col-md-6">
                        <fieldset class=" mg-b-10">
                            <legend class="float-none w-auto tx-14 tx-bold">Điểm đầu</legend>
                            <div class="row">

                                <div class="col-lg-4 col-md-6 mb-3">
                                    <label>Tỉnh/thành phố</label>
                                    <v-select v-model="selectedSourceCityId" :reduce="(option) => option.Id" label="Name"
                                        :filterable="false" :options="sourceCities" @search="getSourceCities">
                                        <template #no-options="{ search, searching, loading }">
                                            Gõ từ khóa để tìm....
                                        </template>
                                    </v-select>
                                </div>
                                <div class="col-lg-4 col-md-6 mb-3">
                                    <label>Quận/huyện</label>
                                    <v-select v-model="selectedSourceDistrictId" :reduce="(option) => option.Id"
                                        label="Name" :options="sourceDistricts">
                                        <template #no-options="{ search, searching, loading }">
                                            Gõ từ khóa để tìm....
                                        </template>
                                    </v-select>
                                </div>
                            </div>
                        </fieldset>
                    </div>
                    <div class="col-md-6">
                        <fieldset class="mg-b-10">
                            <legend class="float-none w-auto tx-14 tx-bold">Điểm cuối</legend>
                            <div class="row">

                                <div class="col-lg-4 col-md-6 mb-3">
                                    <label>Tỉnh/thành phố</label>
                                    <v-select v-model="selectedDestCityId" :reduce="(option) => option.Id" label="Name"
                                        :filterable="false" :options="destCities" @search="getDestCities">
                                        <template #no-options="{ search, searching, loading }">
                                            Gõ từ khóa để tìm....
                                        </template>
                                    </v-select>
                                </div>
                                <div class="col-lg-4 col-md-6 mb-3">
                                    <label>Quận/huyện</label>
                                    <v-select v-model="selectedDestDistrictId" :reduce="(option) => option.Id" label="Name"
                                        :options="destDistricts">
                                        <template #no-options="{ search, searching, loading }">
                                            Gõ từ khóa để tìm....
                                        </template>
                                    </v-select>
                                </div>
                            </div>
                        </fieldset>
                    </div>

                    <div class="col-lg-4 col-md-6 mb-3">
                        <label>Khoảng cách từ</label>
                        <input type="number" v-model="searchModel.Search.PredicateObject.DistanceFrom" class="form-control"
                            placeholder="từ khóa...">
                    </div>
                    <div class="col-lg-4 col-md-6 mb-3">
                        <label>Khoảng cách đến</label>
                        <input type="number" v-model="searchModel.Search.PredicateObject.DistanceTo" class="form-control"
                            placeholder="từ khóa...">
                    </div>
                </div>




                <div class="row">
                    <div class="col-lg mb-3">
                        <button type="submit" class="btn btn-dark" :disabled="loading">
                            <i v-show="!loading" class="fe fe-search"></i>
                            <span v-show="loading" class="spinner-border spinner-border-sm"></span>
                            <span>Tìm kiếm</span>
                        </button>
                        <!-- <button @click="getDistance" type="button" class="btn btn-dark">

                            <span>Tính khoảng cách</span>
                        </button> -->
                    </div>
                </div>


            </form>
        </div>


        <div class="card card-table shadow-none">
            <div class="card-body card-table-body">
                <div class="d-flex flex-row justify-content-between mg-b-10 mg-l-10">
                    <button :disabled="loading" @click="fnCreateOrUpdate(0)" type="button"
                        class="btn btn-outline-primary mx-2 button-icon mb-1">
                        <i v-show="!loading" class="fe fe-plus me-2"></i>

                        <span v-show="loading" class="spinner-border spinner-border-sm"></span>



                        <span>Tạo đầu cuối</span>
                    </button>
                    <button :disabled="loading" @click="autoGenerate" type="button"
                        class="btn btn-outline-success mx-2 button-icon mb-1">
                        <i v-show="!loading" class="fe fe-cpu me-2"></i>
                        <span v-show="loading" class="spinner-border spinner-border-sm"></span>
                        Tự động sinh
                    </button>
                </div>
                <div class="table-responsive border-top mg-b-10">
                    <table class="table table-vcenter mb-0" style="min-height:300px">
                        <thead>
                            <tr>
                                <th class="wd-lg-5p"><span>ID</span></th>
                                <th class="wd-lg-10p min-width-1"><span>Điểm đầu</span></th>

                                <th class="wd-lg-10p min-width-1"><span>Điểm cuối</span></th>

                                <th class="wd-lg-10p min-width-1"><span>Khoảng cách</span></th>
                                <th class="wd-lg-10p min-width-2"><span>Ngày tạo</span></th>
                                <th class="wd-lg-10p"></th>
                            </tr>
                        </thead>
                        <tbody v-if="loading">
                            <tr>
                                <td colspan="7" class="text-center">
                                    <Loader></Loader>
                                    <!-- <span class="spinner-border spinner-border-sm"></span> -->
                                </td>
                            </tr>
                        </tbody>
                        <tbody v-if="!loading && items.length <= 0">
                            <tr>
                                <td colspan="7" class="tx-semibold text-center text-danger">
                                    Không tìm thấy bản ghi nào!
                                </td>
                            </tr>
                        </tbody>
                        <tbody v-if="!loading && items.length > 0">

                            <tr v-for="item in items" :key="item.Id">

                                <td class="text-wrap align-top">
                                    {{ item.Id }}
                                </td>
                                <td class="text-wrap align-top">
                                    <span>{{ item.Start }}, {{ item.StartDistrict }}</span><br />
                                    <span>{{ item.StartCity }}</span>
                                </td>

                                <td class="text-wrap align-top">
                                    <span>{{ item.End }}, {{ item.EndDistrict }}</span><br />
                                    <span>{{ item.EndCity }}</span>
                                </td>

                                <td class="text-wrap align-top">
                                    {{ item.DistanceText }}
                                </td>
                                <td class="text-wrap align-top">
                                    {{ item.CreatedTime }}
                                </td>
                                <td class="align-top pt-2">

                                    <button type="button" data-bs-toggle="dropdown"
                                        class="mb-1 mt-1 mr-1 btn btn-light dropdown-toggle btn-sm" aria-expanded="false"><i
                                            class="fas fa-cog"></i> Quản lý
                                    </button>
                                    <div class="dropdown-menu dropdown-menu-arrow">
                                        <a @click="fnCreateOrUpdate(item.Id)" class="dropdown-item"
                                            href="javascript:void(0);"><i class="fe fe-edit-2"></i>
                                            <span class="mg-l-6">Cập nhật</span>
                                        </a>

                                        <a @click="deleteLocation(item.Id)" class="dropdown-item"
                                            href="javascript:void(0);">
                                            <i class="fe fe-trash"></i>
                                            <span class="mg-l-6">Xóa</span></a>

                                    </div>
                                </td>
                            </tr>

                        </tbody>
                    </table>
                </div>
                <pager ref="ctrlPager" v-show="!loading && items.length > 0" @PageSizeChanged="PageSizeChanged"
                    @PageIndexChanged="PageIndexChanged" :Total="searchModel.Pagination.Total" :TotalCurrent="items.length">
                </pager>
            </div>
        </div>
        <!-- <LadaDialog :visible="modalControl.CreateOrUpdate">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title" v-if="selectedId <= 0">Tạo tỉnh / thành phố</h5>
                    <h5 class="modal-title" v-if="selectedId > 0">Cập nhật tỉnh / thành phố</h5>
                    <button @click="closeModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <CreateOrUpdate @cancel="closeModal" :id="selectedId" :level="props.level"></CreateOrUpdate>
            </template>

        </LadaDialog> -->
    </div>
</template>

<script setup>
//#region Imports
//#endregion


//#region Imports
import { ref, reactive, onMounted, watch } from 'vue'
import endPointsService from "@/services/endPointsService";
import _ from 'lodash';
import locationService from "@/services/locationService";
//#endregion

//#region props
//1: city, 2: district, 3:ward
const props = defineProps({
    level: Number
});
//#endregion



//#region Components


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


//#region Modals
const modalControl = reactive({
    CreateOrUpdate: false
});
function closeModal() {
    modalControl.CreateOrUpdate = false;
    loadData();
}
//#endregion

//#region Actions
const selectedId = ref(0);
async function fnCreateOrUpdate(id) {
    selectedId.value = id;
    modalControl.CreateOrUpdate = true;
}


async function deleteLocation(id) {
    var cf = confirm("Bạn chắc chắn muốn xóa?");
    if (cf) {
        loading.value = true;
        var result = await locationService.delete(id);

        if (result != null && result.Result === 1) {
            toast.success('Thành công!');
        } else {
            toast.error('Thất bại: ' + result.Message);
        }
        loading.value = false;
        search();
    }
}

async function autoGenerate() {
    loading.value = true;
    items.splice(0, items.length);
    var result = await endPointsService.autoGenerate();
    if (result != null && result.Result === 1) {
        toast.success('Thành công!');
    } else {
        toast.error('Thất bại: ' + result.Message);
    }
    loading.value = false;
}

//#endregion


//#region SEARCH



const sourceCities = reactive([]);
const sourceDistricts = reactive([]);
const destCities = reactive([]);
const destDistricts = reactive([]);
const selectedSourceCityId = ref();
const selectedSourceDistrictId = ref();
const selectedDestCityId = ref();
const selectedDestDistrictId = ref();


watch(selectedSourceCityId, async (newCityId) => {
    sourceDistricts.splice(0, sourceDistricts.length);
    selectedSourceDistrictId.value = null;
    if (newCityId != null && newCityId > 0) {
        var districtResult = await locationService.loSug("", 1, newCityId);
        if (districtResult != null && districtResult.length > 0) {
            districtResult.forEach(district => {
                sourceDistricts.push(district);
            });
        }
    }
})

watch(selectedDestCityId, async (newCityId) => {
    destDistricts.splice(0, destDistricts.length);
    selectedDestDistrictId.value = null;
    if (newCityId != null && newCityId > 0) {
        var districtResult = await locationService.loSug("", 1, newCityId);
        if (districtResult != null && districtResult.length > 0) {
            districtResult.forEach(district => {
                destDistricts.push(district);
            });
        }
    }
})



async function getSourceCities(keyword, loading) {
    if (keyword.length) {
        loading(true);
        await loSugSourceCities(loading, keyword);
    }
}
let loSugSourceCities = _.debounce(async (loading, keyword) => {
    sourceCities.splice(0, sourceCities.length);
    var cityResult = await locationService.loSug(keyword, 3, 0);
    if (cityResult != null && cityResult.length > 0) {
        cityResult.forEach(city => {
            sourceCities.push(city);
        });
    }
    loading(false);

}, 300);

async function getDestCities(keyword, loading) {
    if (keyword.length) {
        loading(true);
        await loSugDestCities(loading, keyword);
    }
}
let loSugDestCities = _.debounce(async (loading, keyword) => {
    destCities.splice(0, destCities.length);
    var cityResult = await locationService.loSug(keyword, 3, 0);
    if (cityResult != null && cityResult.length > 0) {
        cityResult.forEach(city => {
            destCities.push(city);
        });
    }
    loading(false);

}, 300);





const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            SourceCityId: null,
            SourceDistrictId: null,
            DestCityId: null,
            DestDistrictId: null,
            DistanceFrom: null,
            DistanceTo: null
        }
    }
});
const items = reactive([]);
const loading = ref(false);


const ctrlPager = ref();
async function search() {
    searchModel.Pagination.PageIndex = 1;
    ctrlPager.value.Refresh();
    loadData();
}


// functions that mutate state and trigger updates
async function loadData() {
    loading.value = true;
    items.splice(0, items.length);
    // const selectedSourceCityId = ref();
    // const selectedSourceDistrictId = ref();
    // const selectedDestCityId = ref();
    // const selectedDestDistrictId = ref();
    if (searchModel.Search.PredicateObject.DistanceFrom == "") {
        searchModel.Search.PredicateObject.DistanceFrom = null;
    }
    if (searchModel.Search.PredicateObject.DistanceTo == "") {
        searchModel.Search.PredicateObject.DistanceTo = null;
    }
    if (selectedSourceCityId.value > 0) {
        searchModel.Search.PredicateObject.SourceCityId = selectedSourceCityId.value;
    } else {
        searchModel.Search.PredicateObject.SourceCityId = 0;
    }
    if (selectedSourceDistrictId.value > 0) {
        searchModel.Search.PredicateObject.SourceDistrictId = selectedSourceDistrictId.value;
    } else {
        searchModel.Search.PredicateObject.SourceDistrictId = 0;
    }
    if (selectedDestCityId.value > 0) {
        searchModel.Search.PredicateObject.DestCityId = selectedDestCityId.value;
    } else {
        searchModel.Search.PredicateObject.DestCityId = 0;
    }
    if (selectedDestDistrictId.value > 0) {
        searchModel.Search.PredicateObject.DestDistrictId = selectedDestDistrictId.value;
    } else {
        searchModel.Search.PredicateObject.DestDistrictId = 0;
    }





    var searchResult = await endPointsService.search(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(menu => {
            items.push(menu);
        });
    }
    searchModel.Pagination.Total = searchResult.TotalRecord;
    loading.value = false;
}


function PageSizeChanged(pagesize) {
    searchModel.Pagination.PageSize = pagesize;
    searchModel.Pagination.PageIndex = 1;
    loadData();
}
function PageIndexChanged(pageIndex) {
    searchModel.Pagination.PageIndex = pageIndex;
    loadData();
}

//#endregion


async function getDistance() {

    await endPointsService.calculateDistance();
}


onMounted(async () => {

    await search();
})

</script>

