<template>
    <view class="page-container">


        <!-- 月份选择栏 -->
        <view class="month-bar">
            <view class="month-select" @click="showMonthPicker = true">
                <text class="month-text">{{ currentYear }}年{{ currentMonth }}月</text>
                <text class="month-arrow">▾</text>
            </view>
        </view>

        <!-- 日历区域 -->
        <view class="calendar-section">
            <view class="calendar-header">
                <text v-for="(day, index) in weekDays" :key="index" class="week-day">{{ day }}</text>
            </view>
            <view class="calendar-grid" :class="{ 'collapsed': !calendarExpanded }">
                <view v-for="(day, index) in calendarDays" :key="index" class="calendar-item" :class="{
                    'empty': !day.date,
                    'current': day.isCurrent,
                    'selected': day.isSelected,
                    'has-record': day.hasRecord
                }" @click="selectDate(day)">
                    <text v-if="day.date" class="day-num">{{ day.date }}</text>
                    <view v-if="day.hasRecord" class="record-dot"></view>
                </view>
            </view>
            <!-- 展开/收起箭头 -->
            <view class="calendar-toggle" @click="toggleCalendar">
                <text class="toggle-arrow" :class="{ 'expanded': calendarExpanded }">▼</text>
            </view>
        </view>

        <!-- 工时统计 -->
        <view class="stats-section">
            <view class="stats-bar">
                <view class="stats-icon">
                    <image class="icon-image" src="/static/login/clockIcon.png" mode="widthFix" />
                </view>
                <view class="stats-content">
                    <text class="stats-label">工时统计：</text>
                    <text class="stats-value">{{ formatHours(totalHours) }}</text>
                    <text v-if="totalHours < 8" class="stats-warning">（不足8小时上线要求）</text>
                </view>
            </view>
        </view>

        <!-- 当日工时详情 -->
        <view class="detail-section">
            <view class="detail-header">
                <text class="detail-title">工时：</text>
                <text class="detail-value">{{ formatHours(selectedDayHours) }}</text>
            </view>

            <!-- 空状态 -->
            <view v-if="!hasRecords" class="empty-state">
                <view class="empty-icon">📦</view>
                <text class="empty-text">暂无记录</text>
            </view>

            <!-- 记录列表 -->
            <view v-else-if="selectedDayRecords.length === 0" class="empty-state">
                <view class="empty-icon">📦</view>
                <text class="empty-text">暂无记录</text>
            </view>

            <view v-else class="record-list">
                <view v-for="(record, index) in selectedDayRecords" :key="index" class="record-item">
                    <view class="record-time">
                        <text class="time-start">{{ record.startTime }}</text>
                        <text class="time-arrow">→</text>
                        <text class="time-end">{{ record.endTime }}</text>
                    </view>
                    <view class="record-duration">
                        <text class="duration-text">时长：{{ record.duration }}</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 月份选择器弹窗 -->
        <u-popup :show="showMonthPicker" mode="bottom" :safe-area-inset-bottom="true">
            <view class="month-picker-container">
                <u-datetime-picker confirmColor="#fff" title="选择月份" ref="datetimePicker" :show="showMonthPicker"
                    v-model="value1" mode="year-month" @cancel="showMonthPicker = false" :formatter="formatter"
                    @confirm="handleConfirm"></u-datetime-picker>
            </view>
        </u-popup>
    </view>
</template>

<script>
export default {
    data() {
        return {
            value1: Number(new Date()),
            currentYear: 2025,
            currentMonth: 12,
            selectedYear: 2025,
            selectedMonth: 12,
            selectedDate: null,
            showMonthPicker: false,
            weekDays: ['日', '一', '二', '三', '四', '五', '六'],
            calendarDays: [],
            workRecords: [], // 模拟数据
            totalHours: 0,
            selectedDayHours: 0,
            selectedDayRecords: [],
            calendarExpanded: false, // 新增：日历展开状态
        }
    },
    computed: {
        hasRecords() {
            return this.workRecords.length > 0
        },
        monthList() {
            const list = []
            const now = new Date()
            const currentYear = now.getFullYear()
            const currentMonth = now.getMonth() + 1

            // 生成最近3年的月份列表
            for (let year = currentYear - 2; year <= currentYear; year++) {
                for (let month = 1; month <= 12; month++) {
                    if (year === currentYear && month > currentMonth) break
                    list.push({ year, month })
                }
            }
            return list.reverse()
        }
    },
    onLoad() {
        this.showMonthPicker = false
        // 初始化当前年月
        const now = new Date(this.value1)
        this.currentYear = now.getFullYear()
        this.currentMonth = now.getMonth() + 1
        this.selectedYear = this.currentYear
        this.selectedMonth = this.currentMonth
        this.selectedDate = now.getDate()

        this.generateCalendar()
        this.calculateTotalHours()
        this.loadSelectedDayRecords()
    },
    onReady() {
    },
    methods: {
        goBack() {
            uni.navigateBack()
        },
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`
            }
            if (type === 'month') {
                return `${value}月`
            }
            return value
        },
        handleConfirm(e) {
            this.showMonthPicker = false
            // 关键：更新 currentYear 和 currentMonth，日历才会变化
            const selectedDate = new Date(e.value)
            this.currentYear = selectedDate.getFullYear()
            this.currentMonth = selectedDate.getMonth() + 1
            this.selectedYear = this.currentYear
            this.selectedMonth = this.currentMonth
            // 判断是否选中当前月份
            const today = new Date()
            if (this.currentYear === today.getFullYear() && this.currentMonth === today.getMonth() + 1) {
                // 当前月份，选中今天
                this.selectedDate = today.getDate()
            } else {
                // 其他月份，不选中任何日期
                this.selectedDate = null
            }

            this.generateCalendar()
            this.calculateTotalHours()
            this.loadSelectedDayRecords()
        },

        generateCalendar() {
            const year = this.currentYear
            const month = this.currentMonth
            const firstDay = new Date(year, month - 1, 1)
            const lastDay = new Date(year, month, 0)
            const daysInMonth = lastDay.getDate()
            const startWeekDay = firstDay.getDay()

            this.calendarDays = []

            // 填充空白日期
            for (let i = 0; i < startWeekDay; i++) {
                this.calendarDays.push({ date: null, isCurrent: false, isSelected: false, hasRecord: false })
            }

            // 填充当月日期
            const today = new Date()
            for (let i = 1; i <= daysInMonth; i++) {
                const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(i).padStart(2, '0')}`
                const hasRecord = this.workRecords.some(item => item.date === dateStr)
                this.calendarDays.push({
                    date: i,
                    fullDate: dateStr,
                    isCurrent: today.getFullYear() === year && today.getMonth() + 1 === month && today.getDate() === i,
                    isSelected: this.selectedDate === i,
                    hasRecord: hasRecord
                })
            }
        },

        selectDate(day) {
            if (!day.date) return

            this.selectedDate = day.date
            this.calendarDays.forEach(d => {
                d.isSelected = d.date === day.date
            })

            this.loadSelectedDayRecords()
        },
        toggleCalendar() {
            this.calendarExpanded = !this.calendarExpanded
        },

        loadSelectedDayRecords() {
            const dateStr = `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}-${String(this.selectedDate).padStart(2, '0')}`
            const dayData = this.workRecords.find(item => item.date === dateStr)

            if (dayData) {
                this.selectedDayRecords = dayData.records
                this.selectedDayHours = this.calculateHours(dayData.records)
            } else {
                this.selectedDayRecords = []
                this.selectedDayHours = 0
            }
        },

        calculateHours(records) {
            let totalMinutes = 0
            records.forEach(record => {
                const match = record.duration.match(/(\d+)小时(\d+)分/)
                if (match) {
                    totalMinutes += parseInt(match[1]) * 60 + parseInt(match[2])
                }
            })
            return totalMinutes / 60
        },

        calculateTotalHours() {
            const monthRecords = this.workRecords.filter(item => {
                return item.date.startsWith(`${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}`)
            })

            let totalMinutes = 0
            monthRecords.forEach(item => {
                item.records.forEach(record => {
                    const match = record.duration.match(/(\d+)小时(\d+)分/)
                    if (match) {
                        totalMinutes += parseInt(match[1]) * 60 + parseInt(match[2])
                    }
                })
            })

            this.totalHours = totalMinutes / 60
        },

        formatHours(hours) {
            if (!hours || hours <= 0) return '--:--'
            const h = Math.floor(hours)
            const m = Math.round((hours - h) * 60)
            return `${h}小时${m}分`
        },

    }
}
</script>

<style lang="scss" scoped>
::v-deep .u-toolbar__title {
    font-weight: 500;
    font-size: 36rpx;
    color: #1D2129;
}

::v-deep .u-picker__view__column__item {
    font-weight: 400 !important;
    font-size: 28rpx;
    color: #1D2129
}

::v-deep .u-upload__success {
    display: none;
}

::v-deep .u-picker {
    bottom: 136rpx;
    background-color: #ffffff;
    position: relative;
}

::v-deep .u-toolbar__cancel__wrapper {
    width: 30rpx;
    height: 30rpx;
    position: absolute;
    right: 32rpx;
    background-image: url('/static/login/closeIcon.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;

    .u-toolbar__wrapper__cancel {
        width: 30rpx;
        height: 30rpx;

        span {
            display: none;
        }

    }
}

/* 关键：穿透隐藏原生 toolbar，只留插槽内容 */
.u-toolbar {
    z-index: 9999 !important;
    display: block !important;
}

::v-deep .u-toolbar__cancel__wrapper {
    color: #666;
}

::v-deep .u-toolbar__confirm__wrapper {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24rpx 48rpx;

    .u-toolbar__wrapper__confirm {
        width: 654rpx;
        height: 88rpx;
        background: #333335;
        border-radius: 60rpx 60rpx 60rpx 60rpx;

        font-weight: 400;
        font-size: 32rpx;
        color: #FFFFFF;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}



.page-container {
    min-height: 100vh;
    background-color: #f5f5f5;
}

.header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 60rpx 32rpx 24rpx;
    background-color: #fff;
}

.header-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.back-icon {
    font-size: 48rpx;
    color: #333;
}

.header-title {
    font-size: 34rpx;
    font-weight: 600;
    color: #1d2129;
}

.header-right {
    width: 60rpx;
}

.month-bar {
    background-color: #fff;
    padding: 20rpx 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
}

.month-select {
    display: flex;
    align-items: center;
    justify-content: center;
}

.month-text {
    font-size: 32rpx;
    color: #1d2129;
    font-weight: 500;
}

.month-arrow {
    font-size: 20rpx;
    color: #86909c;
    margin-left: 8rpx;
}

.calendar-section {
    background-color: #fff;
    margin-top: 16rpx;
    padding: 24rpx 32rpx;
}

.calendar-header {
    display: flex;
    margin-bottom: 20rpx;
}

.week-day {
    flex: 1;
    text-align: center;
    font-size: 26rpx;
    color: #86909c;
}

.calendar-grid {
    display: flex;
    flex-wrap: wrap;
}

/* 添加以下样式 */
.calendar-grid.collapsed {
    max-height: 160rpx;
    /* 只显示两行 */
    overflow: hidden;
}

.calendar-toggle {
    text-align: center;
    padding: 16rpx 0;
}

.toggle-arrow {
    font-size: 20rpx;
    color: #86909c;
    transition: transform 0.3s;
    display: inline-block;
}

.toggle-arrow.expanded {
    transform: rotate(180deg);
}

.calendar-item {
    width: calc(100% / 7);
    height: 80rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
}

.calendar-item.empty {
    pointer-events: none;
}

.calendar-item.current .day-num {
    background-color: #07c160;
    color: #fff;
    border-radius: 50%;
    width: 56rpx;
    height: 56rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.calendar-item.selected .day-num {
    border: 2rpx solid #07c160;
    border-radius: 50%;
    width: 52rpx;
    height: 52rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.day-num {
    font-size: 28rpx;
    color: #1d2129;
}

.record-dot {
    width: 8rpx;
    height: 8rpx;
    background-color: #ff7d00;
    border-radius: 50%;
    position: absolute;
    bottom: 8rpx;
}

.stats-section {
    background-color: #fff;
    margin-top: 16rpx;
    padding: 20rpx 32rpx;
}

.stats-bar {
    display: flex;
    align-items: center;
    padding: 16rpx 20rpx;
    background-color: #fff8ec;
    border-radius: 8rpx;
}

.stats-icon {
    width: 48rpx;
    height: 48rpx;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16rpx;
}

.icon-text {
    font-size: 24rpx;
}

.stats-content {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.stats-label {
    font-size: 28rpx;
    color: #86909c;
}

.stats-value {
    font-size: 28rpx;
    color: #ff7d00;
    font-weight: 500;
}

.stats-warning {
    font-size: 24rpx;
    color: #ff7d00;
    margin-left: 8rpx;
}

.detail-section {
    background-color: #fff;
    margin-top: 16rpx;
    padding: 24rpx 32rpx;
    min-height: 300rpx;
}

.detail-header {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
}

.detail-title {
    font-size: 28rpx;
    color: #86909c;
}

.detail-value {
    font-size: 32rpx;
    color: #1d2129;
    font-weight: 500;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80rpx 0;
}

.empty-icon {
    font-size: 120rpx;
    margin-bottom: 24rpx;
}

.empty-text {
    font-size: 28rpx;
    color: #86909c;
}

.record-list {
    margin-top: 16rpx;
}

.record-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
}

.record-item:last-child {
    border-bottom: none;
}

.record-time {
    display: flex;
    align-items: center;
}

.time-start,
.time-end {
    font-size: 28rpx;
    color: #1d2129;
}

.time-arrow {
    font-size: 24rpx;
    color: #86909c;
    margin: 0 16rpx;
}

.record-duration {
    margin-left: 24rpx;
}

.duration-text {
    font-size: 26rpx;
    color: #86909c;
}

/* 月份选择器弹窗 */
.month-picker-container {
    background-color: #fff;
    border-radius: 24rpx 24rpx 0 0;
    padding-bottom: env(safe-area-inset-bottom);
}

.picker-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
}

.picker-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #1d2129;
}

.picker-close {
    font-size: 48rpx;
    color: #86909c;
    line-height: 1;
}

.month-scroll {
    max-height: 600rpx;
    padding: 16rpx 32rpx;
}

.month-item {
    padding: 24rpx;
    border-radius: 8rpx;
    margin-bottom: 12rpx;
}

.month-item.active {
    background-color: #f0f9ff;
}

.month-item-text {
    font-size: 28rpx;
    color: #1d2129;
}

.month-item.active .month-item-text {
    color: #07c160;
    font-weight: 500;
}

.picker-footer {
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #f0f0f0;
}

.confirm-btn {
    background-color: #333;
    color: #fff;
    text-align: center;
    padding: 24rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 500;
}
</style>