<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-lg-3 col-md-4 mb-3">
                        <label>Từ khóa</label>
                        <input type="text" v-model="searchModel.Search.PredicateObject.Keyword" class="form-control"
                            placeholder="từ khóa...">
                    </div>
                    <div class="col-lg-3 col-md-4 mb-3" v-if="props.level === 2 || props.level === 3">
                        <label>Tỉnh/thành phố</label>
                        <v-select v-if="props.level === 2 || props.level === 3" v-model="selectedCityId"
                            :reduce="(option) => option.Id" label="Name" :filterable="false" :options="cities"
                            @search="getCities">
                            <template #no-options="{ search, searching, loading }">
                                Gõ từ khóa để tìm....
                            </template>
                        </v-select>
                    </div>
                    <div class="col-lg-3 col-md-4 mb-3" v-if="props.level === 3">
                        <label>Quận/huyện</label>

                        <v-select v-model="selectedDistrictId" :reduce="(option) => option.Id" label="Name"
                            :options="districts">
                            <template #no-options="{ search, searching, loading }">
                                Gõ từ khóa để tìm....
                            </template>
                        </v-select>
                    </div>
                    <div class="col-lg-3 col-md-4 mb-3">
                        <label>Loại khu vực</label>
                        <v-select v-model="searchModel.Search.PredicateObject.Type" :reduce="(option) => option.Id"
                            label="Name" :options="locationTypes">
                            <template slot="no-options">
                                gõ để tìm....
                            </template>
                        </v-select>
                    </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>
                    </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 @click="fnCreateOrUpdate(0)" type="button"
                        class="btn btn-outline-primary mx-2 button-icon mb-1">
                        <i class="fe fe-plus me-2"></i>
                        <span v-if="props.level === 1">Tạo tỉnh / thành phố</span>
                        <span v-if="props.level === 2">Tạo quận / huyện</span>
                        <span v-if="props.level === 3">Tạo phường / xã</span>
                    </button>
                    <!-- <button type="button" class="btn btn-outline-success mx-2 button-icon mb-1">
                                <i class="fe fe-download me-2"></i>Xuất excel</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-15p min-width-1"><span>Tiền tố + tên</span></th>

                                <th v-if="props.level == 2 || props.level == 3" class="wd-lg-15p min-width-1">
                                    <span v-if="props.level == 2">Tỉnh/thành phố</span>
                                    <span v-if="props.level == 3">Quận/huyện - Tỉnh/thành phố</span>
                                </th>
                                <th class="wd-lg-15p min-width-1">
                                    <span>Vùng phủ</span>
                                </th>
                                <th v-if="props.level == 3" class="wd-lg-15p min-width-1">
                                    <span>LatLong</span>
                                </th>
                                <th class="wd-lg-15p min-width-2"><span>Ngày tạo</span></th>
                                <th class="wd-lg-20p min-width-1"><span>Thứ tự</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">
                                    {{ item.Prefix }}
                                    <b>{{ item.Name }}</b>
                                    <small>{{ item.Description }}</small>
                                </td>

                                <td v-if="props.level == 2 || props.level == 3" class="text-wrap align-top">
                                    <span v-if="props.level == 3">{{ item.District }}, {{ item.City }}</span>
                                    <span v-if="props.level == 2"> {{ item.City }}</span>
                                </td>
                                <td class="text-wrap align-top">
                                    <span> {{ item.Type }}</span>
                                </td>
                                <td v-if="props.level == 3" class="text-wrap align-top">
                                    {{ item.Lat }}
                                    {{ item.Long }}
                                    <a v-clipboard="item.Lat + ',' + item.Long"
                                        v-clipboard:success="clipboardSuccessHandler" href="javascript:void(0);"
                                        class="fe fe-clipboard"></a>
                                </td>
                                <td class="text-wrap align-top">
                                    {{ item.CreatedTime }}
                                </td>
                                <td class="text-wrap align-top">
                                    {{ item.DisplayOrder }}
                                </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 _ 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 { LadaDialog, DateRangeSidebar } from '@/components/index';
import CreateOrUpdate from './createOrUpdate.vue';

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();
    }
}


function clipboardSuccessHandler(text) {
    toast.success('Đã copy!');
}

//#endregion


//#region SEARCH

const cities = reactive([]);
const districts = reactive([]);
const locationTypes = [
    { Id: 1, Name: "Nội thành" },
    { Id: 2, Name: "Ngoại thành" },
    { Id: 3, Name: "Chưa phục vụ" }
];
const selectedCityId = ref();
const selectedDistrictId = ref();
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            Level: props.level,
            CityId: null,
            DistrictId: null,
            Type: null
        }
    }
});

async function getCities(keyword, loading) {
    if (keyword.length) {
        loading(true);
        await loSugCities(loading, keyword);
    }
}

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

}, 300);

watch(selectedCityId, async (newCityId) => {
    districts.splice(0, districts.length);
    selectedDistrictId.value = null;
    if (newCityId != null && newCityId > 0) {
        districts.splice(0, districts.length);
        var districtResult = await locationService.loSug("", 1, newCityId);
        if (districtResult != null && districtResult.length > 0) {
            districtResult.forEach(district => {
                districts.push(district);
            });
        }
    }
})
// let loSugCities = 


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() {
    console.log(selectedCityId.value);
    if (selectedCityId.value > 0) {
        searchModel.Search.PredicateObject.CityId = selectedCityId.value;
    } else {
        searchModel.Search.PredicateObject.CityId = 0;
    }
    if (selectedDistrictId.value > 0) {
        searchModel.Search.PredicateObject.DistrictId = selectedDistrictId.value;
    } else {
        searchModel.Search.PredicateObject.DistrictId = 0;
    }
    loading.value = true;
    items.splice(0, items.length);
    var searchResult = await locationService.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



onMounted(async () => {

    await search();
})

</script>
