<template>
  <div class="attendance-calendar">
    <el-card>
      <template #header>
        <div class="calendar-header">
          <div class="search-form">
            <el-form :inline="true">
              <el-form-item label="开始日期">
                <el-date-picker
                  v-model="startDate"
                  type="datetime"
                  placeholder="开始日期"
                  :size="'default'"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="结束日期">
                <el-date-picker
                  v-model="endDate"
                  type="datetime"
                  placeholder="结束日期"
                  :size="'default'"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="setCurrentMonth">本月</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>

      <div class="calendar-container">
        <el-table :data="calendarData" border style="width: 100%">
          <!-- 表头-日期列 -->
          <el-table-column fixed prop="name" label="人员" width="120" />
          
          <!-- 动态生成日期列 -->
          <el-table-column
            v-for="day in daysInMonth"
            :key="day"
            :label="formatDay(day)"
            :width="120"
          >
            <template #default="scope">
              <div class="attendance-cell">
                <template v-if="scope.row.records[day]">
                  <div
                    v-for="(record, index) in scope.row.records[day]"
                    :key="index"
                    :class="['attendance-item', record.recordType]"
                  >
                    {{ formatTimeRange(record.startTime, record.endTime) }}
                    <el-tooltip 
                      :content="getTooltipContent(record)"
                      placement="top"
                    >
                      <span class="attendance-type">
                        {{ getTypeLabel(record.recordType) }}
                      </span>
                    </el-tooltip>
                  </div>
                </template>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { listAttendanceRecord } from '@/api/oa/attendanceRecord'

// 查询日期范围
const startDate = ref('')
const endDate = ref('')

// 考勤类型映射
const typeLabels = {
  attendance: '出勤',
  overtime: '加班',
  travel: '出差'
}

// 考勤记录数据
const attendanceRecords = ref([])

// 获取考勤记录
const getAttendanceRecords = async () => {
  if (!startDate.value || !endDate.value) {
    ElMessage.warning('请选择起止日期')
    return
  }

  try {
    const response = await listAttendanceRecord({
      startTime: startDate.value + ' 00:00:00',
      endTime: endDate.value + ' 23:59:59'
    })
    attendanceRecords.value = response.rows
  } catch (error) {
    console.error('获取考勤记录失败:', error)
    ElMessage.error('获取考勤记录失败')
  }
}

// 转换数据格式
const calendarData = computed(() => {
  // 按人员分组
  const groupedData = {}
  
  attendanceRecords.value.forEach(record => {
    if (!groupedData[record.nickName]) {
      groupedData[record.nickName] = {
        name: record.nickName,
        records: {}
      }
    }
    
    // 获取日期
    const date = new Date(record.recordDate)
    const day = date.getDate()
    
    if (!groupedData[record.nickName].records[day]) {
      groupedData[record.nickName].records[day] = []
    }
    
    // 格式化时间
    const formatTime = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    groupedData[record.nickName].records[day].push({
      recordType: record.recordType,
      startTime: formatTime(record.startTime),
      endTime: formatTime(record.endTime),
      status: record.status,
      durationHour: record.durationHour,
      remark: record.remark
    })
  })
  
  return Object.values(groupedData)
})

// 设置本月日期范围
const setCurrentMonth = () => {
  const now = new Date()
  const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
  const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)
  
  startDate.value = firstDay.toISOString().split('T')[0]
  endDate.value = lastDay.toISOString().split('T')[0]
  handleSearch()
}

// 查询处理
const handleSearch = () => {
  if (!startDate.value || !endDate.value) {
    ElMessage.warning('请选择起止日期')
    return
  }
  getAttendanceRecords()
}

// 初始加载数据
onMounted(() => {
  setCurrentMonth()
})

// 计算日期范围内的天数
const daysInMonth = computed(() => {
  if (!startDate.value || !endDate.value) return []
  
  const start = new Date(startDate.value)
  const end = new Date(endDate.value)
  const days = []
  
  for (let date = new Date(start); date <= end; date.setDate(date.getDate() + 1)) {
    days.push(date.getDate())
  }
  
  return days
})

// 格式化日期显示
const formatDay = (day) => {
  const date = new Date(startDate.value)
  date.setDate(day)
  const weekDay = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()]
  return `${day}日(${weekDay})`
}

// 格式化时间范围
const formatTimeRange = (start, end) => {
  return `${start}-${end}`
}

// 获取考勤类型标签
const getTypeLabel = (type) => {
  return typeLabels[type] || type
}

// 获取提示内容
const getTooltipContent = (record) => {
  const status = {
    'pending': '待审批',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return [
    `类型：${getTypeLabel(record.recordType)}`,
    `时间：${formatTimeRange(record.startTime, record.endTime)}`,
    `时长：${record.durationHour}小时`,
    `状态：${status[record.status] || record.status}`,
    record.remark ? `备注：${record.remark}` : ''
  ].filter(Boolean).join('\n')
}
</script>

<style scoped>
.attendance-calendar {
  padding: 20px;
}

.calendar-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.month-title {
  font-size: 18px;
  font-weight: bold;
}

.calendar-container {
  margin-top: 20px;
}

.attendance-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.attendance-item {
  font-size: 12px;
  padding: 2px 4px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.attendance-type {
  font-weight: bold;
}

/* 考勤类型样式 */
.attendance {
  background-color: #e1f3d8;
  color: #67c23a;
}

.overtime {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.travel {
  background-color: #ecf5ff;
  color: #409eff;
}
</style>
