<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý cấu hình ứng dụng</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Hệ thống</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Cấu hình ứng dụng</li>
                </ol>
            </div>
        </div>
        <div class="row row-sm">
            <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
                <div class="card card-search shadow-none">
                    <form class="card-body" @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">
                                <label>Ngày tạo</label>
                                <VueDatePicker ref="createDatePicker" v-model="date" :enable-time-picker="false" range
                                    multi-calendars auto-apply :format="format" @update:model-value="handleDate">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </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 type="button" @click="resetSearch" class="btn btn-outline-secondary ms-2">
                                    <i class="fe fe-refresh-cw"></i>
                                    <span>Reset</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">
                            <div>
                                <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>
                                    Thêm cấu hình
                                </button>
                                <button @click="reloadCache" type="button"
                                    class="btn btn-outline-success mx-2 button-icon mb-1" :disabled="cacheLoading">
                                    <i v-show="!cacheLoading" class="fe fe-refresh-cw me-2"></i>
                                    <span v-show="cacheLoading" class="spinner-border spinner-border-sm me-2"></span>
                                    Reload Cache
                                </button>
                            </div>
                        </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-15p min-width-2"><span>Key</span></th>
                                        <th class="wd-lg-20p min-width-3"><span>Value</span></th>
                                        <th class="wd-lg-25p min-width-3"><span>Mô tả</span></th>
                                        <th class="wd-lg-12p min-width-1"><span>Ngày tạo</span></th>
                                        <th class="wd-lg-12p min-width-1"><span>Cập nhật lần cuối</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Người cập nhật</span></th>
                                        <th class="wd-lg-6p"></th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="7" class="tx-semibold text-center text-default">
                                            <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">
                                            <code class="text-primary">{{ item.Key }}</code>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <div class="value-cell" :title="item.Value">
                                                {{ truncateText(item.Value, 100) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <div :title="item.Description">
                                                {{ truncateText(item.Description, 150) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <small>{{ formatDate(item.CreatedTime) }}</small>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <small>{{ formatDate(item.UpdatedTime) }}</small>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <small>{{ item.UpdatedByUserName }}</small>
                                        </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="deleteConfig(item.Id, item.Key)"
                                                    class="dropdown-item text-danger" href="javascript:void(0);">
                                                    <i class="fe fe-trash-2"></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>
            </div>
        </div>

        <LadaDialog :visible="modalControl.CreateOrUpdate">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title" v-if="selectedId <= 0">Thêm cấu hình mới</h5>
                    <h5 class="modal-title" v-if="selectedId > 0">Cập nhật cấu hình</h5>
                    <button @click="closeModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <CreateOrUpdate @cancel="closeModal" @success="closeModal" :id="selectedId"></CreateOrUpdate>
            </template>
        </LadaDialog>
    </div>
</template>

<script setup>
//#region Imports
import { ref, reactive, onMounted } from 'vue'
import appConfigService from "@/services/appConfigService";
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';
import CreateOrUpdate from './components/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);
const cacheLoading = ref(false);

async function fnCreateOrUpdate(id) {
    selectedId.value = id;
    modalControl.CreateOrUpdate = true;
}

async function deleteConfig(id, key) {
    var cf = confirm(`Bạn chắc chắn muốn xóa cấu hình "${key}"?`);
    if (cf) {
        loading.value = true;
        var deleteResult = await appConfigService.delete(id);
        if (deleteResult != null && deleteResult.Result === 1) {
            toast.success('Xóa thành công!');
            loadData();
        } else {
            toast.error('Thất bại: ' + deleteResult.Message);
        }
        loading.value = false;
    }
}

async function reloadCache() {
    cacheLoading.value = true;
    var cacheResult = await appConfigService.reloadCache();
    if (cacheResult != null && cacheResult.Result === 1) {
        toast.success('Reload cache thành công!');
    } else {
        toast.error('Thất bại: ' + cacheResult.Message);
    }
    cacheLoading.value = false;
}
//#endregion

//#region SEARCH
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            CreatedStart: null,
            CreatedEnd: null,
        }
    }
});

const items = reactive([]);
const loading = ref(false);
const date = ref();
const createDatePicker = ref(DatepickerInstance);

const format = (dates) => {
    let start = dates[0];
    let end = dates[1];
    const dayStart = start.getDate();
    const monthStart = start.getMonth() + 1;
    const yearStart = start.getFullYear();
    const dayEnd = end.getDate();
    const monthEnd = end.getMonth() + 1;
    const yearEnd = end.getFullYear();

    return `${dayStart}/${monthStart}/${yearStart} - ${dayEnd}/${monthEnd}/${yearEnd}`;
}

async function onChangeDate(newDates) {
    date.value = newDates;
    createDatePicker.value.closeMenu();
    handleDate(newDates)
}

function handleDate(modelData) {
    if (modelData != null) {
        searchModel.Search.PredicateObject.CreatedStart = modelData[0];
        searchModel.Search.PredicateObject.CreatedEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.CreatedStart = null;
        searchModel.Search.PredicateObject.CreatedEnd = null;
    }
}

const ctrlPager = ref();

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

function resetSearch() {
    searchModel.Search.PredicateObject.Keyword = '';
    searchModel.Search.PredicateObject.CreatedStart = null;
    searchModel.Search.PredicateObject.CreatedEnd = null;
    date.value = null;
    search();
}

async function loadData() {
    loading.value = true;
    items.splice(0, items.length);
    var searchResult = await appConfigService.search(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(config => {
            items.push(config);
        });
    }
    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

//#region Utilities
function truncateText(text, maxLength) {
    if (!text) return '';
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
}

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('vi-VN') + ' ' + date.toLocaleTimeString('vi-VN', {
        hour: '2-digit',
        minute: '2-digit'
    });
}
//#endregion

onMounted(async () => {
    await search();
})
</script>

<style scoped>
.value-cell {
    max-width: 200px;
    word-break: break-word;
}

code {
    font-size: 0.875em;
    padding: 2px 4px;
    border-radius: 3px;
    background-color: #f8f9fa;
}
</style>
