<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý vai trò</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ý vai trò</li>
                </ol>
            </div>
        </div>
        <div class="row row-sm">
            <div class="col-12 grid-margin">
                <div class="card card-search shadow-none">
                    <form class="card-body" @submit.prevent="search">
                        <div class="row">
                            <div class="col-lg-4 col-md-6 mb-3">
                                <label>Từ khóa</label>
                                <input v-model="searchModel.Search.PredicateObject.Keyword" class="form-control"
                                    placeholder="Tìm kiếm vai trò..." />
                            </div>
                            <div class="col-lg mb-3 d-flex align-items-end">
                                <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="openForm()" type="button"
                                class="btn btn-outline-primary mx-2 button-icon mb-1">
                                <i class="fe fe-plus me-2"></i>Thêm vai trò
                            </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-20p min-width-2"><span>Tên vai trò</span></th>
                                        <th class="wd-lg-20p 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="permission in items" :key="permission.Id">
                                        <td class="text-wrap align-top">{{ permission.Name }}</td>
                                        <td class="text-wrap align-top">{{ permission.Description }}</td>
                                        <td class="text-wrap align-top">{{ formatDateTime(permission.CreatedTime) }}
                                        </td>
                                        <td class="text-wrap align-top">{{ permission.CreatedByUserName || '-' }}</td>
                                        <td class="text-wrap align-top">{{ formatDateTime(permission.UpdatedTime) }}
                                        </td>
                                        <td class="text-wrap align-top">{{ permission.UpdatedByUserName || '-' }}</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="openForm(permission)" 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="deletePermission(permission.Id)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-trash"></i> <span class="mg-l-6">Xóa</span>
                                                </a>
                                                <a @click="openRole(permission)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-user-check"></i> <span class="mg-l-6">Phân
                                                        quyền</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="showForm">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">{{ selectedPermission && selectedPermission.Id ?
                        'Sửa vai trò' : 'Thêm vai trò' }}</h5>
                    <button @click="closeForm" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <PermissionForm :permission="selectedPermission" @close="closeForm" @saved="search" />
            </template>
        </LadaDialog>
        <LadaDialog :visible="showRole">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Phân quyền cho vai trò</h5>
                    <button @click="closeRole" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <PermissionRole :permission="selectedPermission" @close="closeRole" />
            </template>
        </LadaDialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import PermissionForm from './PermissionForm.vue';
import PermissionRole from './PermissionRole.vue';
import permissionService from '@/services/permissionService';
import { LadaDialog } from '@/components/index';

const items = reactive([]);
const loading = ref(false);
const showForm = ref(false);
const showRole = ref(false);
const selectedPermission = ref(null);
const ctrlPager = ref();

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

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

async function loadData() {
    loading.value = true;
    items.splice(0, items.length);
    const res = await permissionService.getList(searchModel);
    if (res && res.Items && res.Items.length > 0) {
        res.Items.forEach(p => items.push(p));
    }
    searchModel.Pagination.Total = res && res.TotalRecord ? res.TotalRecord : 0;
    loading.value = false;
}

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

function openForm(permission = null) {
    selectedPermission.value = permission;
    showForm.value = true;
}

function closeForm() {
    showForm.value = false;
    selectedPermission.value = null;
}

async function deletePermission(id) {
    if (confirm('Bạn có chắc muốn xóa vai trò này?')) {
        await permissionService.delete(id);
        search();
    }
}

function openRole(permission) {
    selectedPermission.value = permission;
    showRole.value = true;
}

function closeRole() {
    showRole.value = false;
    selectedPermission.value = null;
}

function formatDateTime(dateTimeString) {
    if (!dateTimeString) return '-';
    try {
        const date = new Date(dateTimeString);
        return date.toLocaleString('vi-VN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    } catch (error) {
        return dateTimeString;
    }
}

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