<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý chấm công</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">Chấm công</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-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>Nhân viên</label>
                                <v-select v-model="selectedStaff" label="UserName" :filterable="false" :options="staffs"
                                    @search="getStaffs" placeholder="Tìm kiếm nhân viên">
                                    <template #no-options="{ search, searching, loading }">
                                        Gõ từ khóa để tìm....
                                    </template>
                                    <template v-slot:option="option">
                                        {{ option.UserName }} ({{ option.FullName }})
                                    </template>
                                </v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Ngày chấm vào</label>
                                <VueDatePicker ref="checkInDatePicker" v-model="checkInDate" :enable-time-picker="false" range
                                    multi-calendars auto-apply :format="format" @update:model-value="handleCheckInDate">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeCheckInDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Ngày chấm ra</label>
                                <VueDatePicker ref="checkOutDatePicker" v-model="checkOutDate" :enable-time-picker="false" range
                                    multi-calendars auto-apply :format="format" @update:model-value="handleCheckOutDate">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeCheckOutDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </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-end mb-2">
                            <button class="btn btn-outline-success mx-2 button-icon mb-1" @click="exportExcel">
                                <i class="fe fe-download me-2"></i>Xuất Excel
                            </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>Nhân viên</th>
                                        <th>Giờ vào / Ảnh check in<br><small>ODO vào</small></th>
                                        <th>Giờ ra / Ảnh check out<br><small>ODO ra</small></th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="3" 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="3" 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>
                                            <div><b>{{ item.UserFullName }}</b></div>
                                            <div v-if="item.UserName"><small>Tài khoản: {{ item.UserName }}</small>
                                            </div>
                                            <div><small>Mã NV: {{ item.UserId }}</small></div>
                                        </td>
                                        <td>
                                            <div>{{ item.CheckInTime }}</div>
                                            <div v-if="item.CheckInOdo != null">
                                                <small class="text-muted">ODO: {{ item.CheckInOdo }}</small>
                                            </div>
                                            <viewer v-if="item.CheckInMedias && item.CheckInMedias.length > 0">
                                                <img v-for="img in item.CheckInMedias" :key="img.Id" :src="img.Url"
                                                    :alt="img.AltText || 'Ảnh check in'"
                                                    style="max-width:60px;max-height:60px;object-fit:cover;border-radius:4px;cursor:pointer;margin-right:4px;margin-top:4px;" />
                                            </viewer>
                                        </td>
                                        <td>
                                            <div>{{ item.CheckOutTime }}</div>
                                            <div v-if="item.CheckOutOdo != null">
                                                <small class="text-muted">ODO: {{ item.CheckOutOdo }}</small>
                                            </div>
                                            <viewer v-if="item.CheckOutMedias && item.CheckOutMedias.length > 0">
                                                <img v-for="img in item.CheckOutMedias" :key="img.Id" :src="img.Url"
                                                    :alt="img.AltText || 'Ảnh check out'"
                                                    style="max-width:60px;max-height:60px;object-fit:cover;border-radius:4px;cursor:pointer;margin-right:4px;margin-top:4px;" />
                                            </viewer>
                                        </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>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import attendanceService from '@/services/hr/attendanceService';
import userService from '@/services/userService';
import DatepickerInstance from '@vuepic/vue-datepicker';
import { useToast } from 'vue-toastification';
import pager from '@/components/pagination/pager.vue';
import { DateRangeSidebar } from '@/components/index';
import _ from 'lodash';

const toast = useToast();
const loading = ref(false);
const items = reactive([]);
const checkInDate = ref();
const checkOutDate = ref();
const ctrlPager = ref();
const checkInDatePicker = ref(DatepickerInstance);
const checkOutDatePicker = ref(DatepickerInstance);
const staffs = ref([]);
const selectedStaff = ref(null);

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

const format = (dates) => {
    if (!dates || dates.length < 2) return '';
    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 onChangeCheckInDate(newDates) {
    console.log(newDates);
    checkInDate.value = newDates;
    checkInDatePicker.value.closeMenu();
    handleCheckInDate(newDates);
}

function handleCheckInDate(modelData) {
    if (modelData != null) {
        searchModel.Search.PredicateObject.CheckInStart = modelData[0];
        searchModel.Search.PredicateObject.CheckInEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.CheckInStart = null;
        searchModel.Search.PredicateObject.CheckInEnd = null;
    }
}

async function onChangeCheckOutDate(newDates) {
    console.log(newDates);
    checkOutDate.value = newDates;
    checkOutDatePicker.value.closeMenu();
    handleCheckOutDate(newDates);
}

function handleCheckOutDate(modelData) {
    if (modelData != null) {
        searchModel.Search.PredicateObject.CheckOutStart = modelData[0];
        searchModel.Search.PredicateObject.CheckOutEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.CheckOutStart = null;
        searchModel.Search.PredicateObject.CheckOutEnd = null;
    }
}

const getStaffs = _.debounce(async (keyword, loading) => {
    staffs.value = [];
    if (!keyword) {
        loading && loading(false);
        return;
    }
    try {
        const res = await userService.sugStaff(keyword);
        if (res && Array.isArray(res)) {
            staffs.value = res;
        }
    } catch (e) {
        staffs.value = [];
    }
    loading && loading(false);
}, 300);

async function search() {
    // Gán lại UserId từ selectedStaff
    if (selectedStaff.value) {
        searchModel.Search.PredicateObject.UserId = selectedStaff.value.Id;
    } else {
        searchModel.Search.PredicateObject.UserId = null;
    }
    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);
    try {
        const result = await attendanceService.search(searchModel);
        if (result && result.Items && result.Items.length > 0) {
            result.Items.forEach(item => items.push(item));
        }
        searchModel.Pagination.Total = result.TotalRecord || 0;
    } catch (e) {
        toast.error('Lỗi khi tải dữ liệu chấm công!');
    }
    loading.value = false;
}

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

function exportExcel() {
    toast.info('Tính năng xuất Excel sẽ được phát triển!');
}

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