<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý ứng viên</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);">Nhân sự</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Quản lý ứng viê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 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="datePickerStore.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>
                        <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="d-flex flex-row justify-content-end mg-b-20 mg-r-20">
                        <button @click="fnCreateOrUpdate(0)" type="button" class="btn btn-primary">
                            <i class="fe fe-plus me-2"></i>
                            Tạo ứng viên
                        </button>

                    </div>


                    <div class="table-responsive">
                        <table class="table table-hover mg-b-0 text-md-nowrap">
                            <thead>
                                <tr>
                                    <th class="wd-20p">
                                        Ứng viên
                                    </th>

                                    <th class="wd-20p">
                                        Giới thiệu
                                    </th>
                                    <th class="wd-10p">
                                        Trạng thái
                                    </th>
                                    <th class="wd-30p">
                                        Review
                                    </th>
                                    <th class="wd-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>
                                <tr v-for="item in items">
                                    <td @click="openDetail(item.Id)" style="cursor:pointer;">
                                        Họ và tên: <b>{{ item.FullName }}</b><br />
                                        SĐT: <b>{{ item.PhoneNumber }}</b><br />
                                        Năm sinh: <b>{{ item.YearOfBirth }}</b><br />
                                        Địa chỉ: <b>{{ item.Address }}</b><br />
                                        Ngày ứng tuyển: <b>{{ item.CreatedTime }}</b><br />
                                        <template v-if="item.HasCv">
                                            <div class="mt-2">
                                                <i class="fa fa-paperclip"></i>
                                                <a href="javascript:void(0);" @click.stop="openCvModal(item)"
                                                    :title="item.CvFileName">
                                                    {{ item.CvFileName }}
                                                </a>
                                                <span v-if="item.CvFileSize"> ({{ (item.CvFileSize / 1024).toFixed(1) }}
                                                    KB)</span>
                                                <span v-if="item.CvFileType"> [{{ item.CvFileType }}]</span>
                                            </div>
                                        </template>
                                    </td>

                                    <td>
                                        {{ item.Introduction }}
                                    </td>
                                    <td>
                                        <a class="btnstatus" href="javascript:void(0);" @click="review(item.Id)">
                                            <span class="tag" :class="getTagClass(item.Status)">{{ item.StatusStr
                                                }}</span>
                                        </a>


                                    </td>
                                    <td>
                                        <p style="white-space: pre-line;">{{ item.StatusContent }}</p>
                                    </td>
                                    <td>
                                        <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 @click="review(item.Id)">
                                                <a class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fa fa-star"></i> Cập nhật trạng thái
                                                </a>
                                            </li>
                                        </ul>
                                    </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><!-- COL END -->
        </div>
        <LadaDialog :visible="modalControl.Review">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Cập nhật trạng thái ứng viên</h5>
                    <button @click="closeModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <Review @cancel="closeModal" :id="selectedId"></Review>
            </template>

        </LadaDialog>
        <LadaDialog :visible="modalControl.Create">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Tạo ứng viên mới</h5>
                    <button @click="closeCreateModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <Create @cancel="closeCreateModal" @success="() => { closeCreateModal(); loadData(); }" />
            </template>
        </LadaDialog>
        <LadaDialog :visible="cvModal.visible" variant="modal-full">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Xem CV: {{ cvModal.name }}</h5>
                    <button @click="closeCvModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <div v-if="cvModal.url && cvModal.type === '.pdf'">
                    <VuePdfEmbed :source="cvModal.url" />
                </div>
                <div
                    v-else-if="cvModal.url && ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'].includes(cvModal.type)">
                    <img :src="encodeURI(cvModal.url)" :alt="cvModal.name"
                        style="max-width:100%;max-height:80vh;display:block;margin:auto;" />
                </div>
                <div v-else>
                    <p>Không hỗ trợ xem trực tiếp định dạng này. Vui lòng tải về để xem.</p>
                    <a :href="cvModal.url ? encodeURI(cvModal.url) : '#'" target="_blank" class="btn btn-primary">Tải
                        về</a>
                </div>
            </template>
        </LadaDialog>
    </div>
</template>

<script setup>
//#region Imports
//#endregion

//#region Imports
import moment from "moment";
import { ref, reactive, onMounted, watch } from 'vue';
import candidateService from "@/services/candidateService";
import { useRouter } from 'vue-router';
const router = useRouter();
//#endregion

import { useDatePickerStore } from "@/stores";
const datePickerStore = useDatePickerStore();


//#region Components
import DatepickerInstance from "@vuepic/vue-datepicker";
import { DateRangeSidebar } from '@/components/index';
import { useToast } from "vue-toastification";
const toast = useToast();


import Review from './components/review.vue';
import Create from './components/create.vue';
// Thêm import cho PDF Viewer
import { VuePDF, usePDF } from '@tato30/vue-pdf';
import '@tato30/vue-pdf/style.css';
import VuePdfEmbed from 'vue-pdf-embed';
//#endregion

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

}


//#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,

        }
    }
});
const items = reactive([]);
const loading = ref(false);

//#region Modals
const modalControl = reactive({
    Review: false,
    Create: false
});
function closeModal() {
    modalControl.Review = false;
    loadData();
}
function closeCreateModal() {
    modalControl.Create = false;
}
function openCreateModal() {
    modalControl.Create = true;
}
//#endregion


const date = ref();
const createDatePicker = ref(DatepickerInstance);


const statuses = reactive([
    { Id: 1, Name: 'Mới' },
    { Id: 2, Name: 'Liên hệ lại' },
    { Id: 3, Name: 'Phù hợp' },
    { Id: 4, Name: 'Hẹn phỏng vấn' },
    { Id: 5, Name: 'Gửi đề nghị' },
    { Id: 6, Name: 'Nhận việc' },
    { Id: 7, Name: 'Từ chối' }
]);




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

async function review(id) {
    selectedId.value = id;
    modalControl.Review = true;
}

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-info'

        case 2:
            return 'tag-warning';

        case 3:
            return 'tag-success';

        case 4:
            return 'tag-blue';
        case 5:
            return 'tag-lime';
        case 6:
            return 'tag-green';
        case 7:
            return 'tag-red';
        default:
            return 'tag-default';
    }
}
//#endregion

const cvModal = ref({ visible: false, url: '', name: '', type: '' });
function openCvModal(item) {
    let url = item.CvFileUrl;
    if (url && !url.startsWith('http')) {
        url = url.replace(/^\/+/, '');
    }
    cvModal.value = {
        visible: true,
        url,
        name: item.CvFileName,
        type: (item.CvFileType || '').toLowerCase()
    };
}
function closeCvModal() {
    cvModal.value.visible = false;
}

const pdf = ref(null);
watch(
    () => cvModal.value,
    (val) => {
        if (val.visible && val.url && val.type === '.pdf') {
            const { pdf: pdfObj } = usePDF(val.url);
            pdf.value = pdfObj;
        } else {
            pdf.value = null;
        }
    },
    { immediate: true, deep: true }
);

function openDetail(id) {
    const url = router.resolve({ name: 'hr-candidate-detail', params: { id } }).href;
    window.open(url, '_blank');
}

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

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

a>span.tag {
    cursor: pointer;
}
</style>