<template>
  <div>
    <!-- Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Báo cáo 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"><a href="javascript:void(0);">Nhân sự</a></li>
          <li class="breadcrumb-item active" aria-current="page">Báo cáo chấm công</li>
        </ol>
      </div>
    </div>

    <!-- Main Content -->
    <div class="row row-sm">
      <div class="col-12 grid-margin">
        <!-- Search Form -->
        <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>Tháng</label>
                <select v-model="searchParams.month" class="form-select">
                  <option v-for="m in months" :key="m" :value="m">Tháng {{ m }}</option>
                </select>
              </div>
              <div class="col-lg-3 col-md-4 mb-3">
                <label>Năm</label>
                <select v-model="searchParams.year" class="form-select">
                  <option v-for="y in years" :key="y" :value="y">{{ y }}</option>
                </select>
              </div>
              <div class="col-lg mb-3 d-flex align-items-end">
                <button type="submit" class="btn btn-dark me-2" :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>
                <button type="button" class="btn btn-outline-success" @click="exportExcel" :disabled="loading || items.length === 0">
                  <i class="fe fe-download me-2"></i>Xuất Excel
                </button>
              </div>
            </div>
          </form>
        </div>

        <!-- Data Table -->
        <div class="card card-table shadow-none">
          <div class="card-body card-table-body">
            <div class="table-responsive border-top mg-b-10">
              <table class="table table-vcenter mb-0" style="min-height:300px">
                <thead>
                  <tr>
                    <th class="wd-5p text-center">STT</th>
                    <th>Họ và tên</th>
                    <th class="text-center">Tên đăng nhập</th>
                    <th class="text-center">Số ngày làm</th>
                    <th class="text-center">Tổng giờ làm</th>
                    <th class="text-center">Tổng công</th>
                    <th class="text-center">Thao tác</th>
                  </tr>
                </thead>

                <!-- Loading State -->
                <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>

                <!-- Empty State -->
                <tbody v-if="!loading && items.length === 0">
                  <tr>
                    <td colspan="7" class="tx-semibold text-center text-danger">
                      Không tìm thấy dữ liệu!
                    </td>
                  </tr>
                </tbody>

                <!-- Data Rows -->
                <tbody v-if="!loading && items.length > 0">
                  <tr v-for="(item, index) in items" :key="item.UserId">
                    <td class="text-center">{{ index + 1 }}</td>
                    <td>
                      <div class="fw-bold">{{ item.FullName }}</div>
                      <small class="text-muted">Mã NV: {{ item.UserId }}</small>
                    </td>
                    <td class="text-center">{{ item.UserName }}</td>
                    <td class="text-center">
                      <span class="badge bg-primary">{{ item.TotalWorkDays }} ngày</span>
                    </td>
                    <td class="text-center">
                      <span class="badge bg-info">{{ item.TotalWorkingHours.toFixed(1) }} giờ</span>
                    </td>
                    <td class="text-center">
                      <span class="badge bg-success">{{ item.TotalWorkCredits.toFixed(2) }} công</span>
                    </td>
                    <td class="text-center">
                      <button 
                        type="button" 
                        class="btn btn-sm btn-outline-primary"
                        @click="viewDetail(item)"
                      >
                        <i class="fe fe-eye me-1"></i>Xem chi tiết
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- Summary -->
            <div v-if="!loading && items.length > 0" class="alert alert-info mt-3">
              <strong>Tổng kết:</strong> 
              <span class="ms-3">Số nhân viên: <strong>{{ items.length }}</strong></span>
              <span class="ms-3">Tổng công: <strong>{{ totalWorkCredits.toFixed(2) }}</strong></span>
              <span class="ms-3">Tổng giờ: <strong>{{ totalWorkingHours.toFixed(1) }}</strong></span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import attendanceService from '@/services/hr/attendanceService';
import { useToast } from 'vue-toastification';

const router = useRouter();
const toast = useToast();
const loading = ref(false);
const items = reactive([]);

// Generate months array (1-12)
const months = Array.from({ length: 12 }, (_, i) => i + 1);

// Generate years array (current year and 2 years before/after)
const currentYear = new Date().getFullYear();
const years = Array.from({ length: 5 }, (_, i) => currentYear - 2 + i);

// Search parameters
const searchParams = reactive({
  month: new Date().getMonth() + 1,
  year: currentYear
});

// Computed totals
const totalWorkCredits = computed(() => {
  return items.reduce((sum, item) => sum + item.TotalWorkCredits, 0);
});

const totalWorkingHours = computed(() => {
  return items.reduce((sum, item) => sum + item.TotalWorkingHours, 0);
});

// Search function
async function search() {
  loading.value = true;
  items.splice(0, items.length);
  
  try {
    const result = await attendanceService.getMonthlySummary(
      searchParams.month,
      searchParams.year
    );
    
    if (result && Array.isArray(result)) {
      result.forEach(item => items.push(item));
      
      if (result.length === 0) {
        toast.info('Không có dữ liệu chấm công cho tháng này');
      }
    }
  } catch (error) {
    console.error('Error fetching monthly summary:', error);
    
    // Handle specific error messages from API
    if (error.response && error.response.data) {
      toast.error(error.response.data);
    } else {
      toast.error('Lỗi khi tải dữ liệu báo cáo chấm công!');
    }
  } finally {
    loading.value = false;
  }
}

// View detail function
function viewDetail(item) {
  router.push({
    name: 'hr-attendance-detail',
    params: {
      userId: item.UserId
    },
    query: {
      month: searchParams.month,
      year: searchParams.year,
      fullName: item.FullName
    }
  });
}

// Export Excel function
function exportExcel() {
  if (items.length === 0) {
    toast.warning('Không có dữ liệu để xuất!');
    return;
  }

  // Create CSV content
  const headers = ['STT', 'Họ và tên', 'Tên đăng nhập', 'Số ngày làm', 'Tổng giờ làm', 'Tổng công'];
  const rows = items.map((item, index) => [
    index + 1,
    item.FullName,
    item.UserName,
    item.TotalWorkDays,
    item.TotalWorkingHours.toFixed(1),
    item.TotalWorkCredits.toFixed(2)
  ]);

  let csvContent = headers.join(',') + '\n';
  rows.forEach(row => {
    csvContent += row.map(cell => `"${cell}"`).join(',') + '\n';
  });

  // Add BOM for Excel UTF-8 support
  const BOM = '\uFEFF';
  const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  
  link.setAttribute('href', url);
  link.setAttribute('download', `BaoCaoCong_${searchParams.month}_${searchParams.year}.csv`);
  link.style.visibility = 'hidden';
  
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  
  toast.success('Đã xuất file Excel thành công!');
}

// Load data on mount
onMounted(async () => {
  await search();
});
</script>

<style scoped>
.badge {
  font-size: 0.875rem;
  padding: 0.35rem 0.65rem;
}
</style>

