<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý URL Record</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);">CMS</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Quản lý URL Record</li>
                </ol>
            </div>
        </div>
        <div class="row row-sm">
            <div class="col-12 grid-margin">
                <div class="card card-search shadow-none mb-5">
                    <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ìm theo slug, entity...">
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Loại thực thể</label>
                                <select v-model="searchModel.Search.PredicateObject.EntityType" class="form-control">
                                    <option :value="null">Tất cả</option>
                                    <option value="1">Bài viết</option>
                                    <option value="2">Tag</option>
                                    <option value="3">Danh mục</option>
                                    <option value="4">Topic</option>
                                    <option value="5">Dịch vụ</option>
                                    <option value="6">Việc làm</option>
                                </select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Trạng thái</label>
                                <select v-model="searchModel.Search.PredicateObject.IsActive" class="form-control">
                                    <option :value="null">Tất cả</option>
                                    <option :value="true">Hoạt động</option>
                                    <option :value="false">Ẩn</option>
                                </select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>IncludeInSiteMap</label>
                                <select v-model="searchModel.Search.PredicateObject.IncludeInSiteMap"
                                    class="form-control">
                                    <option :value="null">Tất cả</option>
                                    <option :value="true">Có</option>
                                    <option :value="false">Không</option>
                                </select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Tần suất (Frequency)</label>
                                <select v-model="searchModel.Search.PredicateObject.Frequency" class="form-control">
                                    <option :value="null">Tất cả</option>
                                    <option :value="1">Không bao giờ</option>
                                    <option :value="2">Hàng năm</option>
                                    <option :value="3">Hàng tháng</option>
                                    <option :value="4">Hàng tuần</option>
                                    <option :value="5">Hàng ngày</option>
                                    <option :value="6">Hàng giờ</option>
                                    <option :value="7">Liên tục</option>
                                </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 class="card-body bd p-0">
                        <div class="table-responsive border-top mg-b-10">
                            <table class="table table-vcenter mb-0" style="min-height:300px">
                                <thead>
                                    <tr>
                                        <th>Id</th>
                                        <th class="wd-lg-40p min-width-2">Thông tin</th>
                                        <th class="wd-lg-15p min-width-1">EntityName</th>
                                        <th class="wd-lg-15p min-width-1">EntityId</th>
                                        <th class="wd-lg-15p min-width-1">IsActive</th>
                                        <th class="wd-lg-15p min-width-1">Ngày tạo</th>
                                        <th class="wd-lg-10p min-width-1">Thao tác</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>{{ item.Id }}</td>
                                        <td>
                                            <div class="mb-1" v-if="item.MetaTitle">
                                                <strong>MetaTitle:</strong> {{ item.MetaTitle }}
                                            </div>
                                            <div class="mb-1" v-if="item.MetaDescription">
                                                <strong>MetaDescription:</strong> {{ item.MetaDescription }}
                                            </div>
                                            <div class="mb-1" v-if="item.MetaKeywords">
                                                <strong>MetaKeywords:</strong> {{ item.MetaKeywords }}
                                            </div>
                                            <div class="mb-1">
                                                <strong>IncludeInSiteMap:</strong>
                                                <span v-if="item.IncludeInSiteMap" class="text-success">Có</span>
                                                <span v-else class="text-danger">Không</span>
                                            </div>
                                            <div class="mb-1" v-if="item.Priority">
                                                <strong>Priority:</strong> {{ item.Priority }}
                                            </div>
                                            <div class="mb-1" v-if="item.Priority">
                                                <strong>Frequency:</strong> {{ getFrequencyDescription(item.Frequency)
                                                }}
                                            </div>
                                            <div class="mb-1">
                                                <strong>Slug:</strong>
                                                <a :href="`${frontendURL}${item.Slug}`" target="_blank"
                                                    class="text-primary">
                                                    {{ item.Slug }}
                                                </a>
                                            </div>
                                        </td>
                                        <td>{{ item.EntityName }}</td>
                                        <td>{{ item.EntityIdInt }}</td>
                                        <td>
                                            <span v-if="item.IsActive" class="tag bg-success" style="color:white">Hoạt
                                                động</span>
                                            <span v-else class="tag bg-danger" style="color:white">Ẩn</span>
                                        </td>
                                        <td>{{ item.CreatedTimeDisplay }}</td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-outline-primary"
                                                @click="editItem(item)" title="Chỉnh sửa">
                                                <i class="fe fe-edit-2"></i>
                                            </button>
                                        </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>
    </div>

    <LadaDialog :visible="modalControl.Edit">
        <template #header>
            <div class="modal-header">
                <h5 class="modal-title">Chỉnh sửa URL Record</h5>
                <button @click="closeModal" type="button" class="close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        </template>
        <template #body>
            <form @submit.prevent="saveItem">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>MetaTitle</label>
                        <input type="text" v-model="editModel.MetaTitle" class="form-control"
                            placeholder="Nhập MetaTitle">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label>Priority</label>
                        <input type="number" v-model="editModel.Priority" class="form-control"
                            placeholder="Nhập Priority" min="0" max="1" step="0.1">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label>Frequency</label>
                        <select v-model="editModel.Frequency" class="form-control">
                            <option :value="1">Không bao giờ</option>
                            <option :value="2">Hàng năm</option>
                            <option :value="3">Hàng tháng</option>
                            <option :value="4">Hàng tuần</option>
                            <option :value="5">Hàng ngày</option>
                            <option :value="6">Hàng giờ</option>
                            <option :value="7">Liên tục</option>
                        </select>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12 mb-3">
                        <label>MetaDescription</label>
                        <textarea v-model="editModel.MetaDescription" class="form-control" rows="3"
                            placeholder="Nhập MetaDescription"></textarea>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12 mb-3">
                        <label>MetaKeywords</label>
                        <input type="text" v-model="editModel.MetaKeywords" class="form-control"
                            placeholder="Nhập MetaKeywords">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>IncludeInSiteMap</label>
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="includeInSiteMap"
                                v-model="editModel.IncludeInSiteMap">
                            <label class="custom-control-label" for="includeInSiteMap">Bao gồm trong sitemap</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @click="closeModal">
                        <i class="fe fe-x me-1"></i>Hủy
                    </button>
                    <button type="button" class="btn btn-primary" @click="saveItem" :disabled="saving">
                        <span v-show="saving" class="spinner-border spinner-border-sm me-1"></span>
                        <i v-show="!saving" class="fe fe-save me-1"></i>
                        <span>Lưu</span>
                    </button>
                </div>
            </form>
        </template>
    </LadaDialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import urlRecordService from '@/services/cms/urlRecordService';
import Pager from '@/components/pagination/pager.vue';

const frontendURL = import.meta.env.VITE_FRONT_END_URL;

const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            EntityType: null,
            IsActive: null,
            IncludeInSiteMap: null,
            Frequency: null
        }
    }
});
const items = reactive([]);
const loading = ref(false);
const ctrlPager = ref();

const editModel = reactive({
    Id: 0,
    MetaTitle: '',
    MetaDescription: '',
    MetaKeywords: '',
    IncludeInSiteMap: false,
    Priority: 0,
    Frequency: 1
});
const saving = ref(false);

const modalControl = reactive({
    Edit: false
});

// Hàm chuyển đổi Frequency sang mô tả tiếng Việt
function getFrequencyDescription(frequency) {
    switch (frequency) {
        case 1: return 'Không bao giờ';
        case 2: return 'Hàng năm';
        case 3: return 'Hàng tháng';
        case 4: return 'Hàng tuần';
        case 5: return 'Hàng ngày';
        case 6: return 'Hàng giờ';
        case 7: return 'Liên tục';
        default: return '';
    }
}

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

async function loadData() {
    loading.value = true;
    items.splice(0, items.length);

    var searchResult = await urlRecordService.search(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(item => {
            items.push(item);
        });
    }
    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();
}

function editItem(item) {
    editModel.Id = item.Id;
    editModel.MetaTitle = item.MetaTitle || '';
    editModel.MetaDescription = item.MetaDescription || '';
    editModel.MetaKeywords = item.MetaKeywords || '';
    editModel.IncludeInSiteMap = item.IncludeInSiteMap || false;
    editModel.Priority = item.Priority || 0;
    editModel.Frequency = item.Frequency || 1;

    // Mở modal bằng LadaDialog
    modalControl.Edit = true;
}

async function saveItem() {
    saving.value = true;
    try {
        await urlRecordService.updateInfo(editModel);
        modalControl.Edit = false;
        await loadData(); // Reload data
        // Có thể thêm thông báo thành công ở đây
    } catch (error) {
        console.error('Lỗi khi cập nhật:', error);
        // Có thể thêm thông báo lỗi ở đây
    } finally {
        saving.value = false;
    }
}

function closeModal() {
    modalControl.Edit = false;
}

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

<style lang="css">
.tag {
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 0.85em;
}

.cursor-pointer {
    cursor: pointer;
}

.cursor-pointer:hover {
    opacity: 0.7;
}
</style>