<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý bài viết</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ý bài viết</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 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ừ 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>Danh mục bài viết</label>
                                <v-select label="Name" :options="categories"
                                    v-model="searchModel.Search.PredicateObject.CategoryId"
                                    :reduce="option => option.Id" placeholder="Chọn danh mục" />
                            </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="d-flex mb-3 pd-l-10 pd-t-10 pd-b-10 bd-b">
                            <div class="flex-grow-1 pd-t-10 pd-l-10">
                                <b>Bài viết</b>
                            </div>
                            <div class="pd-r-10">
                                <button @click="fnCreateOrUpdate(0)" type="button"
                                    class="btn btn-primary mx-2 button-icon mb-1">
                                    <i class="fe fe-plus me-2"></i>
                                    Tạo bài viết
                                </button>
                            </div>

                        </div>
                        <div class="row bd-b p-3 pd-t-1" v-for="item in items">
                            <div class="col">
                                <h6 class="tx-16">
                                    <a @click="fnCreateOrUpdate(item.Id)" href="javascript:void(0);"
                                        style="color: #242f48;">{{ item.Title
                                        }}</a>
                                </h6>
                                <p class="tx-12">
                                    <a :href="frontendURL + item.Slug" target="_blank">
                                        <i>
                                            {{ item.Slug }}</i>
                                    </a>
                                </p>
                                <span class="post-info mg-r-10 bd-r pd-r-10">
                                    <i class="fa fa-clock mg-r-5"></i>
                                    <span>
                                        {{ moment(item.CreatedTime, "DD/MM/YYYY HH:mm").locale('vi').fromNow() }}

                                    </span>
                                </span>
                                <span class="post-info mg-r-10 bd-r pd-r-10">
                                    <span v-if="item.Status === 10" class="tag bg-info" style="color:white">
                                        {{ item.StatusStr }}
                                    </span>
                                    <span v-if="item.Status === 15" class="tag bg-warning" style="color:white">
                                        {{ item.StatusStr }}
                                    </span>
                                    <span v-if="item.Status === 13" class="tag bg-danger" style="color:white">
                                        {{ item.StatusStr }}
                                    </span>
                                    <span v-if="item.Status === 20" class="tag bg-success" style="color:white">
                                        {{ item.StatusStr }}
                                    </span>
                                </span>

                                <span class="post-info">
                                    {{ item.CreatedBy }}
                                </span>


                            </div>
                            <div class="col col-md-auto">
                                <img v-if="item.Thumbnail.length > 0" :src="item.Thumbnail" alt="img" class="wd-150">
                                <img v-if="item.Thumbnail.length <= 0" src="@/assets/images/nopicture.svg" alt="img"
                                    class="wd-150">
                            </div>
                            <div class="col-md-auto mt-2 mb-2">
                                <button type="button" class="btn btn-block btn-outline-primary dropdown-toggle btn-sm"
                                    data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="fe fe-settings"></i>
                                    <span class="pd-l-5">Quản lý</span>
                                </button>
                                <ul class="dropdown-menu">
                                    <li>
                                        <router-link class="dropdown-item"
                                            :to="{ name: 'cms-post-update', params: { id: item.Id } }">
                                            <i class="fa fa-pen"></i> Sửa
                                        </router-link>
                                    </li>
                                    <li @click="publish(item.Id)" v-if="item.Status !== 20">
                                        <a class="dropdown-item" href="javascript:void(0);">
                                            <i class="fa fa-check"></i> Xuất bản
                                        </a>
                                    </li>

                                    <li>
                                        <a class="dropdown-item" href="javascript:void(0);">
                                            <i class="fa fa-eye"></i> Xem
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="javascript:void(0);">
                                            <i class="fa fa-copy"></i> Nhân bản
                                        </a>
                                    </li>

                                    <li>
                                        <a class="dropdown-item" href="javascript:void(0);">
                                            <i class="fa fa-link"></i> Copy link
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="javascript:void(0);">
                                            <i class="fa fa-share"></i> Chia sẻ
                                        </a>
                                    </li>
                                    <li>
                                        <a @click="deletePost(item.Id)" class="dropdown-item"
                                            href="javascript:void(0);">
                                            <i class="fa fa-trash"></i> Xóa
                                        </a>
                                    </li>

                                </ul>
                            </div>
                        </div>
                        <div class="p-2 pd-b-20">
                            <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><!-- COL END -->
        </div>

    </div>
</template>

<script setup>
//#region Imports
import moment from "moment";
const frontendURL = import.meta.env.VITE_FRONT_END_URL;
//#endregion

//#region Imports
import { ref, reactive, onMounted } from 'vue'
import postService from "@/services/postService";
import categoryService from "@/services/categoryService";
import { useRouter } from 'vue-router';
import vSelect from 'vue-select';
const router = useRouter();
//#endregion


//#region Components
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';

import { useToast } from "vue-toastification";
const toast = useToast();
//#endregion

//#region Actions
const selectedId = ref(0);
async function fnCreateOrUpdate(id) {
    console.log(id);
    selectedId.value = id;
    if (id > 0) {
        router.push({ name: 'cms-post-update', params: { id: selectedId.value } });
    } else {
        router.push({ name: 'cms-post-create' });
    }

}


//#endregion


//#region SEARCH


const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            CreatedStart: null,
            CreatedEnd: null,
            Status: null,
            CategoryId: 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 statuses = reactive([
    { Id: 10, Name: 'Biên tập' },
    { Id: 15, Name: 'Chờ xuất bản' },
    { Id: 20, Name: 'Xuất bản' },
    { Id: 30, Name: 'Hệ thống quản lý tài khoản' }
]);
const visibilities = reactive([
    { Id: 10, Name: 'Công khai' },
    { Id: 20, Name: 'Nội bộ' },
    { Id: 25, Name: 'Mật khẩu bảo vệ' },
    { Id: 13, Name: 'Ngừng hiển thị' }
]);

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 postService.search(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(post => {
            items.push(post);
        });
    }
    searchModel.Pagination.Total = searchResult.TotalRecord;
    loading.value = false;
}

async function publish(id) {
    var cf = confirm("Bạn chắc chắn muốn xuất bản?");
    if (cf) {
        loading.value = true;
        var result = await postService.publish(id);

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

async function deletePost(id) {
    var cf = confirm("Bạn chắc chắn muốn xóa?");
    if (cf) {
        loading.value = true;
        var lockResult = await postService.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;
        loadData();
    }
}



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

//#endregion


//#region Utilities
function getTagClass(statusId) {
    switch (statusId) {
        case 1:
            return 'tag-default'

        case 3:
            return 'tag-green';

        case 4:
            return 'tag-yellow';

        case 5:
            return 'tag-red';

        default:
            return 'tag-default';
    }
}
//#endregion

//#region Categories
const categories = reactive([]);

async function getCategories() {
    categories.splice(0, categories.length);
    // Lấy danh mục bài viết (contentType = 1 là bài viết)
    var result = await categoryService.getTree('', 1);
    if (result && Array.isArray(result)) {
        result.forEach(cat => categories.push(cat));
    }
}
//#endregion

onMounted(async () => {
    await getCategories();
    await search();
})

</script>
<style lang="css">
@import 'vue-select/dist/vue-select.css';

.post-info {
    font-size: .83rem;
    font-style: italic;
    color: #090b0ed9;
}
</style>