<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý quyền</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ý quyền</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="searchRefresh">
                        <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>
                                        <LeftSidebar @change-date="onChangeDate"></LeftSidebar>
                                    </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>
                            </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="create" type="button"
                                class="btn btn-outline-primary mx-2 button-icon mb-1"><i class="fe fe-plus me-2"></i>Tạo
                                quyền</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-15p min-width-2"><span>Tên quyền</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>Mô tả</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>Ngày tạo</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>Người tạo</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>Ngày cập nhật</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>Người cập nhật</span></th>
                                        <th class="wd-lg-10p"></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>{{ item.Name }}</div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.Description }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.CreatedTime }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.CreatedBy }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.UpdatedTime }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.UpdatedBy }}
                                        </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="update(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);"><i class="fe fe-edit-2"></i>
                                                    <span class="mg-l-6">Sửa</span>
                                                </a>
                                                <a @click="deleteRole(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-lock"></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="showModal">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Tạo quyền</h5>
                    <button @click="closeDialog" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <CreateOrUpdateRole @cancel="closeDialog" :id="selectedId"></CreateOrUpdateRole>
            </template>
        </LadaDialog>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { CreateOrUpdateRole } from './components';
import roleService from "@/services/roleService";
import { useToast } from "vue-toastification";
import LeftSidebar from "@/components/daterange/left-sidebar.vue";
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog } from '@/components/index';

const toast = useToast();

const selectedId = ref(0);
const showModal = ref(false);
const items = reactive([]);
const loading = ref(false);
const date = ref();
const createDatePicker = ref(DatepickerInstance);
const ctrlPager = ref();

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

// functions that mutate state and trigger updates
async function search() {
    loading.value = true;
    items.splice(0, items.length);
    var searchResult = await roleService.search(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(role => {
            items.push(role);
        });
    }
    searchModel.Pagination.Total = searchResult.TotalRecord;
    loading.value = false;
}

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

function PageSizeChanged(pagesize) {
    searchModel.Pagination.PageSize = pagesize;
    searchModel.Pagination.PageIndex = 1;
    search();
}

function PageIndexChanged(pageIndex) {
    searchModel.Pagination.PageIndex = pageIndex;
    search();
}

// functions that mutate state and trigger updates
async function deleteRole(roleId) {
    var cf = confirm("Bạn chắc chắn muốn xóa?");
    if (cf) {
        var deleteResult = await roleService.delete(roleId);
        if (deleteResult != null && deleteResult.Result === 1) {
            toast.success('Thành công!');
        } else {
            toast.error('Thất bại: ' + deleteResult.message);
        }
    }
    search();
}

function create() {
    selectedId.value = 0;
    showModal.value = true;
}

function update(roleId) {
    selectedId.value = roleId;
    showModal.value = true;
}

function closeDialog() {
    showModal.value = false;
    search();
}

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) {
    console.log('update gia tri moi');
    console.log(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;
    }
}

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