<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý ScriptConfig</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">ScriptConfig</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="onSearch">
                        <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 tên, mô tả...">
                            </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">Không hoạt động</option>
                                </select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Vị trí</label>
                                <select v-model="searchModel.Search.PredicateObject.Position" class="form-control">
                                    <option :value="null">Tất cả</option>
                                    <option :value="0">Header</option>
                                    <option :value="1">Body</option>
                                    <option :value="2">Footer</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>
                <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="openModal(0)" type="button"
                                class="btn btn-outline-primary mx-2 button-icon mb-1">
                                <i class="fe fe-plus me-2"></i>Tạo ScriptConfig
                            </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>ID</th>
                                        <th>Tên</th>
                                        <th>Nội dung Script</th>
                                        <th>Hoạt động</th>
                                        <th>Vị trí</th>
                                        <th>Mô tả</th>
                                        <th></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>{{ item.Name }}</td>
                                        <td>
                                            <pre
                                                style="max-width:300px;white-space:pre-wrap;word-break:break-all;">{{ item.ScriptContent }}</pre>
                                        </td>
                                        <td>
                                            <span
                                                :class="item.IsActive ? 'uk-label uk-label-success' : 'uk-label uk-label-danger'">
                                                {{ item.IsActive ? 'Có' : 'Không' }}
                                            </span>
                                        </td>
                                        <td>{{ getPositionName(item.Position) }}</td>
                                        <td>{{ item.Description }}</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="openModal(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="deleteScript(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 && total > 0" @PageSizeChanged="onPageSizeChanged"
                            @PageIndexChanged="onPageIndexChanged" :Total="total" :TotalCurrent="items.length" />
                    </div>
                </div>
            </div>
        </div>
        <lada-dialog :visible="modalVisible" @close="closeModal">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">{{ selectedId > 0 ? 'Cập nhật' : 'Tạo mới' }} ScriptConfig</h5>
                    <button @click="closeModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <CreateOrUpdate :id="selectedId" @cancel="closeModal" @submit="onSubmit" />
            </template>
        </lada-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import pager from '@/components/pagination/pager.vue';
import ladaDialog from '@/components/dialogs/ladaDialog.vue';
import CreateOrUpdate from './components/CreateOrUpdate.vue';
import scriptConfigService from '@/services/cms/scriptConfigService';
import { useToast } from "vue-toastification";

const toast = useToast();
const items = ref([]);
const loading = ref(false);
const total = ref(0);
const pageIndex = ref(1);
const pageSize = ref(25);

const modalVisible = ref(false);
const selectedId = ref(0);
const ctrlPager = ref();

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

function getPositionName(pos) {
    const map = {
        1: 'Header',
        2: 'Body',
        3: 'Footer',
    };
    return map[pos] || pos;
}

function openModal(id) {
    selectedId.value = id;
    modalVisible.value = true;
}

function closeModal() {
    modalVisible.value = false;
    selectedId.value = 0;
}

async function onSubmit(data) {
    loading.value = true;
    const result = await scriptConfigService.createOrUpdate(data);
    if (result && result.Result === 1) {
        toast.success('Thành công!');
        closeModal();
        loadData();
    } else {
        toast.error('Thất bại: ' + (result?.Message || 'Không xác định'));
    }
    loading.value = false;
}

async function deleteScript(id) {
    if (confirm('Bạn chắc chắn muốn xóa?')) {
        loading.value = true;
        const result = await scriptConfigService.delete(id);
        if (result && result.Result === 1) {
            toast.success('Xóa thành công!');
            loadData();
        } else {
            toast.error('Xóa thất bại: ' + (result?.Message || 'Không xác định'));
        }
        loading.value = false;
    }
}

function onPageSizeChanged(size) {
    searchModel.Pagination.PageSize = size;
    searchModel.Pagination.PageIndex = 1;
    loadData();
}

function onPageIndexChanged(index) {
    searchModel.Pagination.PageIndex = index;
    loadData();
}

async function loadData() {
    loading.value = true;
    items.value = [];
    const result = await scriptConfigService.search(searchModel);
    if (result) {
        if (result.Items && result.Items.length > 0) {
            items.value = result.Items;
        }
        total.value = result.TotalRecord || 0;
    }
    loading.value = false;
}

function onSearch() {
    searchModel.Pagination.PageIndex = 1;
    loadData();
}

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

<style scoped>
.uk-label-success {
    background: #32d296;
}

.uk-label-danger {
    background: #f0506e;
}
</style>