<template>
    <div class="DateUpda">
        <div class="DateUpda_head">
            <div class="head_title">
                <img src="../assets/version.png" alt="">
                <div style="font-size: 14px;">版本说明</div>
            </div>
        </div>
        <div class="DateUpda_area">
            <div class="Date_left">
                <div class="D_l_title">
                    <img src="../assets/left_arrow.png" @click="handleClick" style="cursor: pointer;">
                    <div class="D_l_text">更新日历</div>
                </div>
                <div class="D_l_content">
                    <div class="D_l_head">
                        <div class="head_left" :class="{ 'active': isSelectActive }">选择年份：
                            <el-select v-model="value" placeholder="" style="width: 86px;" @focus="handleFocus"
                                @blur=handleBlur>
                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="head_right">
                            <div @click="prevPage" :class="{ 'active': isPrevActive }" class="prevBtn">上一页</div>
                            <div @click="nextPage" :class="{ 'active': isNextActive }" class="nextBtn">下一页</div>
                        </div>
                    </div>
                    <div class="calendars">
                        <div class="calendar" v-for="month in currentPageMonths" :key="month.month">
                            <div class="month">{{ month.name }}</div>
                            <div class="days">
                                <div class="day " v-for="day in month.days" :key="day"
                                    :class="{ highlight: isHighlighted(day, month.month) }"
                                    @click="selectDate(day, month.month)">{{ day }}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="Date_right">
                <div class="last_update">最新更新日期：<div>{{ latestDate || '暂无数据' }}</div>
                </div>
                <div class="update_count">最高月更新频次：<div style="font-family: DIN Alternate;">
                        {{ getMostUpdatedMonth.month ? `${getMostUpdatedMonth.month} 月 (${getMostUpdatedMonth.count} 次)`
                            : '暂无数据' }}
                    </div>
                </div>
                <div class="update_number">版本数量：<div style="font-family: DIN Alternate;">{{
                    filteredHighlightDates.length }}</div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { API_CONFIG } from '@/common/apiConfig';
import { mapGetters } from 'vuex';
export default {
    data() {
        return {
            options: [],
            value: '',
            months: [
                { month: 1, name: '1月', days: [] },
                { month: 2, name: '2月', days: [] },
                { month: 3, name: '3月', days: [] },
                { month: 4, name: '4月', days: [] },
                { month: 5, name: '5月', days: [] },
                { month: 6, name: '6月', days: [] },
                { month: 7, name: '7月', days: [] },
                { month: 8, name: '8月', days: [] },
                { month: 9, name: '9月', days: [] },
                { month: 10, name: '10月', days: [] },
                { month: 11, name: '11月', days: [] },
                { month: 12, name: '12月', days: [] }
            ],
            currentPage: 0,
            isPrevActive: false,
            isNextActive: false,
            isSelectActive: false,
            highlightDates: [],
            datesData: [],
            filteredData: [],
            filteredHighlightDates: [], // 筛选后的高亮日期
        }
    },
    computed: {
        ...mapGetters(["userid"]),
        totalPages() {
            return Math.ceil(this.months.length / 6); // 计算总页数，每页6个月
        },
        currentPageMonths() {
            const start = this.currentPage * 6;
            const end = start + 6;
            return this.months.slice(start, end); // 获取当前页显示的月份
        },
        latestDate() {
            if (!this.filteredHighlightDates || this.filteredHighlightDates.length === 0) {
                return null; // 如果没有高亮日期，返回 null
            }
            // 找到最新日期
            const latestDate = new Date(
                Math.max(...this.filteredHighlightDates.map(date => new Date(date)))
            );

            // 格式化日期为 'YYYY-MM-DD'
            const year = latestDate.getFullYear();
            const month = String(latestDate.getMonth() + 1).padStart(2, '0');
            const day = String(latestDate.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        getMostUpdatedMonth() {
            if (!this.filteredHighlightDates || this.filteredHighlightDates.length === 0) {
                return { month: null, count: 0 }; // 如果没有高亮日期，返回默认值
            }

            // 创建一个对象用于统计每个月的更新次数
            const monthCounts = {};

            this.filteredHighlightDates.forEach(date => {
                const month = date.substring(5, 7); // 提取月份部分，例如 '03' 表示 3 月
                monthCounts[month] = (monthCounts[month] || 0) + 1; // 累加该月份的计数
            });

            // 找到更新次数最多的月份
            let maxCount = 0;
            let mostUpdatedMonth = null;

            for (const [month, count] of Object.entries(monthCounts)) {
                if (count > maxCount) {
                    maxCount = count;
                    mostUpdatedMonth = month;
                }
            }

            return { month: mostUpdatedMonth, count: maxCount }; // 返回更新次数最多的月份和次数
        },
    },
    watch: {
        value(newYear) {
            if (newYear) {
                this.generateMonths(); // 根据选择的年份生成月份天数
                this.filterHighlightDates(); // 根据选择的年份筛选高亮日期
            }
        }
    },
    mounted() {
        this.generateYears();
        this.generateMonths();
        this.getDate();

    },
    methods: {
        handleClick() {
            // 处理返回操作，例如返回到上一个页面
            this.$router.go(-1);

        },
        generateYears() {
            const currentYear = new Date().getFullYear(); // 获取当前年份
            this.options = Array.from({ length: 5 }, (_, i) => {
                const year = currentYear - i;
                return { value: year.toString(), label: year.toString() };
            });
            this.value = currentYear.toString(); // 默认选择当前年份
        },
        generateMonths() {
            const selectedYear = parseInt(this.value, 10); // 获取选择的年份
            this.months.forEach(month => {
                const daysInMonth = new Date(selectedYear, month.month, 0).getDate(); // 获取当前月的天数
                month.days = Array.from({ length: daysInMonth }, (_, index) => index + 1); // 生成天数
            });
        },

        filterHighlightDates() {
            const selectedYear = this.value; // 当前选择的年份
            this.filteredHighlightDates = this.highlightDates.filter(date => date.startsWith(selectedYear));
        },
        isHighlighted(day, month) {
            // 将 day 转换为字符串格式的日期，例如 '2023-10-01'
            const dateStr = `${this.value}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
            return this.filteredHighlightDates.includes(dateStr);
        },
        prevPage() {
            if (this.currentPage > 0) {
                this.currentPage--;
                this.isPrevActive = true;
                this.isNextActive = false;
            }
        },
        nextPage() {
            if (this.currentPage < this.totalPages - 1) {
                this.currentPage++;
                this.isNextActive = true;
                this.isPrevActive = false;
            }
        },
        handleFocus() {
            this.isSelectActive = true;

        },
        handleBlur() {
            this.isSelectActive = false;
        },
        selectDate(day, month) {
            const dateString = `${this.value}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;

            // 检查日期是否在 filteredHighlightDates 中
            if (!this.filteredHighlightDates.includes(dateString)) {
                console.log(`日期 ${dateString} 未高亮，无法跳转`);
                return; // 如果日期未高亮，直接返回
            }
            const selectedData = this.datesData.find(item => item.update_at.startsWith(dateString));
            this.$router.push(
                {
                    path: '/versionInstr',
                    query: {
                        id: selectedData.id,
                        type: 1
                    }
                });

        },
        getDate() {
            let params = [
                {
                    functionName: "getDates",
                    uid: this.userid
                }
            ];
            this.$ajax
                .post(API_CONFIG.baseUrl, params)
                .then((res) => {
                    this.datesData = res.data[0];
                    // console.log("👉", this.highlightDates);
                    const versType = this.$route.query.versType;
                    console.log("我是type", versType);

                    this.filteredData = this.datesData.filter(item => item.update_version === versType);
                    console.log("filteredData", this.filteredData);

                    // 提取 update_at 字段并添加到 highlightDates 数组中
                    this.highlightDates = this.filteredData.map(item => item.update_at.substring(0, 10));
                    console.log("highlightDates", this.highlightDates);
                    this.filterHighlightDates();
                })
                .catch((err) => {
                    console.log(err);
                });
        }
    },
}
</script>
<style scoped>
html,
body {
    overflow: hidden;
    /* 禁止页面滚动 */
}

.DateUpda {
    height: 100%;
    overflow: hidden;
}

.DateUpda_area {
    display: flex;
    justify-content: space-between;
    height: calc(100% - 54px);
}

.DateUpda_head {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #E7E7E7;
    justify-content: space-between;
    height: 54px;
    background-color: #fff;
}

.head_title {
    display: flex;
    margin-left: 23px;
}

.head_title img {
    width: 16px;
    height: 16px;
    margin-right: 7px;
}

.Date_left {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin: 20px;
}

.D_l_title {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 16px;
    margin-top: 17px;
}

.D_l_text {
    font-size: 36px;
    font-weight: bold;
    margin-left: 19px;
}

.el-icon-arrow-left {
    font-size: 27px;
    font-weight: bold;
}

.D_l_content {
    width: 63vw;
    border-radius: 10px;
    background: #fff;
    box-shadow: 0px 0px 13px #ccd7ed;
    margin-top: 38px;
}

.Date_right {
    background: #fff;
    width: 34vw;
    height: 100%;
    border-left: 1px solid #dddada;
}

.last_update,
.update_count,
.update_number {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border: 1px solid black;
    border-radius: 6px;
    padding: 22px 17px;
    margin: 27px 49px;
    font-size: 14px;
}

.update_count div,
.update_number div {
    font-size: 48px;
    font-weight: bold;
    margin-left: 8px;
}

.D_l_head {
    display: flex;
    justify-content: space-between;
    margin: 23px 41px;
    margin-bottom: 5px;
}

.head_left {
    margin-left: 8px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border: 1px solid #DCDFE6;
    color: #c0c4cc;
    border-radius: 6px;
    padding: 0px 10px;
    cursor: pointer;
    width: 160px;
    font-size: 14px;
}

.head_left.active {
    border: 1px solid black;
    color: black;
}

.head_right {
    display: flex;
}

.prevBtn,
.nextBtn {
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #DCDFE6;
    color: #c0c4cc;
    border-radius: 6px;
    padding: 5px 17px;
    margin-right: 10px;
    cursor: pointer;
}

.prevBtn.active {
    border: 1px solid black;
    color: black;
}

.nextBtn.active {
    border: 1px solid black;
    color: black;
}

.calendars {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    gap: 7px;
    margin-bottom: 15px;
}

.calendar {
    border-radius: 10px;
    margin: 10px;
}

.month {
    font-size: 18px;
    font-weight: bold;
    padding: 10px 0;
}

.days {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 15px;
}

.day {
    width: 30px;
    height: 30px;
    background-color: #f1f1f1;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    font-size: 16px;
    font-weight: bold;
}

.day.highlight {
    background-color: #3681fc;
    color: white;
    cursor: pointer;
}


/* 使用深度选择器覆盖子组件样式 */
::v-deep .el-input__inner {
    border: none !important;
    box-shadow: none !important;
}

::v-deep .el-select .el-input__inner {
    color: black !important;
}

.head_left.active ::v-deep .el-select .el-input .el-select__caret {
    color: black !important;
    /* 激活状态下箭头颜色 */
}
</style>