<template>
  <div>
    <div class="page-header">
      <h1>填报详情</h1>
      <p>查看您的每日工时填报日历和明细记录</p>
    </div>

    <div class="details-layout" v-loading="loading">
      <!-- Left Column: Calendar & Legends -->
      <div class="calendar-section">
        <div class="content-card">
          <div class="card-title">
            <span>📅 工时填报日历</span>
            <div class="calendar-legends">
              <span class="legend-item"><span class="dot green"></span>已满8h</span>
              <span class="legend-item"><span class="dot yellow"></span>未满8h</span>
              <span class="legend-item"><span class="dot red"></span>漏填报</span>
              <span class="legend-item"><span class="dot gray"></span>未到期/周末</span>
            </div>
          </div>

          <el-calendar v-model="calendarDate">
            <template #date-cell="{ data }">
              <div class="day-cell-content" @click="handleSelectDate(data.day)">
                <div class="day-header">
                  <span class="day-num">{{ data.day.split('-')[2] }}</span>
                  <span v-if="isWeekend(data.day)" class="weekend-tag">休</span>
                </div>
                <div class="day-body">
                  <div v-if="getDayHours(data.day) >= 8" class="status-badge filled">
                    {{ getDayHours(data.day) }}h
                  </div>
                  <div v-else-if="getDayHours(data.day) > 0" class="status-badge partial">
                    {{ getDayHours(data.day) }}h
                  </div>
                  <div v-else-if="isPastUnfilled(data.day)" class="status-badge unfilled">
                    未填报
                  </div>
                </div>
              </div>
            </template>
          </el-calendar>
        </div>
      </div>

      <!-- Right Column: Stats & Records details -->
      <div class="info-section">
        <!-- Month Stats -->
        <div class="content-card stats-mini-card">
          <div class="card-title">📊 本月度汇总 ({{ currentMonthStr }})</div>
          <div class="mini-stats-grid">
            <div class="mini-stat-item green-glow">
              <div class="label">满额填报</div>
              <div class="value green-text">{{ monthStats.fullDays }}<span class="unit">天</span></div>
            </div>
            <div class="mini-stat-item yellow-glow">
              <div class="label">部分填报</div>
              <div class="value yellow-text">{{ monthStats.partialDays }}<span class="unit">天</span></div>
            </div>
            <div class="mini-stat-item red-glow">
              <div class="label">漏填工作日</div>
              <div class="value red-text">{{ monthStats.unfilledDays }}<span class="unit">天</span></div>
            </div>
            <div class="mini-stat-item purple-glow">
              <div class="label">累计总工时</div>
              <div class="value purple-text">{{ monthStats.totalHours }}<span class="unit">小时</span></div>
            </div>
          </div>
        </div>

        <!-- Selected Date Detailed Table -->
        <div class="content-card records-card">
          <div class="card-title">
            <span>📋 {{ selectedDate }} 工时明细</span>
            <el-button v-if="selectedDate" type="primary" size="default" @click="goToFill">
              ✍️ 去填报/修改
            </el-button>
          </div>
          
          <el-table :data="selectedDateRecords" stripe style="width: 100%" size="default">
            <el-table-column prop="client_name" label="客户/项目" min-width="120" />
            <el-table-column prop="service_type" label="售前/售后" width="90">
              <template #default="{ row }">
                <el-tag :type="row.service_type === '售后' ? 'warning' : 'success'" size="small">
                  {{ row.service_type || '售前' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="project_type" label="子项目" width="100" />
            <el-table-column prop="hours" label="工时(h)" width="80" />
            <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
          </el-table>
          
          <div v-if="!selectedDateRecords.length" class="empty-placeholder">
            <el-empty description="该日期暂无工时记录" :image-size="60" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { rdApi } from '../../api'

const router = useRouter()
const calendarDate = ref(new Date())
const selectedDate = ref(new Date().toLocaleDateString('sv-SE', { timeZone: 'Asia/Shanghai' }))
const todayStr = ref(new Date().toLocaleDateString('sv-SE', { timeZone: 'Asia/Shanghai' }))

const recordsMap = ref({}) // date -> { hours, list }
const loading = ref(false)

const currentMonthStr = computed(() => {
  const year = calendarDate.value.getFullYear()
  const month = String(calendarDate.value.getMonth() + 1).padStart(2, '0')
  return `${year}-${month}`
})

const selectedDateRecords = computed(() => {
  return recordsMap.value[selectedDate.value]?.list || []
})

// Timezone safe day of week checker
const getDayOfWeek = (dayStr) => {
  const d = new Date(dayStr + 'T00:00:00')
  return d.getDay()
}

const isWeekend = (dayStr) => {
  const day = getDayOfWeek(dayStr)
  return day === 0 || day === 6
}

const getDayHours = (dayStr) => {
  return recordsMap.value[dayStr]?.hours || 0
}

const isPastUnfilled = (dayStr) => {
  if (dayStr >= todayStr.value) return false
  if (isWeekend(dayStr)) return false
  return getDayHours(dayStr) === 0
}

async function loadMonthRecords(yyyyMm) {
  loading.value = true
  try {
    const res = await rdApi.getTimesheets({ month: yyyyMm })
    const records = res.data.records || []
    
    // Group records by date
    const map = {}
    records.forEach(r => {
      if (!map[r.work_date]) {
        map[r.work_date] = { hours: 0, list: [] }
      }
      map[r.work_date].hours += r.hours
      map[r.work_date].list.push(r)
    })
    recordsMap.value = map
  } catch (e) {
    ElMessage.error('获取月度工时失败')
  } finally {
    loading.value = false
  }
}

// Watch calendar date changes to load month data
watch(calendarDate, (newDate) => {
  if (newDate) {
    const year = newDate.getFullYear()
    const month = String(newDate.getMonth() + 1).padStart(2, '0')
    const yyyyMm = `${year}-${month}`
    loadMonthRecords(yyyyMm)
  }
}, { immediate: true })

function handleSelectDate(dayStr) {
  selectedDate.value = dayStr
}

function goToFill() {
  router.push({
    path: '/timesheet',
    query: { date: selectedDate.value }
  })
}

// Compute statistics for the calendar's active month
const monthStats = computed(() => {
  const date = calendarDate.value
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const daysInMonth = new Date(year, month, 0).getDate()
  
  let fullDays = 0
  let partialDays = 0
  let unfilledDays = 0
  let totalHours = 0
  
  for (let day = 1; day <= daysInMonth; day++) {
    const dStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
    const hours = getDayHours(dStr)
    totalHours += hours
    
    if (hours >= 8) {
      fullDays++
    } else if (hours > 0) {
      partialDays++
    } else {
      // Unfilled. Check if it's a weekday in the past
      if (dStr < todayStr.value && !isWeekend(dStr)) {
        unfilledDays++
      }
    }
  }
  
  return {
    fullDays,
    partialDays,
    unfilledDays,
    totalHours: Math.round(totalHours * 10) / 10
  }
})
</script>

<style scoped>
.details-layout {
  display: flex;
  gap: 24px;
  align-items: flex-start;
  flex-wrap: wrap;
}

.calendar-section {
  flex: 1.5;
  min-width: 450px;
}

.info-section {
  flex: 1;
  min-width: 320px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* Calendar Legends */
.calendar-legends {
  display: flex;
  gap: 12px;
  font-size: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: var(--text-secondary);
}

.legend-item .dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.legend-item .dot.green {
  background: var(--success);
}
.legend-item .dot.yellow {
  background: var(--warning);
}
.legend-item .dot.red {
  background: var(--danger);
}
.legend-item .dot.gray {
  background: var(--text-muted);
}

/* Custom Calendar Styling */
:deep(.el-calendar) {
  --el-calendar-border-color: var(--border-color);
  background-color: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: var(--radius);
}

:deep(.el-calendar__header) {
  border-bottom: 1px solid var(--border-color);
  padding: 16px 20px;
}

:deep(.el-calendar__title) {
  color: var(--text-primary);
  font-weight: 600;
}

:deep(.el-calendar-table) {
  background-color: transparent;
}

:deep(.el-calendar-table thead th) {
  color: var(--text-secondary);
  border-bottom: 1px solid var(--border-color);
  padding: 12px 0;
}

:deep(.el-calendar-table td) {
  border-bottom: 1px solid var(--border-color);
  border-right: 1px solid var(--border-color);
  background-color: transparent !important;
}

:deep(.el-calendar-table tr:first-child td) {
  border-top: none;
}

:deep(.el-calendar-table tr td:first-child) {
  border-left: none;
}

:deep(.el-calendar-table tr td:last-child) {
  border-right: none;
}

:deep(.el-calendar-table .el-calendar-day) {
  height: 75px;
  padding: 6px;
  transition: var(--transition);
}

:deep(.el-calendar-table .el-calendar-day:hover) {
  background-color: var(--bg-hover) !important;
}

:deep(.el-calendar-table td.is-selected) {
  background-color: rgba(99, 102, 241, 0.12) !important;
}

:deep(.el-calendar-table td.is-today) {
  border: 2px solid var(--primary) !important;
}

/* Day cell content layout */
.day-cell-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  justify-content: space-between;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.day-num {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
}

.weekend-tag {
  font-size: 10px;
  color: var(--text-muted);
  background: rgba(255, 255, 255, 0.05);
  padding: 1px 4px;
  border-radius: 3px;
}

.day-body {
  margin-top: 4px;
  display: flex;
  justify-content: center;
}

/* Badges styling */
.status-badge {
  font-size: 11px;
  padding: 1px 5px;
  border-radius: 4px;
  font-weight: 500;
  text-align: center;
  width: 90%;
  letter-spacing: 0.2px;
}

.status-badge.filled {
  background: rgba(16, 185, 129, 0.15);
  color: #34d399;
  border: 1px solid rgba(16, 185, 129, 0.3);
}

.status-badge.partial {
  background: rgba(245, 158, 11, 0.15);
  color: #fbbf24;
  border: 1px solid rgba(245, 158, 11, 0.3);
}

.status-badge.unfilled {
  background: rgba(239, 68, 68, 0.15);
  color: #f87171;
  border: 1px solid rgba(239, 68, 68, 0.3);
}

/* Right Stats Cards */
.mini-stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.mini-stat-item {
  background: rgba(30, 41, 59, 0.4);
  border: 1px solid var(--border-color);
  padding: 16px;
  border-radius: var(--radius-sm);
  display: flex;
  flex-direction: column;
  gap: 6px;
  transition: var(--transition);
}

.mini-stat-item:hover {
  transform: translateY(-1px);
}

.green-glow:hover {
  border-color: rgba(16, 185, 129, 0.4);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.1);
}

.yellow-glow:hover {
  border-color: rgba(245, 158, 11, 0.4);
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.1);
}

.red-glow:hover {
  border-color: rgba(239, 68, 68, 0.4);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.1);
}

.purple-glow:hover {
  border-color: rgba(99, 102, 241, 0.4);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.1);
}

.mini-stat-item .label {
  font-size: 12px;
  color: var(--text-muted);
  font-weight: 500;
}

.mini-stat-item .value {
  font-size: 22px;
  font-weight: 700;
}

.mini-stat-item .unit {
  font-size: 12px;
  color: var(--text-secondary);
  font-weight: 400;
  margin-left: 2px;
}

.green-text { color: #10b981; }
.yellow-text { color: #f59e0b; }
.red-text { color: #ef4444; }
.purple-text { color: #818cf8; }

.records-card {
  flex: 1;
}

.empty-placeholder {
  padding: 30px 0;
}
</style>
