<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý menu</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Quản lý menu</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 class="col-lg-3 col-md-4 mb-3">
                                <label>Trạng thái</label>
                                <v-select label="Name" :options="statuses"
                                    v-model="searchModel.Search.PredicateObject.Status"
                                    :reduce="(option) => option.Id"></v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Loại menu</label>
                                <v-select label="Name" :options="menuTypes"
                                    v-model="searchModel.Search.PredicateObject.MenuType"
                                    :reduce="(option) => option.Id"></v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Ứng dụng</label>
                                <v-select label="Name" :options="appTypes"
                                    v-model="searchModel.Search.PredicateObject.AppType"
                                    :reduce="(option) => option.Id"></v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Menu cha</label>
                                <v-select label="Label" :options="parents"
                                    v-model="searchModel.Search.PredicateObject.ParentId"
                                    :reduce="(option) => option.Id">
                                    <template v-slot:no-options="{ search, searching }">
                                        <template v-if="searching">
                                            Không có kết quả cho <em>{{ search }}</em>.
                                        </template>
                                        <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                    </template>
                                </v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Menu level</label>
                                <v-select label="Name" :options="menuLevels"
                                    v-model="searchModel.Search.PredicateObject.MenuLevel"
                                    :reduce="(option) => option.Id">
                                    <template v-slot:no-options="{ search, searching }">
                                        <template v-if="searching">
                                            Không có kết quả cho <em>{{ search }}</em>.
                                        </template>
                                        <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                    </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">
                            <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>Tạo
                                menu</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-12p min-width-2"><span>Menu</span></th>
                                        <th class="wd-lg-12p min-width-1"><span>Menu cha</span></th>
                                        <th class="wd-lg-12p min-width-1"><span>Ứng dụng</span></th>
                                        <th class="wd-lg-12p min-width-2"><span>Quyền cho phép</span></th>
                                        <th class="wd-lg-10p min-width-2"><span>Ngày tạo</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Thứ tự</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Trạng thái</span></th>
                                        <th class="wd-lg-8p"></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">

                                            <div>
                                                <span :class="item.IconClass"></span> {{ item.Label }}
                                            </div>
                                            <div>
                                                <span>Loại menu: {{ item.Kind }}</span>
                                            </div>
                                            <div>
                                                <span>Đường dẫn: {{ item.Url }}</span>
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.ParentName }}
                                            <div>
                                                <span>Level: {{ item.MenuLevel }}</span>
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.AppName }}
                                        </td>

                                        <td class="text-wrap align-top">
                                            {{ item.AllowRoles }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.CreatedTime }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.DisplayOrder }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span v-if="item.Status === 2" class="tag tag-indigo">Bị khóa</span>
                                            <span v-if="item.Status === 1" class="tag tag-green">Đang hoạt động</span>
                                        </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="lock(item.Id)" v-if="item.Status == 1" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-lock"></i>
                                                    <span class="mg-l-6">Khóa</span></a>
                                                <a @click="unlock(item.Id)" v-if="item.Status == 2"
                                                    class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fe fe-check"></i>
                                                    <span class="mg-l-6">Kích hoạt</span></a>
                                                <a @click="deleteMenu(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>
            </div><!-- COL END -->
        </div>
        <LadaDialog :visible="modalControl.CreateOrUpdate">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title" v-if="selectedId <= 0">Tạo menu</h5>
                    <h5 class="modal-title" v-if="selectedId > 0">Cập nhật menu</h5>
                    <button @click="closeModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <CreateOrUpdate @cancel="closeModal" :id="selectedId"></CreateOrUpdate>
            </template>

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

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


//#region Imports
import { ref, reactive, onMounted } from 'vue'
import menuService from "@/services/menuService";
//#endregion


//#region Components
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);
async function fnCreateOrUpdate(id) {
    selectedId.value = id;
    modalControl.CreateOrUpdate = true;
}


async function lock(id) {
    var cf = confirm("Bạn chắc chắn muốn khóa?");
    if (cf) {
        loading.value = true;
        var lockResult = await menuService.lock(id);
        if (lockResult != null && lockResult.Result === 1) {
            toast.success('Thành công!');
        } else {
            toast.error('Thất bại: ' + lockResult.Message);
        }
        loading.value = false;
        search();
    }
}
async function unlock(id) {
    var cf = confirm("Bạn chắc chắn muốn mở khóa?");
    if (cf) {
        loading.value = true;
        var lockResult = await menuService.unlock(id);

        if (lockResult != null && lockResult.Result === 1) {
            toast.success('Thành công!');
        } else {
            toast.error('Thất bại: ' + lockResult.Message);
        }
        loading.value = false;
        search();
    }
}
async function deleteMenu(id) {
    var cf = confirm("Bạn chắc chắn muốn xóa?");
    if (cf) {
        loading.value = true;
        var lockResult = await menuService.delete(id);

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

//#endregion


//#region SEARCH
const statuses = [
    { Id: 1, Name: 'Đang hoạt động' },
    { Id: 2, Name: 'Tạm dừng' }
];
const menuTypes = [
    { Id: 1, Name: 'Group' },
    { Id: 2, Name: 'Has Child' },
    { Id: 3, Name: 'Single' }
];
const appTypes = reactive([
    { Id: 1, Name: 'Hệ thống quản trị nội bộ' },
    { Id: 8, Name: 'Hệ thống khách hàng' },
    { Id: 2, Name: 'Hệ thống đào tạo' },
    { Id: 3, Name: 'Hệ thống quản lý tài khoản' }
]);


const menuLevels = reactive([
    { Id: 1, Name: 'Level 1' },
    { Id: 2, Name: 'Level 2' },
    { Id: 3, Name: 'Level 3' }
]);


const parents = reactive([]);

async function getParents() {
    parents.splice(0, parents.length);
    var parentResult = await menuService.getTree();
    if (parentResult != null && parentResult.length > 0) {
        parentResult.forEach(menu => {
            parents.push(menu);
        });
    }
}

const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            CreatedStart: null,
            CreatedEnd: null,
            Status: null,
            MenuType: null,
            AppType: null,
            MenuLevel: null,
        }
    }
});
const items = reactive([]);
const loading = ref(false);

const date = ref();
const createDatePicker = ref(DatepickerInstance);

const statusOptions = reactive([
    { Id: null, Name: "Tất cả" }, { Id: false, Name: "Đang hoạt động" }, { Id: true, Name: "Bị khóa" }
]);

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) {
    console.log(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();
}


// functions that mutate state and trigger updates
async function loadData() {
    loading.value = true;
    items.splice(0, items.length);
    var searchResult = await menuService.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 getParents();
    await search();
})

</script>
