<template>
  <view class="stats-container">
    <!-- 用户信息 -->
    <view class="user-header">
      <view class="user-avatar">
        <image v-if="currentUser.avatar" :src="currentUser.avatar" class="cu-avatar xl round"></image>
      </view>
      <view class="user-info">
        <text class="user-name">{{ currentUser.name }}</text>
      </view>
    </view>

    <!-- 日历选择器 -->
    <uni-calendar class="uni-calendar--hook card-radius" :selected="markedDates" :showMonth="true"
      @change="handleDateChange" @monthSwitch="handleMonthSwitch" />

    <!-- 打卡记录展示 -->
    <TimelineRecord class="card-radius" :records="filteredRecords" v-if="filteredRecords.length > 0" />
    <view v-else class="no-data">
      <text>暂无打卡记录</text>
    </view>
  </view>
</template>

<script>
import TimelineRecord from '@/components/timeline-record/TimelineRecord.vue';
import { getAttendanceList } from "@/api/attendance/attendance"

export default {
  components: {
    TimelineRecord
  },
  computed: {
    currentUser() {
      return this.$store.state.user || {
        name: '未知用户',
        department: '未知部门',
        position: '未知职位'
      };
    }
  },
  data() {
    return {
      currentDate: new Date(),
      markedDates: [],
      allRecords: [],
      filteredRecords: []
    };
  },
  mounted() {
    this.loadAttendanceData();
  },
  methods: {
    async loadAttendanceData() {
      try {
        const { startDate, endDate } = this.getMonthRange();
        const res = await getAttendanceList({
          userId: this.$store.state.user.id,
          type: 2,
          startDate,
          endDate
        });

        if (res.code === 200) {
          this.allRecords = res.data;
          this.updateMarkedDates();
          this.filterRecordsByDate(this.currentDate);
        }
      } catch (error) {
        console.error('加载考勤数据失败:', error);
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    },

    
updateMarkedDates() {
  const today = new Date().toISOString().split('T')[0];
  this.markedDates = this.allRecords
    .filter(record => record.attendanceDate)
    .map(record => {
		console.log(record,'12312313213')
      const isToday = record.attendanceDate.split('T')[0] === today;
      const hasCheckIn = !!record.checkInTime;
      const hasCheckOut = !!record.checkOutTime;
      
      let status;
      let custom = '';
      if (isToday) {
        status = ''; // 当天记录始终显示正常
      } else if (hasCheckIn && hasCheckOut) {
        status = '正常'; // 完整打卡记录
		custom = 'blue'
      } else if (hasCheckIn) {
        status = '异常'; // 只有上班打卡
      } else {
        return null; // 无效记录过滤
      }

      return {
        date: record.attendanceDate.split('T')[0],
        info: status,
		color:custom
      };
    })
    .filter(Boolean); // 移除null值
},


    filterRecordsByDate(date) {
      const dateStr = this.formatDate(date);
      
      this.filteredRecords = this.allRecords.filter(
        record => record.attendanceDate.includes(dateStr)
      );
    },

    getMonthRange() {
      const year = this.currentDate.getFullYear();
      const month = this.currentDate.getMonth();
      return {
        startDate: this.formatDate(new Date(year, month, 1)),
        endDate: this.formatDate(new Date(year, month + 1, 0))
      };
    },

    formatDate(date) {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      return `${y}-${m}-${d}`;
    },

    handleDateChange(detail) {
      if (!detail || !detail.fulldate) {
        console.error('日期参数异常:', detail);
        return;
      }
      this.currentDate = new Date(detail.fulldate);
      this.filterRecordsByDate(this.currentDate);
    },

    handleMonthSwitch({ month }) {
      this.currentDate = new Date(
        this.currentDate.getFullYear(),
        month - 1,
        this.currentDate.getDate()
      );
      this.loadAttendanceData();
    }
  }
};
</script>

<style lang="scss" scoped>
.stats-container {
  padding: 20rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.user-header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;

  .user-avatar {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 20rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .user-info {
    flex: 1;

    .user-name {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }

    .user-position {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.card-radius {
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 20rpx;
}

.no-data {
  padding: 40rpx;
  text-align: center;
  color: #999;
  background-color: #fff;
  border-radius: 16rpx;
}
</style>
