<template>
  <div class="calendar-container">
    <div class="calendar-header">
      <div class="header-controls">
        <el-date-picker
          v-model="selectedDate"
          type="month"
          placeholder="选择月份"
          format="yyyy年MM月"
          value-format="yyyy-MM"
          @change="handleDateChange"
        />
        <h2>{{ currentMonth }}月 {{ currentYear }}</h2>
      </div>
    </div>
    <div class="calendar-weekdays">
      <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
    </div>
    <div class="calendar-days">
      <div
        v-for="(day, index) in calendarDays"
        :key="index"
        :class="[
          'day',
          { 'empty': !day.date },
          { 'today': isToday(day.date) },
          { 'clocked': day.clockState === 1 },
          { 'not-clocked': day.clockState === 0 }
        ]"
      >
        <div v-if="day.date" class="day-content">
          <div class="day-number">{{ day.date.getDate() }}</div>
          <div class="clock-status">
            {{ day.clockState === 1 ? '✓' : day.clockState === 0 ? '✗' : '' }}
          </div>
        </div>
      </div>
    </div>
    <div class="calendar-summary">
      <div>已打卡: {{ clockSummary.clockDays }}天</div>
      <div>未打卡: {{ clockSummary.noRecordDays }}天</div>
    </div>
  </div>
</template>

<script>
import { listClockInfo } from "@/api/business/clock";
import dayjs from "dayjs";

export default {
  name: "ClockCalendar",
  props: {
    accountId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    const now = new Date();
    return {
      clockRecordList: [],
      weekdays: ['日', '一', '二', '三', '四', '五', '六'],
      selectedDate: dayjs(now).format("YYYY-MM"), // 默认当前年月
      clockSummary: {
        clockDays: 0,
        noRecordDays: 0
      },
      loading: false
    };
  },
  computed: {
    currentYear() {
      return dayjs(this.selectedDate).year();
    },
    currentMonth() {
      return dayjs(this.selectedDate).month() + 1;
    },
    calendarDays() {
      if (!Array.isArray(this.clockRecordList)) {
        return [];
      }

      const year = this.currentYear;
      const month = this.currentMonth - 1; // JavaScript月份是0-11
      const firstDay = new Date(year, month, 1);
      const lastDay = new Date(year, month + 1, 0);
      const firstDayOfWeek = firstDay.getDay();
      const prevMonthDays = firstDayOfWeek;
      const totalDays = lastDay.getDate();

      const days = [];

      // 添加空白格子
      for (let i = 0; i < prevMonthDays; i++) {
        days.push({});
      }

      // 添加当月日期
      for (let i = 1; i <= totalDays; i++) {
        const dateStr = `${year}-${(month + 1).toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`;
        const record = this.clockRecordList.find(item => item.date === dateStr);

        days.push({
          date: new Date(year, month, i),
          clockState: record ? record.clockState : null
        });
      }

      return days;
    }
  },
  watch: {
    accountId: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.getList();
        }
      }
    }
  },
  methods: {
    isToday(date) {
      if (!date) return false;
      const today = new Date();
      return date.getDate() === today.getDate() &&
        date.getMonth() === today.getMonth() &&
        date.getFullYear() === today.getFullYear();
    },

    handleDateChange() {
      this.getList();
    },

    /** 查询打卡列表 */
    getList() {
      if (!this.accountId) return;

      this.loading = true;
      const params = {
        accountId: this.accountId,
        date: this.selectedDate // 传入当月第一天
      };
      listClockInfo(params).then(response => {
        if (response.data) {
          this.clockRecordList = response.data.clockRecordList || [];
          this.clockSummary = {
            clockDays: response.data.clockDay || 0,
            noRecordDays: response.data.noRecordDay || 0
          };
        }
      }).catch(error => {
        console.error("获取打卡记录失败:", error);
        this.clockRecordList = [];
        this.clockSummary = { clockDays: 0, noRecordDays: 0 };
      }).finally(() => {
        this.loading = false;
      });
    }
  }
};
</script>

<style scoped>
.calendar-container {
  font-family: Arial, sans-serif;
  max-width: 600px;
  margin: 0 auto;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.calendar-header {
  background-color: #4a90e2;
  color: white;
  padding: 15px;
  text-align: center;
}

.header-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-bottom: 10px;
}

.header-controls h2 {
  margin: 0;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background-color: #f5f5f5;
  padding: 10px 0;
  text-align: center;
  font-weight: bold;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background-color: #eee;
}

.day {
  min-height: 80px;
  padding: 5px;
  background-color: white;
  position: relative;
}

.day.empty {
  background-color: #f9f9f9;
}

.day-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.day-number {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
}

.clock-status {
  font-size: 20px;
  margin-top: auto;
  text-align: center;
}

.today {
  background-color: #e6f7ff;
  border: 1px solid #4a90e2;
}

.clocked {
  background-color: #e8f5e9;
}

.clocked .clock-status {
  color: #4caf50;
}

.not-clocked {
  background-color: #ffebee;
}

.not-clocked .clock-status {
  color: #f44336;
}

.calendar-summary {
  display: flex;
  justify-content: space-around;
  padding: 10px;
  background-color: #f5f5f5;
  border-top: 1px solid #ddd;
}
</style>
